Merge "InputDispatcher: Optimize count()"
diff --git a/cmds/installd/commands.c b/cmds/installd/commands.c
index 0a307c9..98c51cc 100644
--- a/cmds/installd/commands.c
+++ b/cmds/installd/commands.c
@@ -623,28 +623,6 @@
     return 0;
 }
 
-static void run_dexopt(int zip_fd, int odex_fd, const char* input_file_name,
-    const char* output_file_name)
-{
-    /* platform-specific flags affecting optimization and verification */
-    char dexopt_flags[PROPERTY_VALUE_MAX];
-    property_get("dalvik.vm.dexopt-flags", dexopt_flags, "");
-    ALOGV("dalvik.vm.dexopt-flags=%s\n", dexopt_flags);
-
-    static const char* DEX_OPT_BIN = "/system/bin/dexopt";
-    static const int MAX_INT_LEN = 12;      // '-'+10dig+'\0' -OR- 0x+8dig
-    char zip_num[MAX_INT_LEN];
-    char odex_num[MAX_INT_LEN];
-
-    sprintf(zip_num, "%d", zip_fd);
-    sprintf(odex_num, "%d", odex_fd);
-
-    ALOGV("Running %s in=%s out=%s\n", DEX_OPT_BIN, input_file_name, output_file_name);
-    execl(DEX_OPT_BIN, DEX_OPT_BIN, "--zip", zip_num, odex_num, input_file_name,
-        dexopt_flags, (char*) NULL);
-    ALOGE("execl(%s) failed: %s\n", DEX_OPT_BIN, strerror(errno));
-}
-
 static int split_count(const char *str)
 {
   char *ctx;
@@ -718,7 +696,7 @@
 }
 
 static void run_dex2oat(int zip_fd, int oat_fd, const char* input_file_name,
-    const char* output_file_name, const char *pkgname, const char *instruction_set,
+    const char* output_file_name, int swap_fd, const char *pkgname, const char *instruction_set,
     bool vm_safe_mode)
 {
     static const unsigned int MAX_INSTRUCTION_SET_LEN = 7;
@@ -748,6 +726,12 @@
     bool have_dex2oat_isa_features = property_get(dex2oat_isa_features_key,
                                                   dex2oat_isa_features, NULL) > 0;
 
+    char dex2oat_isa_variant_key[PROPERTY_KEY_MAX];
+    sprintf(dex2oat_isa_variant_key, "dalvik.vm.isa.%s.variant", instruction_set);
+    char dex2oat_isa_variant[PROPERTY_VALUE_MAX];
+    bool have_dex2oat_isa_variant = property_get(dex2oat_isa_variant_key,
+                                                 dex2oat_isa_variant, NULL) > 0;
+
     char dex2oat_flags[PROPERTY_VALUE_MAX];
     int dex2oat_flags_count = property_get("dalvik.vm.dex2oat-flags",
                                  dex2oat_flags, NULL) <= 0 ? 0 : split_count(dex2oat_flags);
@@ -771,19 +755,27 @@
     char oat_fd_arg[strlen("--oat-fd=") + MAX_INT_LEN];
     char oat_location_arg[strlen("--oat-location=") + PKG_PATH_MAX];
     char instruction_set_arg[strlen("--instruction-set=") + MAX_INSTRUCTION_SET_LEN];
+    char instruction_set_variant_arg[strlen("--instruction-set-variant=") + PROPERTY_VALUE_MAX];
     char instruction_set_features_arg[strlen("--instruction-set-features=") + PROPERTY_VALUE_MAX];
     char profile_file_arg[strlen("--profile-file=") + PKG_PATH_MAX];
     char top_k_profile_threshold_arg[strlen("--top-k-profile-threshold=") + PROPERTY_VALUE_MAX];
     char dex2oat_Xms_arg[strlen("-Xms") + PROPERTY_VALUE_MAX];
     char dex2oat_Xmx_arg[strlen("-Xmx") + PROPERTY_VALUE_MAX];
     char dex2oat_compiler_filter_arg[strlen("--compiler-filter=") + PROPERTY_VALUE_MAX];
+    bool have_dex2oat_swap_fd = false;
+    char dex2oat_swap_fd[strlen("--swap-fd=") + MAX_INT_LEN];
 
     sprintf(zip_fd_arg, "--zip-fd=%d", zip_fd);
     sprintf(zip_location_arg, "--zip-location=%s", input_file_name);
     sprintf(oat_fd_arg, "--oat-fd=%d", oat_fd);
     sprintf(oat_location_arg, "--oat-location=%s", output_file_name);
     sprintf(instruction_set_arg, "--instruction-set=%s", instruction_set);
+    sprintf(instruction_set_variant_arg, "--instruction-set-variant=%s", dex2oat_isa_variant);
     sprintf(instruction_set_features_arg, "--instruction-set-features=%s", dex2oat_isa_features);
+    if (swap_fd >= 0) {
+        have_dex2oat_swap_fd = true;
+        sprintf(dex2oat_swap_fd, "--swap-fd=%d", swap_fd);
+    }
 
     bool have_profile_file = false;
     bool have_top_k_profile_threshold = false;
@@ -822,12 +814,14 @@
     ALOGV("Running %s in=%s out=%s\n", DEX2OAT_BIN, input_file_name, output_file_name);
 
     char* argv[7  // program name, mandatory arguments and the final NULL
+               + (have_dex2oat_isa_variant ? 1 : 0)
                + (have_dex2oat_isa_features ? 1 : 0)
                + (have_profile_file ? 1 : 0)
                + (have_top_k_profile_threshold ? 1 : 0)
                + (have_dex2oat_Xms_flag ? 2 : 0)
                + (have_dex2oat_Xmx_flag ? 2 : 0)
                + (have_dex2oat_compiler_filter_flag ? 1 : 0)
+               + (have_dex2oat_swap_fd ? 1 : 0)
                + dex2oat_flags_count];
     int i = 0;
     argv[i++] = (char*)DEX2OAT_BIN;
@@ -836,6 +830,9 @@
     argv[i++] = oat_fd_arg;
     argv[i++] = oat_location_arg;
     argv[i++] = instruction_set_arg;
+    if (have_dex2oat_isa_variant) {
+        argv[i++] = instruction_set_variant_arg;
+    }
     if (have_dex2oat_isa_features) {
         argv[i++] = instruction_set_features_arg;
     }
@@ -856,6 +853,9 @@
     if (have_dex2oat_compiler_filter_flag) {
         argv[i++] = dex2oat_compiler_filter_arg;
     }
+    if (have_dex2oat_swap_fd) {
+        argv[i++] = dex2oat_swap_fd;
+    }
     if (dex2oat_flags_count) {
         i += split(dex2oat_flags, argv + i);
     }
@@ -892,6 +892,23 @@
     }
 }
 
+/*
+ * Whether dexopt should use a swap file when compiling an APK. If kAlwaysProvideSwapFile, do this
+ * on all devices (dex2oat will make a more informed decision itself, anyways). Otherwise, only do
+ * this on a low-mem device.
+ */
+static bool kAlwaysProvideSwapFile = true;
+
+static bool ShouldUseSwapFileForDexopt() {
+    if (kAlwaysProvideSwapFile) {
+        return true;
+    }
+
+    char low_mem_buf[PROPERTY_VALUE_MAX];
+    property_get("ro.config.low_ram", low_mem_buf, "");
+    return (strcmp(low_mem_buf, "true") == 0);
+}
+
 int dexopt(const char *apk_path, uid_t uid, bool is_public,
            const char *pkgname, const char *instruction_set,
            bool vm_safe_mode, bool is_patchoat)
@@ -899,25 +916,19 @@
     struct utimbuf ut;
     struct stat input_stat, dex_stat;
     char out_path[PKG_PATH_MAX];
-    char persist_sys_dalvik_vm_lib[PROPERTY_VALUE_MAX];
+    char swap_file_name[PKG_PATH_MAX];
     char *end;
     const char *input_file;
     char in_odex_path[PKG_PATH_MAX];
-    int res, input_fd=-1, out_fd=-1;
+    int res, input_fd=-1, out_fd=-1, swap_fd=-1;
 
+    // Early best-effort check whether we can fit the the path into our buffers.
+    // Note: the cache path will require an additional 5 bytes for ".swap", but we'll try to run
+    // without a swap file, if necessary.
     if (strlen(apk_path) >= (PKG_PATH_MAX - 8)) {
         return -1;
     }
 
-    /* The command to run depend on the value of persist.sys.dalvik.vm.lib */
-    property_get("persist.sys.dalvik.vm.lib.2", persist_sys_dalvik_vm_lib, "libart.so");
-
-    if (is_patchoat && strncmp(persist_sys_dalvik_vm_lib, "libart", 6) != 0) {
-        /* We may only patch if we are libart */
-        ALOGE("Patching is only supported in libart\n");
-        return -1;
-    }
-
     /* Before anything else: is there a .odex file?  If so, we have
      * precompiled the apk and there is nothing to do here.
      *
@@ -988,6 +999,28 @@
         create_profile_file(pkgname, uid);
     }
 
+    // Create a swap file if necessary.
+    if (!is_patchoat && ShouldUseSwapFileForDexopt()) {
+        // Make sure there really is enough space.
+        size_t out_len = strlen(out_path);
+        if (out_len + strlen(".swap") + 1 <= PKG_PATH_MAX) {
+            strcpy(swap_file_name, out_path);
+            strcpy(swap_file_name + strlen(out_path), ".swap");
+            unlink(swap_file_name);
+            swap_fd = open(swap_file_name, O_RDWR | O_CREAT | O_EXCL, 0600);
+            if (swap_fd < 0) {
+                // Could not create swap file. Optimistically go on and hope that we can compile
+                // without it.
+                ALOGE("installd could not create '%s' for swap during dexopt\n", swap_file_name);
+            } else {
+                // Immediately unlink. We don't really want to hit flash.
+                unlink(swap_file_name);
+            }
+        } else {
+            // Swap file path is too long. Try to run without.
+            ALOGE("installd could not create swap file for path %s during dexopt\n", out_path);
+        }
+    }
 
     ALOGV("DexInv: --- BEGIN '%s' ---\n", input_file);
 
@@ -1022,17 +1055,11 @@
             exit(67);
         }
 
-        if (strncmp(persist_sys_dalvik_vm_lib, "libdvm", 6) == 0) {
-            run_dexopt(input_fd, out_fd, input_file, out_path);
-        } else if (strncmp(persist_sys_dalvik_vm_lib, "libart", 6) == 0) {
-            if (is_patchoat) {
-                run_patchoat(input_fd, out_fd, input_file, out_path, pkgname, instruction_set);
-            } else {
-                run_dex2oat(input_fd, out_fd, input_file, out_path, pkgname, instruction_set,
-                            vm_safe_mode);
-            }
+        if (is_patchoat) {
+            run_patchoat(input_fd, out_fd, input_file, out_path, pkgname, instruction_set);
         } else {
-            exit(69);   /* Unexpected persist.sys.dalvik.vm.lib value */
+            run_dex2oat(input_fd, out_fd, input_file, out_path, swap_fd, pkgname, instruction_set,
+                        vm_safe_mode);
         }
         exit(68);   /* only get here on exec failure */
     } else {
@@ -1051,6 +1078,9 @@
 
     close(out_fd);
     close(input_fd);
+    if (swap_fd != -1) {
+        close(swap_fd);
+    }
     return 0;
 
 fail:
@@ -1064,6 +1094,21 @@
     return -1;
 }
 
+int mark_boot_complete(const char* instruction_set)
+{
+  char boot_marker_path[PKG_PATH_MAX];
+  sprintf(boot_marker_path,"%s%s/.booting", DALVIK_CACHE_PREFIX, instruction_set);
+
+  ALOGV("mark_boot_complete : %s", boot_marker_path);
+  if (unlink(boot_marker_path) != 0) {
+      ALOGE("Unable to unlink boot marker at %s, error=%s", boot_marker_path,
+            strerror(errno));
+      return -1;
+  }
+
+  return 0;
+}
+
 void mkinnerdirs(char* path, int basepos, mode_t mode, int uid, int gid,
         struct stat* statbuf)
 {
diff --git a/cmds/installd/installd.c b/cmds/installd/installd.c
index 4864516..4dd83ae 100644
--- a/cmds/installd/installd.c
+++ b/cmds/installd/installd.c
@@ -42,6 +42,11 @@
     return dexopt(arg[0], atoi(arg[1]), atoi(arg[2]), arg[3], arg[4], atoi(arg[5]), 0);
 }
 
+static int do_mark_boot_complete(char **arg, char reply[REPLY_MAX] __unused)
+{
+    return mark_boot_complete(arg[0] /* instruction set */);
+}
+
 static int do_move_dex(char **arg, char reply[REPLY_MAX] __unused)
 {
     return move_dex(arg[0], arg[1], arg[2]); /* src, dst, instruction_set */
@@ -160,6 +165,7 @@
     { "ping",                 0, do_ping },
     { "install",              4, do_install },
     { "dexopt",               6, do_dexopt },
+    { "markbootcomplete",     1, do_mark_boot_complete },
     { "movedex",              3, do_move_dex },
     { "rmdex",                2, do_rm_dex },
     { "remove",               2, do_remove },
@@ -249,7 +255,9 @@
                 goto done;
             }
         }
-        cmd++;
+        if (*cmd) {
+          cmd++;
+        }
     }
 
     for (i = 0; i < sizeof(cmds) / sizeof(cmds[0]); i++) {
diff --git a/cmds/installd/installd.h b/cmds/installd/installd.h
index 36c3e8c..a9a1999 100644
--- a/cmds/installd/installd.h
+++ b/cmds/installd/installd.h
@@ -40,7 +40,7 @@
 
 #include <private/android_filesystem_config.h>
 
-#if INCLUDE_SYS_MOUNT_FOR_STATFS
+#if defined(__APPLE__)
 #include <sys/mount.h>
 #else
 #include <sys/statfs.h>
@@ -221,6 +221,7 @@
 int free_cache(int64_t free_size);
 int dexopt(const char *apk_path, uid_t uid, bool is_public, const char *pkgName,
            const char *instruction_set, bool vm_safe_mode, bool should_relocate);
+int mark_boot_complete(const char *instruction_set);
 int movefiles();
 int linklib(const char* target, const char* source, int userId);
 int idmap(const char *target_path, const char *overlay_path, uid_t uid);
diff --git a/include/binder/IInterface.h b/include/binder/IInterface.h
index 5f9f69c..4ce3613 100644
--- a/include/binder/IInterface.h
+++ b/include/binder/IInterface.h
@@ -28,9 +28,9 @@
 {
 public:
             IInterface();
-            sp<IBinder>         asBinder();
-            sp<const IBinder>   asBinder() const;
-            
+            static sp<IBinder>  asBinder(const IInterface*);
+            static sp<IBinder>  asBinder(const sp<IInterface>&);
+
 protected:
     virtual                     ~IInterface();
     virtual IBinder*            onAsBinder() = 0;
diff --git a/include/binder/IPCThreadState.h b/include/binder/IPCThreadState.h
index 6e0c01b..60c2242 100644
--- a/include/binder/IPCThreadState.h
+++ b/include/binder/IPCThreadState.h
@@ -22,7 +22,7 @@
 #include <binder/ProcessState.h>
 #include <utils/Vector.h>
 
-#ifdef HAVE_WIN32_PROC
+#if defined(_WIN32)
 typedef  int  uid_t;
 #endif
 
@@ -39,8 +39,8 @@
             
             status_t            clearLastError();
 
-            int                 getCallingPid() const;
-            int                 getCallingUid() const;
+            pid_t               getCallingPid() const;
+            uid_t               getCallingUid() const;
 
             void                setStrictModePolicy(int32_t policy);
             int32_t             getStrictModePolicy() const;
diff --git a/include/binder/Parcel.h b/include/binder/Parcel.h
index 2ee99f8..fee8090 100644
--- a/include/binder/Parcel.h
+++ b/include/binder/Parcel.h
@@ -94,6 +94,7 @@
     void*               writeInplace(size_t len);
     status_t            writeUnpadded(const void* data, size_t len);
     status_t            writeInt32(int32_t val);
+    status_t            writeUint32(uint32_t val);
     status_t            writeInt64(int64_t val);
     status_t            writeFloat(float val);
     status_t            writeDouble(double val);
@@ -152,6 +153,8 @@
     const void*         readInplace(size_t len) const;
     int32_t             readInt32() const;
     status_t            readInt32(int32_t *pArg) const;
+    uint32_t            readUint32() const;
+    status_t            readUint32(uint32_t *pArg) const;
     int64_t             readInt64() const;
     status_t            readInt64(int64_t *pArg) const;
     float               readFloat() const;
diff --git a/include/gui/BufferItemConsumer.h b/include/gui/BufferItemConsumer.h
index 5494ff1..869b470 100644
--- a/include/gui/BufferItemConsumer.h
+++ b/include/gui/BufferItemConsumer.h
@@ -95,7 +95,7 @@
     // setDefaultBufferFormat allows the BufferQueue to create
     // GraphicBuffers of a defaultFormat if no format is specified
     // in dequeueBuffer
-    status_t setDefaultBufferFormat(uint32_t defaultFormat);
+    status_t setDefaultBufferFormat(PixelFormat defaultFormat);
 };
 
 } // namespace android
diff --git a/include/gui/BufferQueueConsumer.h b/include/gui/BufferQueueConsumer.h
index 1912ed0..898c451 100644
--- a/include/gui/BufferQueueConsumer.h
+++ b/include/gui/BufferQueueConsumer.h
@@ -125,9 +125,8 @@
 
     // setDefaultBufferFormat allows the BufferQueue to create
     // GraphicBuffers of a defaultFormat if no format is specified
-    // in dequeueBuffer.  Formats are enumerated in graphics.h; the
-    // initial default is HAL_PIXEL_FORMAT_RGBA_8888.
-    virtual status_t setDefaultBufferFormat(uint32_t defaultFormat);
+    // in dequeueBuffer. The initial default is HAL_PIXEL_FORMAT_RGBA_8888.
+    virtual status_t setDefaultBufferFormat(PixelFormat defaultFormat);
 
     // setConsumerUsageBits will turn on additional usage bits for dequeueBuffer.
     // These are merged with the bits passed to dequeueBuffer.  The values are
diff --git a/include/gui/BufferQueueCore.h b/include/gui/BufferQueueCore.h
index 1d975c0..b23cb08 100644
--- a/include/gui/BufferQueueCore.h
+++ b/include/gui/BufferQueueCore.h
@@ -199,15 +199,15 @@
 
     // mDefaultBufferFormat can be set so it will override the buffer format
     // when it isn't specified in dequeueBuffer.
-    uint32_t mDefaultBufferFormat;
+    PixelFormat mDefaultBufferFormat;
 
     // mDefaultWidth holds the default width of allocated buffers. It is used
     // in dequeueBuffer if a width and height of 0 are specified.
-    int mDefaultWidth;
+    uint32_t mDefaultWidth;
 
     // mDefaultHeight holds the default height of allocated buffers. It is used
     // in dequeueBuffer if a width and height of 0 are specified.
-    int mDefaultHeight;
+    uint32_t mDefaultHeight;
 
     // mDefaultMaxBufferCount is the default limit on the number of buffers that
     // will be allocated at one time. This default limit is set by the consumer.
diff --git a/include/gui/BufferQueueProducer.h b/include/gui/BufferQueueProducer.h
index 3fc5de2..34c32dc 100644
--- a/include/gui/BufferQueueProducer.h
+++ b/include/gui/BufferQueueProducer.h
@@ -73,9 +73,7 @@
     // updateTexImage() is called.  If width and height are both zero, the
     // default values specified by setDefaultBufferSize() are used instead.
     //
-    // The pixel formats are enumerated in graphics.h, e.g.
-    // HAL_PIXEL_FORMAT_RGBA_8888.  If the format is 0, the default format
-    // will be used.
+    // If the format is 0, the default format will be used.
     //
     // The usage argument specifies gralloc buffer usage flags.  The values
     // are enumerated in gralloc.h, e.g. GRALLOC_USAGE_HW_RENDER.  These
@@ -93,8 +91,9 @@
     //
     // In both cases, the producer will need to call requestBuffer to get a
     // GraphicBuffer handle for the returned slot.
-    virtual status_t dequeueBuffer(int *outSlot, sp<Fence>* outFence, bool async,
-            uint32_t width, uint32_t height, uint32_t format, uint32_t usage);
+    virtual status_t dequeueBuffer(int *outSlot, sp<Fence>* outFence,
+            bool async, uint32_t width, uint32_t height, PixelFormat format,
+            uint32_t usage);
 
     // See IGraphicBufferProducer::detachBuffer
     virtual status_t detachBuffer(int slot);
@@ -171,7 +170,7 @@
 
     // See IGraphicBufferProducer::allocateBuffers
     virtual void allocateBuffers(bool async, uint32_t width, uint32_t height,
-            uint32_t format, uint32_t usage);
+            PixelFormat format, uint32_t usage);
 
 private:
     // This is required by the IBinder::DeathRecipient interface
diff --git a/include/gui/CpuConsumer.h b/include/gui/CpuConsumer.h
index 6f4c2ec..3414ede 100644
--- a/include/gui/CpuConsumer.h
+++ b/include/gui/CpuConsumer.h
@@ -67,7 +67,7 @@
     // Create a new CPU consumer. The maxLockedBuffers parameter specifies
     // how many buffers can be locked for user access at the same time.
     CpuConsumer(const sp<IGraphicBufferConsumer>& bq,
-            uint32_t maxLockedBuffers, bool controlledByApp = false);
+            size_t maxLockedBuffers, bool controlledByApp = false);
 
     virtual ~CpuConsumer();
 
@@ -82,10 +82,9 @@
     status_t setDefaultBufferSize(uint32_t width, uint32_t height);
 
     // setDefaultBufferFormat allows CpuConsumer's BufferQueue to create buffers
-    // of a defaultFormat if no format is specified by producer. Formats are
-    // enumerated in graphics.h; the initial default is
-    // HAL_PIXEL_FORMAT_RGBA_8888.
-    status_t setDefaultBufferFormat(uint32_t defaultFormat);
+    // of a defaultFormat if no format is specified by producer.
+    // The initial default is PIXEL_FORMAT_RGBA_8888.
+    status_t setDefaultBufferFormat(PixelFormat defaultFormat);
 
     // Gets the next graphics buffer from the producer and locks it for CPU use,
     // filling out the passed-in locked buffer structure with the native pointer
@@ -106,9 +105,9 @@
 
   private:
     // Maximum number of buffers that can be locked at a time
-    uint32_t mMaxLockedBuffers;
+    size_t mMaxLockedBuffers;
 
-    status_t releaseAcquiredBufferLocked(int lockedIdx);
+    status_t releaseAcquiredBufferLocked(size_t lockedIdx);
 
     virtual void freeBufferLocked(int slotIndex);
 
@@ -129,7 +128,7 @@
     Vector<AcquiredBuffer> mAcquiredBuffers;
 
     // Count of currently locked buffers
-    uint32_t mCurrentLockedBuffers;
+    size_t mCurrentLockedBuffers;
 
 };
 
diff --git a/include/gui/GLConsumer.h b/include/gui/GLConsumer.h
index f91fe46..053d1ed 100644
--- a/include/gui/GLConsumer.h
+++ b/include/gui/GLConsumer.h
@@ -150,7 +150,7 @@
     //
     // The frame number is an incrementing counter set to 0 at the creation of
     // the BufferQueue associated with this consumer.
-    int64_t getFrameNumber();
+    uint64_t getFrameNumber();
 
     // setDefaultBufferSize is used to set the size of buffers returned by
     // requestBuffers when a with and height of zero is requested.
@@ -197,7 +197,7 @@
 
     // These functions call the corresponding BufferQueue implementation
     // so the refactoring can proceed smoothly
-    status_t setDefaultBufferFormat(uint32_t defaultFormat);
+    status_t setDefaultBufferFormat(PixelFormat defaultFormat);
     status_t setConsumerUsageBits(uint32_t usage);
     status_t setTransformHint(uint32_t hint);
 
@@ -254,7 +254,7 @@
         return releaseBufferLocked(slot, graphicBuffer, mEglDisplay, eglFence);
     }
 
-    static bool isExternalFormat(uint32_t format);
+    static bool isExternalFormat(PixelFormat format);
 
     // This releases the buffer in the slot referenced by mCurrentTexture,
     // then updates state to refer to the BufferItem, which must be a
@@ -391,7 +391,7 @@
 
     // mCurrentFrameNumber is the frame counter for the current texture.
     // It gets set each time updateTexImage is called.
-    int64_t mCurrentFrameNumber;
+    uint64_t mCurrentFrameNumber;
 
     uint32_t mDefaultWidth, mDefaultHeight;
 
diff --git a/include/gui/GraphicBufferAlloc.h b/include/gui/GraphicBufferAlloc.h
index b08750c..69fe51e 100644
--- a/include/gui/GraphicBufferAlloc.h
+++ b/include/gui/GraphicBufferAlloc.h
@@ -33,8 +33,9 @@
 public:
     GraphicBufferAlloc();
     virtual ~GraphicBufferAlloc();
-    virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t w, uint32_t h,
-        PixelFormat format, uint32_t usage, status_t* error);
+    virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t width,
+            uint32_t height, PixelFormat format, uint32_t usage,
+            status_t* error);
 };
 
 
diff --git a/include/gui/IGraphicBufferAlloc.h b/include/gui/IGraphicBufferAlloc.h
index cee41d9..f3c46ec 100644
--- a/include/gui/IGraphicBufferAlloc.h
+++ b/include/gui/IGraphicBufferAlloc.h
@@ -45,10 +45,10 @@
 class BnGraphicBufferAlloc : public BnInterface<IGraphicBufferAlloc>
 {
 public:
-    virtual status_t    onTransact( uint32_t code,
-                                    const Parcel& data,
-                                    Parcel* reply,
-                                    uint32_t flags = 0);
+    virtual status_t onTransact(uint32_t code,
+                                const Parcel& data,
+                                Parcel* reply,
+                                uint32_t flags = 0);
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/gui/IGraphicBufferConsumer.h b/include/gui/IGraphicBufferConsumer.h
index 15f51fe..9ac23c2 100644
--- a/include/gui/IGraphicBufferConsumer.h
+++ b/include/gui/IGraphicBufferConsumer.h
@@ -25,6 +25,7 @@
 #include <utils/Timers.h>
 
 #include <binder/IInterface.h>
+#include <ui/PixelFormat.h>
 #include <ui/Rect.h>
 
 #include <EGL/egl.h>
@@ -280,11 +281,11 @@
 
     // setDefaultBufferFormat allows the BufferQueue to create
     // GraphicBuffers of a defaultFormat if no format is specified
-    // in dequeueBuffer.  Formats are enumerated in graphics.h; the
-    // initial default is HAL_PIXEL_FORMAT_RGBA_8888.
+    // in dequeueBuffer.
+    // The initial default is PIXEL_FORMAT_RGBA_8888.
     //
     // Return of a value other than NO_ERROR means an unknown error has occurred.
-    virtual status_t setDefaultBufferFormat(uint32_t defaultFormat) = 0;
+    virtual status_t setDefaultBufferFormat(PixelFormat defaultFormat) = 0;
 
     // setConsumerUsageBits will turn on additional usage bits for dequeueBuffer.
     // These are merged with the bits passed to dequeueBuffer.  The values are
diff --git a/include/gui/IGraphicBufferProducer.h b/include/gui/IGraphicBufferProducer.h
index 4e9e810..4d3cd9a 100644
--- a/include/gui/IGraphicBufferProducer.h
+++ b/include/gui/IGraphicBufferProducer.h
@@ -134,9 +134,7 @@
     // updateTexImage() is called.  If width and height are both zero, the
     // default values specified by setDefaultBufferSize() are used instead.
     //
-    // The pixel formats are enumerated in <graphics.h>, e.g.
-    // HAL_PIXEL_FORMAT_RGBA_8888.  If the format is 0, the default format
-    // will be used.
+    // If the format is 0, the default format will be used.
     //
     // The usage argument specifies gralloc buffer usage flags.  The values
     // are enumerated in <gralloc.h>, e.g. GRALLOC_USAGE_HW_RENDER.  These
@@ -167,7 +165,7 @@
     // All other negative values are an unknown error returned downstream
     // from the graphics allocator (typically errno).
     virtual status_t dequeueBuffer(int* slot, sp<Fence>* fence, bool async,
-            uint32_t w, uint32_t h, uint32_t format, uint32_t usage) = 0;
+            uint32_t w, uint32_t h, PixelFormat format, uint32_t usage) = 0;
 
     // detachBuffer attempts to remove all ownership of the buffer in the given
     // slot from the buffer queue. If this call succeeds, the slot will be
@@ -448,7 +446,7 @@
     // dequeueBuffer. If there are already the maximum number of buffers
     // allocated, this function has no effect.
     virtual void allocateBuffers(bool async, uint32_t width, uint32_t height,
-            uint32_t format, uint32_t usage) = 0;
+            PixelFormat format, uint32_t usage) = 0;
 };
 
 // ----------------------------------------------------------------------------
diff --git a/include/gui/ISurfaceComposer.h b/include/gui/ISurfaceComposer.h
index f04a848..8c3d49e 100644
--- a/include/gui/ISurfaceComposer.h
+++ b/include/gui/ISurfaceComposer.h
@@ -28,7 +28,6 @@
 #include <binder/IInterface.h>
 
 #include <ui/FrameStats.h>
-#include <ui/PixelFormat.h>
 
 #include <gui/IGraphicBufferAlloc.h>
 #include <gui/ISurfaceComposerClient.h>
diff --git a/include/gui/Sensor.h b/include/gui/Sensor.h
index 28a08e2..27a215e 100644
--- a/include/gui/Sensor.h
+++ b/include/gui/Sensor.h
@@ -67,12 +67,12 @@
     int32_t getMinDelay() const;
     nsecs_t getMinDelayNs() const;
     int32_t getVersion() const;
-    int32_t getFifoReservedEventCount() const;
-    int32_t getFifoMaxEventCount() const;
+    uint32_t getFifoReservedEventCount() const;
+    uint32_t getFifoMaxEventCount() const;
     const String8& getStringType() const;
     const String8& getRequiredPermission() const;
     int32_t getMaxDelay() const;
-    int32_t getFlags() const;
+    uint32_t getFlags() const;
     bool isWakeUpSensor() const;
     int32_t getReportingMode() const;
 
@@ -93,12 +93,12 @@
     float   mPower;
     int32_t mMinDelay;
     int32_t mVersion;
-    int32_t mFifoReservedEventCount;
-    int32_t mFifoMaxEventCount;
+    uint32_t mFifoReservedEventCount;
+    uint32_t mFifoMaxEventCount;
     String8 mStringType;
     String8 mRequiredPermission;
     int32_t mMaxDelay;
-    int32_t mFlags;
+    uint32_t mFlags;
     static void flattenString8(void*& buffer, size_t& size, const String8& string8);
     static bool unflattenString8(void const*& buffer, size_t& size, String8& outputString8);
 };
diff --git a/include/gui/Surface.h b/include/gui/Surface.h
index f2cf018..98f4f4f 100644
--- a/include/gui/Surface.h
+++ b/include/gui/Surface.h
@@ -160,12 +160,12 @@
     virtual int connect(int api);
     virtual int disconnect(int api);
     virtual int setBufferCount(int bufferCount);
-    virtual int setBuffersDimensions(int w, int h);
-    virtual int setBuffersUserDimensions(int w, int h);
-    virtual int setBuffersFormat(int format);
+    virtual int setBuffersDimensions(uint32_t width, uint32_t height);
+    virtual int setBuffersUserDimensions(uint32_t width, uint32_t height);
+    virtual int setBuffersFormat(PixelFormat format);
     virtual int setScalingMode(int mode);
-    virtual int setBuffersTransform(int transform);
-    virtual int setBuffersStickyTransform(int transform);
+    virtual int setBuffersTransform(uint32_t transform);
+    virtual int setBuffersStickyTransform(uint32_t transform);
     virtual int setBuffersTimestamp(int64_t timestamp);
     virtual int setCrop(Rect const* rect);
     virtual int setUsage(uint32_t reqUsage);
@@ -211,7 +211,7 @@
 
     // mReqFormat is the buffer pixel format that will be requested at the next
     // deuque operation. It is initialized to PIXEL_FORMAT_RGBA_8888.
-    uint32_t mReqFormat;
+    PixelFormat mReqFormat;
 
     // mReqUsage is the set of buffer usage flags that will be requested
     // at the next deuque operation. It is initialized to 0.
@@ -240,23 +240,23 @@
     // from being set by the compositor.
     uint32_t mStickyTransform;
 
-     // mDefaultWidth is default width of the buffers, regardless of the
-     // native_window_set_buffers_dimensions call.
-     uint32_t mDefaultWidth;
+    // mDefaultWidth is default width of the buffers, regardless of the
+    // native_window_set_buffers_dimensions call.
+    uint32_t mDefaultWidth;
 
-     // mDefaultHeight is default height of the buffers, regardless of the
-     // native_window_set_buffers_dimensions call.
-     uint32_t mDefaultHeight;
+    // mDefaultHeight is default height of the buffers, regardless of the
+    // native_window_set_buffers_dimensions call.
+    uint32_t mDefaultHeight;
 
-     // mUserWidth, if non-zero, is an application-specified override
-     // of mDefaultWidth.  This is lower priority than the width set by
-     // native_window_set_buffers_dimensions.
-     uint32_t mUserWidth;
+    // mUserWidth, if non-zero, is an application-specified override
+    // of mDefaultWidth.  This is lower priority than the width set by
+    // native_window_set_buffers_dimensions.
+    uint32_t mUserWidth;
 
-     // mUserHeight, if non-zero, is an application-specified override
-     // of mDefaultHeight.  This is lower priority than the height set
-     // by native_window_set_buffers_dimensions.
-     uint32_t mUserHeight;
+    // mUserHeight, if non-zero, is an application-specified override
+    // of mDefaultHeight.  This is lower priority than the height set
+    // by native_window_set_buffers_dimensions.
+    uint32_t mUserHeight;
 
     // mTransformHint is the transform probably applied to buffers of this
     // window. this is only a hint, actual transform may differ.
diff --git a/include/gui/SurfaceComposerClient.h b/include/gui/SurfaceComposerClient.h
index 4cbfc09..37d953e 100644
--- a/include/gui/SurfaceComposerClient.h
+++ b/include/gui/SurfaceComposerClient.h
@@ -127,7 +127,7 @@
     status_t    show(const sp<IBinder>& id);
     status_t    setFlags(const sp<IBinder>& id, uint32_t flags, uint32_t mask);
     status_t    setTransparentRegionHint(const sp<IBinder>& id, const Region& transparent);
-    status_t    setLayer(const sp<IBinder>& id, int32_t layer);
+    status_t    setLayer(const sp<IBinder>& id, uint32_t layer);
     status_t    setAlpha(const sp<IBinder>& id, float alpha=1.0f);
     status_t    setMatrix(const sp<IBinder>& id, float dsdx, float dtdx, float dsdy, float dtdy);
     status_t    setPosition(const sp<IBinder>& id, float x, float y);
diff --git a/include/gui/SurfaceControl.h b/include/gui/SurfaceControl.h
index 84fb9f9..9f62f7c 100644
--- a/include/gui/SurfaceControl.h
+++ b/include/gui/SurfaceControl.h
@@ -57,8 +57,8 @@
     // release surface data from java
     void        clear();
 
-    status_t    setLayerStack(int32_t layerStack);
-    status_t    setLayer(int32_t layer);
+    status_t    setLayerStack(uint32_t layerStack);
+    status_t    setLayer(uint32_t layer);
     status_t    setPosition(float x, float y);
     status_t    setSize(uint32_t w, uint32_t h);
     status_t    hide();
diff --git a/include/ui/Fence.h b/include/ui/Fence.h
index 20466b6..b431bd5 100644
--- a/include/ui/Fence.h
+++ b/include/ui/Fence.h
@@ -65,7 +65,7 @@
     // before the fence signals then -ETIME is returned.  A timeout of
     // TIMEOUT_NEVER may be used to indicate that the call should wait
     // indefinitely for the fence to signal.
-    status_t wait(unsigned int timeout);
+    status_t wait(int timeout);
 
     // waitForever is a convenience function for waiting forever for a fence to
     // signal (just like wait(TIMEOUT_NEVER)), but issuing an error to the
diff --git a/include/ui/FramebufferNativeWindow.h b/include/ui/FramebufferNativeWindow.h
index 5cd8101..6b66d5f 100644
--- a/include/ui/FramebufferNativeWindow.h
+++ b/include/ui/FramebufferNativeWindow.h
@@ -14,11 +14,13 @@
  * limitations under the License.
  */
 
+#ifndef INCLUDED_FROM_FRAMEBUFFER_NATIVE_WINDOW_CPP
+#warning "FramebufferNativeWindow is deprecated"
+#endif
+
 #ifndef ANDROID_FRAMEBUFFER_NATIVE_WINDOW_H
 #define ANDROID_FRAMEBUFFER_NATIVE_WINDOW_H
 
-#warning "FramebufferNativeWindow is deprecated"
-
 #include <stdint.h>
 #include <sys/types.h>
 
diff --git a/include/ui/GraphicBuffer.h b/include/ui/GraphicBuffer.h
index 7630faa..cea94fc 100644
--- a/include/ui/GraphicBuffer.h
+++ b/include/ui/GraphicBuffer.h
@@ -49,7 +49,7 @@
         USAGE_SW_READ_RARELY    = GRALLOC_USAGE_SW_READ_RARELY,
         USAGE_SW_READ_OFTEN     = GRALLOC_USAGE_SW_READ_OFTEN,
         USAGE_SW_READ_MASK      = GRALLOC_USAGE_SW_READ_MASK,
-        
+
         USAGE_SW_WRITE_NEVER    = GRALLOC_USAGE_SW_WRITE_NEVER,
         USAGE_SW_WRITE_RARELY   = GRALLOC_USAGE_SW_WRITE_RARELY,
         USAGE_SW_WRITE_OFTEN    = GRALLOC_USAGE_SW_WRITE_OFTEN,
@@ -72,11 +72,13 @@
     GraphicBuffer();
 
     // creates w * h buffer
-    GraphicBuffer(uint32_t w, uint32_t h, PixelFormat format, uint32_t usage);
+    GraphicBuffer(uint32_t inWidth, uint32_t inHeight, PixelFormat inFormat,
+            uint32_t inUsage);
 
     // create a buffer from an existing handle
-    GraphicBuffer(uint32_t w, uint32_t h, PixelFormat format, uint32_t usage,
-            uint32_t stride, native_handle_t* handle, bool keepOwnership);
+    GraphicBuffer(uint32_t inWidth, uint32_t inHeight, PixelFormat inFormat,
+            uint32_t inUsage, uint32_t inStride, native_handle_t* inHandle,
+            bool keepOwnership);
 
     // create a buffer from an existing ANativeWindowBuffer
     GraphicBuffer(ANativeWindowBuffer* buffer, bool keepOwnership);
@@ -84,26 +86,31 @@
     // return status
     status_t initCheck() const;
 
-    uint32_t getWidth() const           { return width; }
-    uint32_t getHeight() const          { return height; }
-    uint32_t getStride() const          { return stride; }
-    uint32_t getUsage() const           { return usage; }
+    uint32_t getWidth() const           { return static_cast<uint32_t>(width); }
+    uint32_t getHeight() const          { return static_cast<uint32_t>(height); }
+    uint32_t getStride() const          { return static_cast<uint32_t>(stride); }
+    uint32_t getUsage() const           { return static_cast<uint32_t>(usage); }
     PixelFormat getPixelFormat() const  { return format; }
     Rect getBounds() const              { return Rect(width, height); }
     uint64_t getId() const              { return mId; }
 
-    status_t reallocate(uint32_t w, uint32_t h, PixelFormat f, uint32_t usage);
+    status_t reallocate(uint32_t inWidth, uint32_t inHeight,
+            PixelFormat inFormat, uint32_t inUsage);
 
-    status_t lock(uint32_t usage, void** vaddr);
-    status_t lock(uint32_t usage, const Rect& rect, void** vaddr);
+    status_t lock(uint32_t inUsage, void** vaddr);
+    status_t lock(uint32_t inUsage, const Rect& rect, void** vaddr);
     // For HAL_PIXEL_FORMAT_YCbCr_420_888
-    status_t lockYCbCr(uint32_t usage, android_ycbcr *ycbcr);
-    status_t lockYCbCr(uint32_t usage, const Rect& rect, android_ycbcr *ycbcr);
+    status_t lockYCbCr(uint32_t inUsage, android_ycbcr *ycbcr);
+    status_t lockYCbCr(uint32_t inUsage, const Rect& rect,
+            android_ycbcr *ycbcr);
     status_t unlock();
-    status_t lockAsync(uint32_t usage, void** vaddr, int fenceFd);
-    status_t lockAsync(uint32_t usage, const Rect& rect, void** vaddr, int fenceFd);
-    status_t lockAsyncYCbCr(uint32_t usage, android_ycbcr *ycbcr, int fenceFd);
-    status_t lockAsyncYCbCr(uint32_t usage, const Rect& rect, android_ycbcr *ycbcr, int fenceFd);
+    status_t lockAsync(uint32_t inUsage, void** vaddr, int fenceFd);
+    status_t lockAsync(uint32_t inUsage, const Rect& rect, void** vaddr,
+            int fenceFd);
+    status_t lockAsyncYCbCr(uint32_t inUsage, android_ycbcr *ycbcr,
+            int fenceFd);
+    status_t lockAsyncYCbCr(uint32_t inUsage, const Rect& rect,
+            android_ycbcr *ycbcr, int fenceFd);
     status_t unlockAsync(int *fenceFd);
 
     ANativeWindowBuffer* getNativeBuffer() const;
@@ -143,8 +150,8 @@
     GraphicBuffer& operator = (const GraphicBuffer& rhs);
     const GraphicBuffer& operator = (const GraphicBuffer& rhs) const;
 
-    status_t initSize(uint32_t w, uint32_t h, PixelFormat format, 
-            uint32_t usage);
+    status_t initSize(uint32_t inWidth, uint32_t inHeight, PixelFormat inFormat,
+            uint32_t inUsage);
 
     void free_handle();
 
diff --git a/include/ui/GraphicBufferAllocator.h b/include/ui/GraphicBufferAllocator.h
index dffa788..5443f09 100644
--- a/include/ui/GraphicBufferAllocator.h
+++ b/include/ui/GraphicBufferAllocator.h
@@ -1,17 +1,17 @@
-/* 
+/*
 **
 ** Copyright 2009, The Android Open Source Project
 **
-** Licensed under the Apache License, Version 2.0 (the "License"); 
-** you may not use this file except in compliance with the License. 
-** You may obtain a copy of the License at 
+** 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 
+**     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 
+** 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.
 */
 
@@ -45,14 +45,14 @@
         USAGE_SW_READ_RARELY    = GRALLOC_USAGE_SW_READ_RARELY,
         USAGE_SW_READ_OFTEN     = GRALLOC_USAGE_SW_READ_OFTEN,
         USAGE_SW_READ_MASK      = GRALLOC_USAGE_SW_READ_MASK,
-        
+
         USAGE_SW_WRITE_NEVER    = GRALLOC_USAGE_SW_WRITE_NEVER,
         USAGE_SW_WRITE_RARELY   = GRALLOC_USAGE_SW_WRITE_RARELY,
         USAGE_SW_WRITE_OFTEN    = GRALLOC_USAGE_SW_WRITE_OFTEN,
         USAGE_SW_WRITE_MASK     = GRALLOC_USAGE_SW_WRITE_MASK,
-        
+
         USAGE_SOFTWARE_MASK     = USAGE_SW_READ_MASK|USAGE_SW_WRITE_MASK,
-        
+
         USAGE_HW_TEXTURE        = GRALLOC_USAGE_HW_TEXTURE,
         USAGE_HW_RENDER         = GRALLOC_USAGE_HW_RENDER,
         USAGE_HW_2D             = GRALLOC_USAGE_HW_2D,
@@ -60,10 +60,9 @@
     };
 
     static inline GraphicBufferAllocator& get() { return getInstance(); }
-    
 
-    status_t alloc(uint32_t w, uint32_t h, PixelFormat format, int usage,
-            buffer_handle_t* handle, int32_t* stride);
+    status_t alloc(uint32_t w, uint32_t h, PixelFormat format, uint32_t usage,
+            buffer_handle_t* handle, uint32_t* stride);
 
     status_t free(buffer_handle_t handle);
 
@@ -72,21 +71,21 @@
 
 private:
     struct alloc_rec_t {
-        uint32_t w;
-        uint32_t h;
-        uint32_t s;
+        uint32_t width;
+        uint32_t height;
+        uint32_t stride;
         PixelFormat format;
         uint32_t usage;
         size_t size;
     };
-    
+
     static Mutex sLock;
     static KeyedVector<buffer_handle_t, alloc_rec_t> sAllocList;
-    
+
     friend class Singleton<GraphicBufferAllocator>;
     GraphicBufferAllocator();
     ~GraphicBufferAllocator();
-    
+
     alloc_device_t  *mAllocDev;
 };
 
diff --git a/include/ui/GraphicBufferMapper.h b/include/ui/GraphicBufferMapper.h
index 98fff0e..6099548 100644
--- a/include/ui/GraphicBufferMapper.h
+++ b/include/ui/GraphicBufferMapper.h
@@ -41,23 +41,24 @@
     status_t registerBuffer(buffer_handle_t handle);
 
     status_t unregisterBuffer(buffer_handle_t handle);
-    
+
     status_t lock(buffer_handle_t handle,
-            int usage, const Rect& bounds, void** vaddr);
+            uint32_t usage, const Rect& bounds, void** vaddr);
 
     status_t lockYCbCr(buffer_handle_t handle,
-            int usage, const Rect& bounds, android_ycbcr *ycbcr);
+            uint32_t usage, const Rect& bounds, android_ycbcr *ycbcr);
 
     status_t unlock(buffer_handle_t handle);
 
     status_t lockAsync(buffer_handle_t handle,
-            int usage, const Rect& bounds, void** vaddr, int fenceFd);
+            uint32_t usage, const Rect& bounds, void** vaddr, int fenceFd);
 
     status_t lockAsyncYCbCr(buffer_handle_t handle,
-            int usage, const Rect& bounds, android_ycbcr *ycbcr, int fenceFd);
+            uint32_t usage, const Rect& bounds, android_ycbcr *ycbcr,
+            int fenceFd);
 
     status_t unlockAsync(buffer_handle_t handle, int *fenceFd);
-    
+
     // dumps information about the mapping of this handle
     void dump(buffer_handle_t handle);
 
diff --git a/include/ui/PixelFormat.h b/include/ui/PixelFormat.h
index 7e46945..e7e8ffc 100644
--- a/include/ui/PixelFormat.h
+++ b/include/ui/PixelFormat.h
@@ -25,9 +25,6 @@
 #ifndef UI_PIXELFORMAT_H
 #define UI_PIXELFORMAT_H
 
-#include <stdint.h>
-#include <sys/types.h>
-#include <utils/Errors.h>
 #include <hardware/hardware.h>
 
 namespace android {
@@ -69,8 +66,8 @@
 
 typedef int32_t PixelFormat;
 
-ssize_t bytesPerPixel(PixelFormat format);
-ssize_t bitsPerPixel(PixelFormat format);
+uint32_t bytesPerPixel(PixelFormat format);
+uint32_t bitsPerPixel(PixelFormat format);
 
 }; // namespace android
 
diff --git a/include/ui/Rect.h b/include/ui/Rect.h
index 31e28d2..40d1166 100644
--- a/include/ui/Rect.h
+++ b/include/ui/Rect.h
@@ -18,6 +18,7 @@
 #define ANDROID_UI_RECT
 
 #include <utils/Flattenable.h>
+#include <utils/Log.h>
 #include <utils/TypeHelpers.h>
 #include <ui/Point.h>
 
@@ -43,6 +44,22 @@
         bottom = h;
     }
 
+    inline Rect(uint32_t w, uint32_t h) {
+        if (w > INT32_MAX) {
+            ALOG(LOG_WARN, "Rect",
+                    "Width %u too large for Rect class, clamping", w);
+            w = INT32_MAX;
+        }
+        if (h > INT32_MAX) {
+            ALOG(LOG_WARN, "Rect",
+                    "Height %u too large for Rect class, clamping", h);
+            h = INT32_MAX;
+        }
+        left = top = 0;
+        right = w;
+        bottom = h;
+    }
+
     inline Rect(int32_t l, int32_t t, int32_t r, int32_t b) {
         left = l;
         top = t;
diff --git a/include/ui/Region.h b/include/ui/Region.h
index 0d1c68c..873cd34 100644
--- a/include/ui/Region.h
+++ b/include/ui/Region.h
@@ -55,11 +55,11 @@
 
             // the region becomes its bounds
             Region&     makeBoundsSelf();
-    
+
             void        clear();
             void        set(const Rect& r);
-            void        set(uint32_t w, uint32_t h);
-        
+            void        set(int32_t w, int32_t h);
+
             Region&     orSelf(const Rect& rhs);
             Region&     xorSelf(const Rect& rhs);
             Region&     andSelf(const Rect& rhs);
@@ -110,14 +110,14 @@
     inline  Region&     operator -= (const Region& rhs);
     inline  Region&     operator += (const Point& pt);
 
-    
+
     // returns true if the regions share the same underlying storage
     bool isTriviallyEqual(const Region& region) const;
 
 
     /* various ways to access the rectangle list */
 
-    
+
     // STL-like iterators
     typedef Rect const* const_iterator;
     const_iterator begin() const;
@@ -133,7 +133,7 @@
     SharedBuffer const* getSharedBuffer(size_t* count) const;
 
     /* no user serviceable parts here... */
-            
+
             // add a rectangle to the internal list. This rectangle must
             // be sorted in Y and X and must not make the region invalid.
             void        addRectUnchecked(int l, int t, int r, int b);
@@ -149,7 +149,7 @@
 private:
     class rasterizer;
     friend class rasterizer;
-    
+
     Region& operationSelf(const Rect& r, int op);
     Region& operationSelf(const Region& r, int op);
     Region& operationSelf(const Region& r, int dx, int dy, int op);
@@ -172,7 +172,7 @@
 
     static bool validate(const Region& reg,
             const char* name, bool silent = false);
-    
+
     // mStorage is a (manually) sorted array of Rects describing the region
     // with an extra Rect as the last element which is set to the
     // bounds of the region. However, if the region is
diff --git a/libs/binder/AppOpsManager.cpp b/libs/binder/AppOpsManager.cpp
index 61b4f7d..c562c30 100644
--- a/libs/binder/AppOpsManager.cpp
+++ b/libs/binder/AppOpsManager.cpp
@@ -44,7 +44,7 @@
     int64_t startTime = 0;
     mLock.lock();
     sp<IAppOpsService> service = mService;
-    while (service == NULL || !service->asBinder()->isBinderAlive()) {
+    while (service == NULL || !IInterface::asBinder(service)->isBinderAlive()) {
         sp<IBinder> binder = defaultServiceManager()->checkService(_appops);
         if (binder == NULL) {
             // Wait for the app ops service to come back...
diff --git a/libs/binder/Binder.cpp b/libs/binder/Binder.cpp
index 296a98b..9d200fb 100644
--- a/libs/binder/Binder.cpp
+++ b/libs/binder/Binder.cpp
@@ -72,7 +72,7 @@
 
 BBinder::BBinder()
 {
-    atomic_init(&mExtras, 0);
+  atomic_init(&mExtras, static_cast<uintptr_t>(0));
 }
 
 bool BBinder::isBinderAlive() const
diff --git a/libs/binder/BpBinder.cpp b/libs/binder/BpBinder.cpp
index 101de7e..345ba20 100644
--- a/libs/binder/BpBinder.cpp
+++ b/libs/binder/BpBinder.cpp
@@ -220,7 +220,6 @@
         if ((obit.recipient == recipient
                     || (recipient == NULL && obit.cookie == cookie))
                 && obit.flags == flags) {
-            const uint32_t allFlags = obit.flags|flags;
             if (outRecipient != NULL) {
                 *outRecipient = mObituaries->itemAt(i).recipient;
             }
diff --git a/libs/binder/Debug.cpp b/libs/binder/Debug.cpp
index 0ffafbb..bdb7182 100644
--- a/libs/binder/Debug.cpp
+++ b/libs/binder/Debug.cpp
@@ -220,13 +220,8 @@
         
         for (word = 0; word < bytesPerLine; ) {
 
-#ifdef HAVE_LITTLE_ENDIAN
             const size_t startIndex = word+(alignment-(alignment?1:0));
             const ssize_t dir = -1;
-#else
-            const size_t startIndex = word;
-            const ssize_t dir = 1;
-#endif
 
             for (index = 0; index < alignment || (alignment == 0 && index < bytesPerLine); index++) {
             
diff --git a/libs/binder/IAppOpsService.cpp b/libs/binder/IAppOpsService.cpp
index f58a352..86abdc0 100644
--- a/libs/binder/IAppOpsService.cpp
+++ b/libs/binder/IAppOpsService.cpp
@@ -91,14 +91,14 @@
         data.writeInterfaceToken(IAppOpsService::getInterfaceDescriptor());
         data.writeInt32(op);
         data.writeString16(packageName);
-        data.writeStrongBinder(callback->asBinder());
+        data.writeStrongBinder(IInterface::asBinder(callback));
         remote()->transact(START_WATCHING_MODE_TRANSACTION, data, &reply);
     }
 
     virtual void stopWatchingMode(const sp<IAppOpsCallback>& callback) {
         Parcel data, reply;
         data.writeInterfaceToken(IAppOpsService::getInterfaceDescriptor());
-        data.writeStrongBinder(callback->asBinder());
+        data.writeStrongBinder(IInterface::asBinder(callback));
         remote()->transact(STOP_WATCHING_MODE_TRANSACTION, data, &reply);
     }
 
diff --git a/libs/binder/IInterface.cpp b/libs/binder/IInterface.cpp
index 99a9ffe..8c60dc4 100644
--- a/libs/binder/IInterface.cpp
+++ b/libs/binder/IInterface.cpp
@@ -27,14 +27,18 @@
 IInterface::~IInterface() {
 }
 
-sp<IBinder> IInterface::asBinder()
+// static
+sp<IBinder> IInterface::asBinder(const IInterface* iface)
 {
-    return onAsBinder();
+    if (iface == NULL) return NULL;
+    return const_cast<IInterface*>(iface)->onAsBinder();
 }
 
-sp<const IBinder> IInterface::asBinder() const
+// static
+sp<IBinder> IInterface::asBinder(const sp<IInterface>& iface)
 {
-    return const_cast<IInterface*>(this)->onAsBinder();
+    if (iface == NULL) return NULL;
+    return iface->onAsBinder();
 }
 
 // ---------------------------------------------------------------------------
diff --git a/libs/binder/IMemory.cpp b/libs/binder/IMemory.cpp
index d8ed995..e9891a8 100644
--- a/libs/binder/IMemory.cpp
+++ b/libs/binder/IMemory.cpp
@@ -216,7 +216,7 @@
             CHECK_INTERFACE(IMemory, data, reply);
             ssize_t offset;
             size_t size;
-            reply->writeStrongBinder( getMemory(&offset, &size)->asBinder() );
+            reply->writeStrongBinder( IInterface::asBinder(getMemory(&offset, &size)) );
             reply->writeInt32(offset);
             reply->writeInt32(size);
             return NO_ERROR;
@@ -241,7 +241,7 @@
         if (mRealHeap) {
             // by construction we're the last one
             if (mBase != MAP_FAILED) {
-                sp<IBinder> binder = const_cast<BpMemoryHeap*>(this)->asBinder();
+                sp<IBinder> binder = IInterface::asBinder(this);
 
                 if (VERBOSE) {
                     ALOGD("UNMAPPING binder=%p, heap=%p, size=%zu, fd=%d",
@@ -253,7 +253,7 @@
             }
         } else {
             // remove from list only if it was mapped before
-            sp<IBinder> binder = const_cast<BpMemoryHeap*>(this)->asBinder();
+            sp<IBinder> binder = IInterface::asBinder(this);
             free_heap(binder);
         }
     }
@@ -262,7 +262,7 @@
 void BpMemoryHeap::assertMapped() const
 {
     if (mHeapId == -1) {
-        sp<IBinder> binder(const_cast<BpMemoryHeap*>(this)->asBinder());
+        sp<IBinder> binder(IInterface::asBinder(const_cast<BpMemoryHeap*>(this)));
         sp<BpMemoryHeap> heap(static_cast<BpMemoryHeap*>(find_heap(binder).get()));
         heap->assertReallyMapped();
         if (heap->mBase != MAP_FAILED) {
@@ -297,7 +297,8 @@
         uint32_t offset = reply.readInt32();
 
         ALOGE_IF(err, "binder=%p transaction failed fd=%d, size=%zd, err=%d (%s)",
-                asBinder().get(), parcel_fd, size, err, strerror(-err));
+                IInterface::asBinder(this).get(),
+                parcel_fd, size, err, strerror(-err));
 
         int fd = dup( parcel_fd );
         ALOGE_IF(fd==-1, "cannot dup fd=%d, size=%zd, err=%d (%s)",
@@ -314,7 +315,7 @@
             mBase = mmap(0, size, access, MAP_SHARED, fd, offset);
             if (mBase == MAP_FAILED) {
                 ALOGE("cannot map BpMemoryHeap (binder=%p), size=%zd, fd=%d (%s)",
-                        asBinder().get(), size, fd, strerror(errno));
+                        IInterface::asBinder(this).get(), size, fd, strerror(errno));
                 close(fd);
             } else {
                 mSize = size;
diff --git a/libs/binder/IPCThreadState.cpp b/libs/binder/IPCThreadState.cpp
index a37eba5..2043d54 100644
--- a/libs/binder/IPCThreadState.cpp
+++ b/libs/binder/IPCThreadState.cpp
@@ -70,7 +70,6 @@
 namespace android {
 
 static const char* getReturnString(size_t idx);
-static const char* getCommandString(size_t idx);
 static const void* printReturnCommand(TextOutput& out, const void* _cmd);
 static const void* printCommand(TextOutput& out, const void* _cmd);
 
@@ -125,14 +124,6 @@
         return "unknown";
 }
 
-static const char* getCommandString(size_t idx)
-{
-    if (idx < sizeof(kCommandStrings) / sizeof(kCommandStrings[0]))
-        return kCommandStrings[idx];
-    else
-        return "unknown";
-}
-
 static const void* printBinderTransactionData(TextOutput& out, const void* data)
 {
     const binder_transaction_data* btd =
@@ -156,9 +147,9 @@
 {
     static const size_t N = sizeof(kReturnStrings)/sizeof(kReturnStrings[0]);
     const int32_t* cmd = (const int32_t*)_cmd;
-    int32_t code = *cmd++;
+    uint32_t code = (uint32_t)*cmd++;
     size_t cmdIndex = code & 0xff;
-    if (code == (int32_t) BR_ERROR) {
+    if (code == BR_ERROR) {
         out << "BR_ERROR: " << (void*)(long)(*cmd++) << endl;
         return cmd;
     } else if (cmdIndex >= N) {
@@ -217,7 +208,7 @@
 {
     static const size_t N = sizeof(kCommandStrings)/sizeof(kCommandStrings[0]);
     const int32_t* cmd = (const int32_t*)_cmd;
-    int32_t code = *cmd++;
+    uint32_t code = (uint32_t)*cmd++;
     size_t cmdIndex = code & 0xff;
 
     if (cmdIndex >= N) {
@@ -359,12 +350,12 @@
     return err;
 }
 
-int IPCThreadState::getCallingPid() const
+pid_t IPCThreadState::getCallingPid() const
 {
     return mCallingPid;
 }
 
-int IPCThreadState::getCallingUid() const
+uid_t IPCThreadState::getCallingUid() const
 {
     return mCallingUid;
 }
@@ -706,7 +697,7 @@
 
 status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
 {
-    int32_t cmd;
+    uint32_t cmd;
     int32_t err;
 
     while (1) {
@@ -715,7 +706,7 @@
         if (err < NO_ERROR) break;
         if (mIn.dataAvail() == 0) continue;
         
-        cmd = mIn.readInt32();
+        cmd = (uint32_t)mIn.readInt32();
         
         IF_LOG_COMMANDS() {
             alog << "Processing waitForResponse Command: "
@@ -945,7 +936,7 @@
     RefBase::weakref_type* refs;
     status_t result = NO_ERROR;
     
-    switch (cmd) {
+    switch ((uint32_t)cmd) {
     case BR_ERROR:
         result = mIn.readInt32();
         break;
diff --git a/libs/binder/IServiceManager.cpp b/libs/binder/IServiceManager.cpp
index 7b1b0e7..3c716df 100644
--- a/libs/binder/IServiceManager.cpp
+++ b/libs/binder/IServiceManager.cpp
@@ -87,7 +87,7 @@
             }
             
             // Is this a permission failure, or did the controller go away?
-            if (pc->asBinder()->isBinderAlive()) {
+            if (IInterface::asBinder(pc)->isBinderAlive()) {
                 ALOGW("Permission failure: %s from uid=%d pid=%d",
                         String8(permission).string(), uid, pid);
                 return false;
diff --git a/libs/binder/Parcel.cpp b/libs/binder/Parcel.cpp
index 1dbb06f..c526399 100644
--- a/libs/binder/Parcel.cpp
+++ b/libs/binder/Parcel.cpp
@@ -624,6 +624,12 @@
 {
     return writeAligned(val);
 }
+
+status_t Parcel::writeUint32(uint32_t val)
+{
+    return writeAligned(val);
+}
+
 status_t Parcel::writeInt32Array(size_t len, const int32_t *val) {
     if (!val) {
         return writeAligned(-1);
@@ -1035,6 +1041,15 @@
     return readAligned<int32_t>();
 }
 
+status_t Parcel::readUint32(uint32_t *pArg) const
+{
+    return readAligned(pArg);
+}
+
+uint32_t Parcel::readUint32() const
+{
+    return readAligned<uint32_t>();
+}
 
 status_t Parcel::readInt64(int64_t *pArg) const
 {
@@ -1452,7 +1467,7 @@
     for (size_t i = 0; i < mObjectsSize; i++) {
         binder_size_t offset = mObjects[i];
         if (offset < minOffset) {
-            ALOGE("%s: bad object offset %"PRIu64" < %"PRIu64"\n",
+            ALOGE("%s: bad object offset %" PRIu64 " < %" PRIu64 "\n",
                   __func__, (uint64_t)offset, (uint64_t)minOffset);
             mObjectsSize = 0;
             break;
diff --git a/libs/binder/tests/Android.mk b/libs/binder/tests/Android.mk
new file mode 100644
index 0000000..3668729
--- /dev/null
+++ b/libs/binder/tests/Android.mk
@@ -0,0 +1,34 @@
+#
+# 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.
+#
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+ifneq ($(TARGET_USES_64_BIT_BINDER),true)
+ifneq ($(TARGET_IS_64_BIT),true)
+LOCAL_CFLAGS += -DBINDER_IPC_32BIT=1
+endif
+endif
+
+LOCAL_MODULE := binderDriverInterfaceTest
+LOCAL_SRC_FILES := binderDriverInterfaceTest.cpp
+include $(BUILD_NATIVE_TEST)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := binderLibTest
+LOCAL_SRC_FILES := binderLibTest.cpp
+LOCAL_SHARED_LIBRARIES := libbinder libutils
+include $(BUILD_NATIVE_TEST)
diff --git a/libs/binder/tests/binderDriverInterfaceTest.cpp b/libs/binder/tests/binderDriverInterfaceTest.cpp
new file mode 100644
index 0000000..acb7d49
--- /dev/null
+++ b/libs/binder/tests/binderDriverInterfaceTest.cpp
@@ -0,0 +1,353 @@
+/*
+ * 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.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <gtest/gtest.h>
+#include <linux/binder.h>
+#include <binder/IBinder.h>
+#include <sys/mman.h>
+#include <poll.h>
+
+#define BINDER_DEV_NAME "/dev/binder"
+
+testing::Environment* binder_env;
+
+class BinderDriverInterfaceTestEnv : public ::testing::Environment {
+        virtual void SetUp() {
+            int ret;
+            uint32_t max_threads = 0;
+
+            m_binderFd = open(BINDER_DEV_NAME, O_RDWR | O_NONBLOCK);
+            ASSERT_GE(m_binderFd, 0);
+            m_buffer = mmap(NULL, 64*1024, PROT_READ, MAP_SHARED, m_binderFd, 0);
+            ASSERT_NE(m_buffer, (void *)NULL);
+            ret = ioctl(m_binderFd, BINDER_SET_MAX_THREADS, &max_threads);
+            EXPECT_EQ(0, ret);
+            EnterLooper();
+        }
+        virtual void TearDown() {
+            close(m_binderFd);
+        }
+    private:
+        int m_binderFd;
+        void *m_buffer;
+    public:
+        int getBinderFd(void) {
+            return m_binderFd;
+        }
+        void EnterLooper(void) {
+            int ret;
+            const uint32_t bc[] = {
+                BC_ENTER_LOOPER,
+            };
+            struct binder_write_read bwr = binder_write_read();
+            bwr.write_buffer = (intptr_t)bc;
+            bwr.write_size = sizeof(bc);
+            ret = ioctl(m_binderFd, BINDER_WRITE_READ, &bwr);
+            EXPECT_EQ(0, ret);
+            if (ret < 0) {
+                    EXPECT_EQ(0, errno);
+            }
+            EXPECT_EQ(sizeof(bc), bwr.write_consumed);
+        }
+};
+
+class BinderDriverInterfaceTest : public ::testing::Test {
+    public:
+        virtual void SetUp() {
+            m_binderFd = static_cast<BinderDriverInterfaceTestEnv *>(binder_env)->getBinderFd();
+        }
+        virtual void TearDown() {
+        }
+    protected:
+        void binderTestIoctlRetErr2(int cmd, void *arg, int expect_ret, int expect_errno, int accept_errno) {
+            int ret;
+
+            ret = ioctl(m_binderFd, cmd, arg);
+            EXPECT_EQ(expect_ret, ret);
+            if (ret < 0) {
+                if (errno != accept_errno)
+                    EXPECT_EQ(expect_errno, errno);
+            }
+        }
+        void binderTestIoctlErr2(int cmd, void *arg, int expect_errno, int accept_errno) {
+            binderTestIoctlRetErr2(cmd, arg, -1, expect_errno, accept_errno);
+        }
+        void binderTestIoctlErr1(int cmd, void *arg, int expect_errno) {
+            binderTestIoctlErr2(cmd, arg, expect_errno, expect_errno);
+        }
+        void binderTestIoctl(int cmd, void *arg) {
+            binderTestIoctlRetErr2(cmd, arg, 0, 0, 0);
+        }
+        void binderTestIoctlUnimplemented(int cmd, void *arg) {
+            int ret;
+
+            ret = ioctl(m_binderFd, cmd, arg);
+            if (ret < 0) {
+                /* Not currently implmented. Allow ret == -1, errno == EINVAL */
+                EXPECT_EQ(-1, ret);
+                EXPECT_EQ(EINVAL, errno);
+            }
+        }
+        void binderTestReadEmpty(void) {
+            size_t i;
+            uint32_t br[32];
+            struct binder_write_read bwr = binder_write_read();
+            SCOPED_TRACE("TestReadEmpty");
+            bwr.read_buffer = (intptr_t)br;
+            bwr.read_size = sizeof(br);
+            binderTestIoctlErr1(BINDER_WRITE_READ, &bwr, EAGAIN);
+            EXPECT_EQ(0, bwr.read_consumed);
+            for (i = 0; i * sizeof(uint32_t) < bwr.read_consumed; i++) {
+                SCOPED_TRACE(testing::Message() << "i = " << i);
+                EXPECT_EQ(BR_NOOP, br[i]);
+            }
+        }
+        void binderWaitForReadData(int timeout_ms) {
+            int ret;
+            pollfd pfd = pollfd();
+
+            pfd.fd = m_binderFd;
+            pfd.events = POLLIN;
+            ret = poll(&pfd, 1, timeout_ms);
+            EXPECT_EQ(1, ret);
+        }
+    private:
+        int m_binderFd;
+};
+
+TEST_F(BinderDriverInterfaceTest, Version) {
+    struct binder_version version;
+    binderTestIoctl(BINDER_VERSION, &version);
+    ASSERT_EQ(BINDER_CURRENT_PROTOCOL_VERSION, version.protocol_version);
+}
+
+TEST_F(BinderDriverInterfaceTest, WriteReadNull) {
+    binderTestIoctlErr1(BINDER_WRITE_READ, NULL, EFAULT);
+}
+
+TEST_F(BinderDriverInterfaceTest, SetIdleTimeoutNull) {
+    binderTestIoctlErr2(BINDER_SET_IDLE_TIMEOUT, NULL, EFAULT, EINVAL);
+}
+
+TEST_F(BinderDriverInterfaceTest, SetMaxThreadsNull) {
+    binderTestIoctlErr2(BINDER_SET_MAX_THREADS, NULL, EFAULT, EINVAL); /* TODO: don't accept EINVAL */
+}
+
+TEST_F(BinderDriverInterfaceTest, SetIdlePriorityNull) {
+    binderTestIoctlErr2(BINDER_SET_IDLE_PRIORITY, NULL, EFAULT, EINVAL);
+}
+
+TEST_F(BinderDriverInterfaceTest, VersionNull) {
+    binderTestIoctlErr2(BINDER_VERSION, NULL, EFAULT, EINVAL); /* TODO: don't accept EINVAL */
+}
+
+TEST_F(BinderDriverInterfaceTest, SetIdleTimeoutNoTest) {
+    int64_t idle_timeout = 100000;
+    binderTestIoctlUnimplemented(BINDER_SET_IDLE_TIMEOUT, &idle_timeout);
+}
+
+TEST_F(BinderDriverInterfaceTest, SetMaxThreads) {
+    uint32_t max_threads = 0;
+    binderTestIoctl(BINDER_SET_MAX_THREADS, &max_threads);
+}
+
+TEST_F(BinderDriverInterfaceTest, SetIdlePriorityNoTest) {
+    int idle_priority = 0;
+    binderTestIoctlUnimplemented(BINDER_SET_IDLE_PRIORITY, &idle_priority);
+}
+
+TEST_F(BinderDriverInterfaceTest, SetContextMgrBusy) {
+    int32_t dummy = 0;
+    binderTestIoctlErr1(BINDER_SET_CONTEXT_MGR, &dummy, EBUSY);
+}
+
+TEST_F(BinderDriverInterfaceTest, ThreadExit) {
+    int32_t dummy = 0;
+    binderTestIoctl(BINDER_THREAD_EXIT, &dummy);
+    static_cast<BinderDriverInterfaceTestEnv *>(binder_env)->EnterLooper();
+}
+
+TEST_F(BinderDriverInterfaceTest, WriteReadEmpty) {
+    struct binder_write_read bwr = binder_write_read();
+    binderTestIoctl(BINDER_WRITE_READ, &bwr);
+}
+
+TEST_F(BinderDriverInterfaceTest, Read) {
+    binderTestReadEmpty();
+}
+
+TEST_F(BinderDriverInterfaceTest, IncRefsAcquireReleaseDecRefs) {
+    const uint32_t bc[] = {
+        BC_INCREFS,
+        0,
+        BC_ACQUIRE,
+        0,
+        BC_RELEASE,
+        0,
+        BC_DECREFS,
+        0,
+    };
+    struct binder_write_read bwr = binder_write_read();
+    bwr.write_buffer = (intptr_t)bc;
+    bwr.write_size = sizeof(bc);
+    binderTestIoctl(BINDER_WRITE_READ, &bwr);
+    EXPECT_EQ(sizeof(bc), bwr.write_consumed);
+    binderTestReadEmpty();
+}
+
+TEST_F(BinderDriverInterfaceTest, Transaction) {
+    binder_uintptr_t cookie = 1234;
+    struct {
+        uint32_t cmd1;
+        struct binder_transaction_data arg1;
+    } __attribute__((packed)) bc1 = {
+        .cmd1 = BC_TRANSACTION,
+        .arg1 = {
+            .target = { 0 },
+            .cookie = 0,
+            .code = android::IBinder::PING_TRANSACTION,
+            .flags = 0,
+            .sender_pid = 0,
+            .sender_euid = 0,
+            .data_size = 0,
+            .offsets_size = 0,
+            .data = {0, 0},
+        },
+    };
+    struct {
+        uint32_t cmd0;
+        uint32_t cmd1;
+        uint32_t cmd2;
+        binder_transaction_data arg2;
+        uint32_t pad[16];
+    } __attribute__((packed)) br;
+    struct binder_write_read bwr = binder_write_read();
+
+    bwr.write_buffer = (intptr_t)&bc1;
+    bwr.write_size = sizeof(bc1);
+    bwr.read_buffer = (intptr_t)&br;
+    bwr.read_size = sizeof(br);
+
+    {
+        SCOPED_TRACE("1st WriteRead");
+        binderTestIoctl(BINDER_WRITE_READ, &bwr);
+    }
+    EXPECT_EQ(sizeof(bc1), bwr.write_consumed);
+    if (bwr.read_consumed < offsetof(typeof(br), pad)) {
+        SCOPED_TRACE("2nd WriteRead");
+        binderWaitForReadData(10000);
+        binderTestIoctl(BINDER_WRITE_READ, &bwr);
+    }
+    EXPECT_EQ(offsetof(typeof(br), pad), bwr.read_consumed);
+    if (bwr.read_consumed > offsetof(typeof(br), cmd0))
+        EXPECT_EQ(BR_NOOP, br.cmd0);
+    if (bwr.read_consumed > offsetof(typeof(br), cmd1))
+        EXPECT_EQ(BR_TRANSACTION_COMPLETE, br.cmd1);
+    if (bwr.read_consumed > offsetof(typeof(br), cmd2))
+        EXPECT_EQ(BR_REPLY, br.cmd2);
+    if (bwr.read_consumed >= offsetof(typeof(br), pad)) {
+        EXPECT_EQ(0, br.arg2.target.ptr);
+        EXPECT_EQ(0, br.arg2.cookie);
+        EXPECT_EQ(0, br.arg2.code);
+        EXPECT_EQ(0, br.arg2.flags);
+        EXPECT_EQ(0, br.arg2.data_size);
+        EXPECT_EQ(0, br.arg2.offsets_size);
+
+        SCOPED_TRACE("3rd WriteRead");
+
+        binderTestReadEmpty();
+
+        struct {
+            uint32_t cmd1;
+            binder_uintptr_t arg1;
+        } __attribute__((packed)) bc2 = {
+            .cmd1 = BC_FREE_BUFFER,
+            .arg1 = br.arg2.data.ptr.buffer,
+        };
+
+        bwr.write_buffer = (intptr_t)&bc2;
+        bwr.write_size = sizeof(bc2);
+        bwr.write_consumed = 0;
+        bwr.read_size = 0;
+
+        binderTestIoctl(BINDER_WRITE_READ, &bwr);
+        EXPECT_EQ(sizeof(bc2), bwr.write_consumed);
+    }
+    binderTestReadEmpty();
+}
+
+TEST_F(BinderDriverInterfaceTest, RequestDeathNotification) {
+    binder_uintptr_t cookie = 1234;
+    struct {
+        uint32_t cmd0;
+        uint32_t arg0;
+        uint32_t cmd1;
+        struct binder_handle_cookie arg1;
+        uint32_t cmd2;
+        struct binder_handle_cookie arg2;
+        uint32_t cmd3;
+        uint32_t arg3;
+    } __attribute__((packed)) bc = {
+        .cmd0 = BC_INCREFS,
+        .arg0 = 0,
+        .cmd1 = BC_REQUEST_DEATH_NOTIFICATION,
+        .arg1 = {
+            .handle = 0,
+            .cookie = cookie,
+        },
+        .cmd2 = BC_CLEAR_DEATH_NOTIFICATION,
+        .arg2 = {
+            .handle = 0,
+            .cookie = cookie,
+        },
+        .cmd3 = BC_DECREFS,
+        .arg3 = 0,
+    };
+    struct {
+        uint32_t cmd0;
+        uint32_t cmd1;
+        binder_uintptr_t arg1;
+        uint32_t pad[16];
+    } __attribute__((packed)) br;
+    struct binder_write_read bwr = binder_write_read();
+
+    bwr.write_buffer = (intptr_t)&bc;
+    bwr.write_size = sizeof(bc);
+    bwr.read_buffer = (intptr_t)&br;
+    bwr.read_size = sizeof(br);
+
+    binderTestIoctl(BINDER_WRITE_READ, &bwr);
+    EXPECT_EQ(sizeof(bc), bwr.write_consumed);
+    EXPECT_EQ(sizeof(br) - sizeof(br.pad), bwr.read_consumed);
+    EXPECT_EQ(BR_NOOP, br.cmd0);
+    EXPECT_EQ(BR_CLEAR_DEATH_NOTIFICATION_DONE, br.cmd1);
+    EXPECT_EQ(cookie, br.arg1);
+    binderTestReadEmpty();
+}
+
+int main(int argc, char **argv) {
+    ::testing::InitGoogleTest(&argc, argv);
+
+    binder_env = AddGlobalTestEnvironment(new BinderDriverInterfaceTestEnv());
+
+    return RUN_ALL_TESTS();
+}
+
diff --git a/libs/binder/tests/binderLibTest.cpp b/libs/binder/tests/binderLibTest.cpp
new file mode 100644
index 0000000..3df3acf
--- /dev/null
+++ b/libs/binder/tests/binderLibTest.cpp
@@ -0,0 +1,954 @@
+/*
+ * 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.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <poll.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <gtest/gtest.h>
+
+#include <binder/Binder.h>
+#include <binder/IBinder.h>
+#include <binder/IPCThreadState.h>
+#include <binder/IServiceManager.h>
+
+#define ARRAY_SIZE(array) (sizeof array / sizeof array[0])
+
+using namespace android;
+
+static testing::Environment* binder_env;
+static char *binderservername;
+static char binderserverarg[] = "--binderserver";
+
+static String16 binderLibTestServiceName = String16("test.binderLib");
+
+enum BinderLibTestTranscationCode {
+    BINDER_LIB_TEST_NOP_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
+    BINDER_LIB_TEST_REGISTER_SERVER,
+    BINDER_LIB_TEST_ADD_SERVER,
+    BINDER_LIB_TEST_CALL_BACK,
+    BINDER_LIB_TEST_NOP_CALL_BACK,
+    BINDER_LIB_TEST_GET_ID_TRANSACTION,
+    BINDER_LIB_TEST_INDIRECT_TRANSACTION,
+    BINDER_LIB_TEST_SET_ERROR_TRANSACTION,
+    BINDER_LIB_TEST_GET_STATUS_TRANSACTION,
+    BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION,
+    BINDER_LIB_TEST_LINK_DEATH_TRANSACTION,
+    BINDER_LIB_TEST_WRITE_FILE_TRANSACTION,
+    BINDER_LIB_TEST_PROMOTE_WEAK_REF_TRANSACTION,
+    BINDER_LIB_TEST_EXIT_TRANSACTION,
+    BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION,
+    BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION,
+};
+
+pid_t start_server_process(int arg2)
+{
+    int ret;
+    pid_t pid;
+    status_t status;
+    int pipefd[2];
+    char stri[16];
+    char strpipefd1[16];
+    char *childargv[] = {
+        binderservername,
+        binderserverarg,
+        stri,
+        strpipefd1,
+        NULL
+    };
+
+    ret = pipe(pipefd);
+    if (ret < 0)
+        return ret;
+
+    snprintf(stri, sizeof(stri), "%d", arg2);
+    snprintf(strpipefd1, sizeof(strpipefd1), "%d", pipefd[1]);
+
+    pid = fork();
+    if (pid == -1)
+        return pid;
+    if (pid == 0) {
+        close(pipefd[0]);
+        execv(binderservername, childargv);
+        status = -errno;
+        write(pipefd[1], &status, sizeof(status));
+        fprintf(stderr, "execv failed, %s\n", strerror(errno));
+        _exit(EXIT_FAILURE);
+    }
+    close(pipefd[1]);
+    ret = read(pipefd[0], &status, sizeof(status));
+    //printf("pipe read returned %d, status %d\n", ret, status);
+    close(pipefd[0]);
+    if (ret == sizeof(status)) {
+        ret = status;
+    } else {
+        kill(pid, SIGKILL);
+        if (ret >= 0) {
+            ret = NO_INIT;
+        }
+    }
+    if (ret < 0) {
+        wait(NULL);
+        return ret;
+    }
+    return pid;
+}
+
+class BinderLibTestEnv : public ::testing::Environment {
+    public:
+        BinderLibTestEnv() {}
+        sp<IBinder> getServer(void) {
+            return m_server;
+        }
+
+    private:
+        virtual void SetUp() {
+            m_serverpid = start_server_process(0);
+            //printf("m_serverpid %d\n", m_serverpid);
+            ASSERT_GT(m_serverpid, 0);
+
+            sp<IServiceManager> sm = defaultServiceManager();
+            //printf("%s: pid %d, get service\n", __func__, m_pid);
+            m_server = sm->getService(binderLibTestServiceName);
+            ASSERT_TRUE(m_server != NULL);
+            //printf("%s: pid %d, get service done\n", __func__, m_pid);
+        }
+        virtual void TearDown() {
+            status_t ret;
+            Parcel data, reply;
+            int exitStatus;
+            pid_t pid;
+
+            //printf("%s: pid %d\n", __func__, m_pid);
+            if (m_server != NULL) {
+                ret = m_server->transact(BINDER_LIB_TEST_GET_STATUS_TRANSACTION, data, &reply);
+                EXPECT_EQ(0, ret);
+                ret = m_server->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
+                EXPECT_EQ(0, ret);
+            }
+            if (m_serverpid > 0) {
+                //printf("wait for %d\n", m_pids[i]);
+                pid = wait(&exitStatus);
+                EXPECT_EQ(m_serverpid, pid);
+                EXPECT_TRUE(WIFEXITED(exitStatus));
+                EXPECT_EQ(0, WEXITSTATUS(exitStatus));
+            }
+        }
+
+        pid_t m_serverpid;
+        sp<IBinder> m_server;
+};
+
+class BinderLibTest : public ::testing::Test {
+    public:
+        virtual void SetUp() {
+            m_server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
+        }
+        virtual void TearDown() {
+        }
+    protected:
+        sp<IBinder> addServer(int32_t *idPtr = NULL)
+        {
+            int ret;
+            int32_t id;
+            Parcel data, reply;
+            sp<IBinder> binder;
+
+            ret = m_server->transact(BINDER_LIB_TEST_ADD_SERVER, data, &reply);
+            EXPECT_EQ(NO_ERROR, ret);
+
+            EXPECT_FALSE(binder != NULL);
+            binder = reply.readStrongBinder();
+            EXPECT_TRUE(binder != NULL);
+            ret = reply.readInt32(&id);
+            EXPECT_EQ(NO_ERROR, ret);
+            if (idPtr)
+                *idPtr = id;
+            return binder;
+        }
+        void waitForReadData(int fd, int timeout_ms) {
+            int ret;
+            pollfd pfd = pollfd();
+
+            pfd.fd = fd;
+            pfd.events = POLLIN;
+            ret = poll(&pfd, 1, timeout_ms);
+            EXPECT_EQ(1, ret);
+        }
+
+        sp<IBinder> m_server;
+};
+
+class BinderLibTestBundle : public Parcel
+{
+    public:
+        BinderLibTestBundle(void) {}
+        BinderLibTestBundle(const Parcel *source) : m_isValid(false) {
+            int32_t mark;
+            int32_t bundleLen;
+            size_t pos;
+
+            if (source->readInt32(&mark))
+                return;
+            if (mark != MARK_START)
+                return;
+            if (source->readInt32(&bundleLen))
+                return;
+            pos = source->dataPosition();
+            if (Parcel::appendFrom(source, pos, bundleLen))
+                return;
+            source->setDataPosition(pos + bundleLen);
+            if (source->readInt32(&mark))
+                return;
+            if (mark != MARK_END)
+                return;
+            m_isValid = true;
+            setDataPosition(0);
+        }
+        void appendTo(Parcel *dest) {
+            dest->writeInt32(MARK_START);
+            dest->writeInt32(dataSize());
+            dest->appendFrom(this, 0, dataSize());
+            dest->writeInt32(MARK_END);
+        };
+        bool isValid(void) {
+            return m_isValid;
+        }
+    private:
+        enum {
+            MARK_START  = B_PACK_CHARS('B','T','B','S'),
+            MARK_END    = B_PACK_CHARS('B','T','B','E'),
+        };
+        bool m_isValid;
+};
+
+class BinderLibTestEvent
+{
+    public:
+        BinderLibTestEvent(void)
+            : m_eventTriggered(false)
+        {
+            pthread_mutex_init(&m_waitMutex, NULL);
+            pthread_cond_init(&m_waitCond, NULL);
+        }
+        int waitEvent(int timeout_s)
+        {
+            int ret;
+            pthread_mutex_lock(&m_waitMutex);
+            if (!m_eventTriggered) {
+#if defined(HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE)
+                pthread_cond_timeout_np(&m_waitCond, &m_waitMutex, timeout_s * 1000);
+#else
+                struct timespec ts;
+                clock_gettime(CLOCK_REALTIME, &ts);
+                ts.tv_sec += timeout_s;
+                pthread_cond_timedwait(&m_waitCond, &m_waitMutex, &ts);
+#endif
+            }
+            ret = m_eventTriggered ? NO_ERROR : TIMED_OUT;
+            pthread_mutex_unlock(&m_waitMutex);
+            return ret;
+        }
+    protected:
+        void triggerEvent(void) {
+            pthread_mutex_lock(&m_waitMutex);
+            pthread_cond_signal(&m_waitCond);
+            m_eventTriggered = true;
+            pthread_mutex_unlock(&m_waitMutex);
+        };
+    private:
+        pthread_mutex_t m_waitMutex;
+        pthread_cond_t m_waitCond;
+        bool m_eventTriggered;
+};
+
+class BinderLibTestCallBack : public BBinder, public BinderLibTestEvent
+{
+    public:
+        BinderLibTestCallBack()
+            : m_result(NOT_ENOUGH_DATA)
+        {
+        }
+        status_t getResult(void)
+        {
+            return m_result;
+        }
+
+    private:
+        virtual status_t onTransact(uint32_t code,
+                                    const Parcel& data, Parcel* reply,
+                                    uint32_t flags = 0)
+        {
+            (void)reply;
+            (void)flags;
+            switch(code) {
+            case BINDER_LIB_TEST_CALL_BACK:
+                m_result = data.readInt32();
+                triggerEvent();
+                return NO_ERROR;
+            default:
+                return UNKNOWN_TRANSACTION;
+            }
+        }
+
+        status_t m_result;
+};
+
+class TestDeathRecipient : public IBinder::DeathRecipient, public BinderLibTestEvent
+{
+    private:
+        virtual void binderDied(const wp<IBinder>& who) {
+            (void)who;
+            triggerEvent();
+        };
+};
+
+TEST_F(BinderLibTest, NopTransaction) {
+    status_t ret;
+    Parcel data, reply;
+    ret = m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply);
+    EXPECT_EQ(NO_ERROR, ret);
+}
+
+TEST_F(BinderLibTest, SetError) {
+    int32_t testValue[] = { 0, -123, 123 };
+    for (size_t i = 0; i < ARRAY_SIZE(testValue); i++) {
+        status_t ret;
+        Parcel data, reply;
+        data.writeInt32(testValue[i]);
+        ret = m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply);
+        EXPECT_EQ(testValue[i], ret);
+    }
+}
+
+TEST_F(BinderLibTest, GetId) {
+    status_t ret;
+    int32_t id;
+    Parcel data, reply;
+    ret = m_server->transact(BINDER_LIB_TEST_GET_ID_TRANSACTION, data, &reply);
+    EXPECT_EQ(NO_ERROR, ret);
+    ret = reply.readInt32(&id);
+    EXPECT_EQ(NO_ERROR, ret);
+    EXPECT_EQ(0, id);
+}
+
+TEST_F(BinderLibTest, PtrSize) {
+    status_t ret;
+    int32_t ptrsize;
+    Parcel data, reply;
+    sp<IBinder> server = addServer();
+    ASSERT_TRUE(server != NULL);
+    ret = server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply);
+    EXPECT_EQ(NO_ERROR, ret);
+    ret = reply.readInt32(&ptrsize);
+    EXPECT_EQ(NO_ERROR, ret);
+    RecordProperty("TestPtrSize", sizeof(void *));
+    RecordProperty("ServerPtrSize", sizeof(void *));
+}
+
+TEST_F(BinderLibTest, IndirectGetId2)
+{
+    status_t ret;
+    int32_t id;
+    int32_t count;
+    Parcel data, reply;
+    int32_t serverId[3];
+
+    data.writeInt32(ARRAY_SIZE(serverId));
+    for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
+        sp<IBinder> server;
+        BinderLibTestBundle datai;
+
+        server = addServer(&serverId[i]);
+        ASSERT_TRUE(server != NULL);
+        data.writeStrongBinder(server);
+        data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
+        datai.appendTo(&data);
+    }
+
+    ret = m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply);
+    ASSERT_EQ(NO_ERROR, ret);
+
+    ret = reply.readInt32(&id);
+    ASSERT_EQ(NO_ERROR, ret);
+    EXPECT_EQ(0, id);
+
+    ret = reply.readInt32(&count);
+    ASSERT_EQ(NO_ERROR, ret);
+    EXPECT_EQ(ARRAY_SIZE(serverId), count);
+
+    for (size_t i = 0; i < (size_t)count; i++) {
+        BinderLibTestBundle replyi(&reply);
+        EXPECT_TRUE(replyi.isValid());
+        ret = replyi.readInt32(&id);
+        EXPECT_EQ(NO_ERROR, ret);
+        EXPECT_EQ(serverId[i], id);
+        EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
+    }
+
+    EXPECT_EQ(reply.dataSize(), reply.dataPosition());
+}
+
+TEST_F(BinderLibTest, IndirectGetId3)
+{
+    status_t ret;
+    int32_t id;
+    int32_t count;
+    Parcel data, reply;
+    int32_t serverId[3];
+
+    data.writeInt32(ARRAY_SIZE(serverId));
+    for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
+        sp<IBinder> server;
+        BinderLibTestBundle datai;
+        BinderLibTestBundle datai2;
+
+        server = addServer(&serverId[i]);
+        ASSERT_TRUE(server != NULL);
+        data.writeStrongBinder(server);
+        data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
+
+        datai.writeInt32(1);
+        datai.writeStrongBinder(m_server);
+        datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
+        datai2.appendTo(&datai);
+
+        datai.appendTo(&data);
+    }
+
+    ret = m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply);
+    ASSERT_EQ(NO_ERROR, ret);
+
+    ret = reply.readInt32(&id);
+    ASSERT_EQ(NO_ERROR, ret);
+    EXPECT_EQ(0, id);
+
+    ret = reply.readInt32(&count);
+    ASSERT_EQ(NO_ERROR, ret);
+    EXPECT_EQ(ARRAY_SIZE(serverId), count);
+
+    for (size_t i = 0; i < (size_t)count; i++) {
+        int32_t counti;
+
+        BinderLibTestBundle replyi(&reply);
+        EXPECT_TRUE(replyi.isValid());
+        ret = replyi.readInt32(&id);
+        EXPECT_EQ(NO_ERROR, ret);
+        EXPECT_EQ(serverId[i], id);
+
+        ret = replyi.readInt32(&counti);
+        ASSERT_EQ(NO_ERROR, ret);
+        EXPECT_EQ(1, counti);
+
+        BinderLibTestBundle replyi2(&replyi);
+        EXPECT_TRUE(replyi2.isValid());
+        ret = replyi2.readInt32(&id);
+        EXPECT_EQ(NO_ERROR, ret);
+        EXPECT_EQ(0, id);
+        EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
+
+        EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
+    }
+
+    EXPECT_EQ(reply.dataSize(), reply.dataPosition());
+}
+
+TEST_F(BinderLibTest, CallBack)
+{
+    status_t ret;
+    Parcel data, reply;
+    sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
+    data.writeStrongBinder(callBack);
+    ret = m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY);
+    EXPECT_EQ(NO_ERROR, ret);
+    ret = callBack->waitEvent(5);
+    EXPECT_EQ(NO_ERROR, ret);
+    ret = callBack->getResult();
+    EXPECT_EQ(NO_ERROR, ret);
+}
+
+TEST_F(BinderLibTest, AddServer)
+{
+    sp<IBinder> server = addServer();
+    ASSERT_TRUE(server != NULL);
+}
+
+TEST_F(BinderLibTest, DeathNotificationNoRefs)
+{
+    status_t ret;
+
+    sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
+
+    {
+        sp<IBinder> binder = addServer();
+        ASSERT_TRUE(binder != NULL);
+        ret = binder->linkToDeath(testDeathRecipient);
+        EXPECT_EQ(NO_ERROR, ret);
+    }
+    IPCThreadState::self()->flushCommands();
+    ret = testDeathRecipient->waitEvent(5);
+    EXPECT_EQ(NO_ERROR, ret);
+#if 0 /* Is there an unlink api that does not require a strong reference? */
+    ret = binder->unlinkToDeath(testDeathRecipient);
+    EXPECT_EQ(NO_ERROR, ret);
+#endif
+}
+
+TEST_F(BinderLibTest, DeathNotificationWeakRef)
+{
+    status_t ret;
+    wp<IBinder> wbinder;
+
+    sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
+
+    {
+        sp<IBinder> binder = addServer();
+        ASSERT_TRUE(binder != NULL);
+        ret = binder->linkToDeath(testDeathRecipient);
+        EXPECT_EQ(NO_ERROR, ret);
+        wbinder = binder;
+    }
+    IPCThreadState::self()->flushCommands();
+    ret = testDeathRecipient->waitEvent(5);
+    EXPECT_EQ(NO_ERROR, ret);
+#if 0 /* Is there an unlink api that does not require a strong reference? */
+    ret = binder->unlinkToDeath(testDeathRecipient);
+    EXPECT_EQ(NO_ERROR, ret);
+#endif
+}
+
+TEST_F(BinderLibTest, DeathNotificationStrongRef)
+{
+    status_t ret;
+    sp<IBinder> sbinder;
+
+    sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
+
+    {
+        sp<IBinder> binder = addServer();
+        ASSERT_TRUE(binder != NULL);
+        ret = binder->linkToDeath(testDeathRecipient);
+        EXPECT_EQ(NO_ERROR, ret);
+        sbinder = binder;
+    }
+    {
+        Parcel data, reply;
+        ret = sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
+        EXPECT_EQ(0, ret);
+    }
+    IPCThreadState::self()->flushCommands();
+    ret = testDeathRecipient->waitEvent(5);
+    EXPECT_EQ(NO_ERROR, ret);
+    ret = sbinder->unlinkToDeath(testDeathRecipient);
+    EXPECT_EQ(DEAD_OBJECT, ret);
+}
+
+TEST_F(BinderLibTest, DeathNotificationMultiple)
+{
+    status_t ret;
+    const int clientcount = 2;
+    sp<IBinder> target;
+    sp<IBinder> linkedclient[clientcount];
+    sp<BinderLibTestCallBack> callBack[clientcount];
+    sp<IBinder> passiveclient[clientcount];
+
+    target = addServer();
+    ASSERT_TRUE(target != NULL);
+    for (int i = 0; i < clientcount; i++) {
+        {
+            Parcel data, reply;
+
+            linkedclient[i] = addServer();
+            ASSERT_TRUE(linkedclient[i] != NULL);
+            callBack[i] = new BinderLibTestCallBack();
+            data.writeStrongBinder(target);
+            data.writeStrongBinder(callBack[i]);
+            ret = linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply, TF_ONE_WAY);
+            EXPECT_EQ(NO_ERROR, ret);
+        }
+        {
+            Parcel data, reply;
+
+            passiveclient[i] = addServer();
+            ASSERT_TRUE(passiveclient[i] != NULL);
+            data.writeStrongBinder(target);
+            ret = passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply, TF_ONE_WAY);
+            EXPECT_EQ(NO_ERROR, ret);
+        }
+    }
+    {
+        Parcel data, reply;
+        ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
+        EXPECT_EQ(0, ret);
+    }
+
+    for (int i = 0; i < clientcount; i++) {
+        ret = callBack[i]->waitEvent(5);
+        EXPECT_EQ(NO_ERROR, ret);
+        ret = callBack[i]->getResult();
+        EXPECT_EQ(NO_ERROR, ret);
+    }
+}
+
+TEST_F(BinderLibTest, PassFile) {
+    int ret;
+    int pipefd[2];
+    uint8_t buf[1] = { 0 };
+    uint8_t write_value = 123;
+
+    ret = pipe2(pipefd, O_NONBLOCK);
+    ASSERT_EQ(0, ret);
+
+    {
+        Parcel data, reply;
+        uint8_t writebuf[1] = { write_value };
+
+        ret = data.writeFileDescriptor(pipefd[1], true);
+        EXPECT_EQ(NO_ERROR, ret);
+
+        ret = data.writeInt32(sizeof(writebuf));
+        EXPECT_EQ(NO_ERROR, ret);
+
+        ret = data.write(writebuf, sizeof(writebuf));
+        EXPECT_EQ(NO_ERROR, ret);
+
+        ret = m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply);
+        EXPECT_EQ(NO_ERROR, ret);
+    }
+
+    ret = read(pipefd[0], buf, sizeof(buf));
+    EXPECT_EQ(sizeof(buf), ret);
+    EXPECT_EQ(write_value, buf[0]);
+
+    waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
+
+    ret = read(pipefd[0], buf, sizeof(buf));
+    EXPECT_EQ(0, ret);
+
+    close(pipefd[0]);
+}
+
+TEST_F(BinderLibTest, PromoteLocal) {
+    sp<IBinder> strong = new BBinder();
+    wp<IBinder> weak = strong;
+    sp<IBinder> strong_from_weak = weak.promote();
+    EXPECT_TRUE(strong != NULL);
+    EXPECT_EQ(strong, strong_from_weak);
+    strong = NULL;
+    strong_from_weak = NULL;
+    strong_from_weak = weak.promote();
+    EXPECT_TRUE(strong_from_weak == NULL);
+}
+
+TEST_F(BinderLibTest, PromoteRemote) {
+    int ret;
+    Parcel data, reply;
+    sp<IBinder> strong = new BBinder();
+    sp<IBinder> server = addServer();
+
+    ASSERT_TRUE(server != NULL);
+    ASSERT_TRUE(strong != NULL);
+
+    ret = data.writeWeakBinder(strong);
+    EXPECT_EQ(NO_ERROR, ret);
+
+    ret = server->transact(BINDER_LIB_TEST_PROMOTE_WEAK_REF_TRANSACTION, data, &reply);
+    EXPECT_GE(ret, 0);
+}
+
+class BinderLibTestService : public BBinder
+{
+    public:
+        BinderLibTestService(int32_t id)
+            : m_id(id)
+            , m_nextServerId(id + 1)
+            , m_serverStartRequested(false)
+        {
+            pthread_mutex_init(&m_serverWaitMutex, NULL);
+            pthread_cond_init(&m_serverWaitCond, NULL);
+        }
+        ~BinderLibTestService()
+        {
+            exit(EXIT_SUCCESS);
+        }
+        virtual status_t onTransact(uint32_t code,
+                                    const Parcel& data, Parcel* reply,
+                                    uint32_t flags = 0) {
+            //printf("%s: code %d\n", __func__, code);
+            (void)flags;
+
+            if (getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
+                return PERMISSION_DENIED;
+            }
+            switch (code) {
+            case BINDER_LIB_TEST_REGISTER_SERVER: {
+                int32_t id;
+                sp<IBinder> binder;
+                id = data.readInt32();
+                binder = data.readStrongBinder();
+                if (binder == NULL) {
+                    return BAD_VALUE;
+                }
+
+                if (m_id != 0)
+                    return INVALID_OPERATION;
+
+                pthread_mutex_lock(&m_serverWaitMutex);
+                if (m_serverStartRequested) {
+                    m_serverStartRequested = false;
+                    m_serverStarted = binder;
+                    pthread_cond_signal(&m_serverWaitCond);
+                }
+                pthread_mutex_unlock(&m_serverWaitMutex);
+                return NO_ERROR;
+            }
+            case BINDER_LIB_TEST_ADD_SERVER: {
+                int ret;
+                uint8_t buf[1] = { 0 };
+                int serverid;
+
+                if (m_id != 0) {
+                    return INVALID_OPERATION;
+                }
+                pthread_mutex_lock(&m_serverWaitMutex);
+                if (m_serverStartRequested) {
+                    ret = -EBUSY;
+                } else {
+                    serverid = m_nextServerId++;
+                    m_serverStartRequested = true;
+
+                    pthread_mutex_unlock(&m_serverWaitMutex);
+                    ret = start_server_process(serverid);
+                    pthread_mutex_lock(&m_serverWaitMutex);
+                }
+                if (ret > 0) {
+                    if (m_serverStartRequested) {
+#if defined(HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE)
+                        ret = pthread_cond_timeout_np(&m_serverWaitCond, &m_serverWaitMutex, 5000);
+#else
+                        struct timespec ts;
+                        clock_gettime(CLOCK_REALTIME, &ts);
+                        ts.tv_sec += 5;
+                        ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
+#endif
+                    }
+                    if (m_serverStartRequested) {
+                        m_serverStartRequested = false;
+                        ret = -ETIMEDOUT;
+                    } else {
+                        reply->writeStrongBinder(m_serverStarted);
+                        reply->writeInt32(serverid);
+                        m_serverStarted = NULL;
+                        ret = NO_ERROR;
+                    }
+                } else if (ret >= 0) {
+                    m_serverStartRequested = false;
+                    ret = UNKNOWN_ERROR;
+                }
+                pthread_mutex_unlock(&m_serverWaitMutex);
+                return ret;
+            }
+            case BINDER_LIB_TEST_NOP_TRANSACTION:
+                return NO_ERROR;
+            case BINDER_LIB_TEST_NOP_CALL_BACK: {
+                Parcel data2, reply2;
+                sp<IBinder> binder;
+                binder = data.readStrongBinder();
+                if (binder == NULL) {
+                    return BAD_VALUE;
+                }
+                reply2.writeInt32(NO_ERROR);
+                binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
+                return NO_ERROR;
+            }
+            case BINDER_LIB_TEST_GET_ID_TRANSACTION:
+                reply->writeInt32(m_id);
+                return NO_ERROR;
+            case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
+                int32_t count;
+                uint32_t indirect_code;
+                sp<IBinder> binder;
+
+                count = data.readInt32();
+                reply->writeInt32(m_id);
+                reply->writeInt32(count);
+                for (int i = 0; i < count; i++) {
+                    binder = data.readStrongBinder();
+                    if (binder == NULL) {
+                        return BAD_VALUE;
+                    }
+                    indirect_code = data.readInt32();
+                    BinderLibTestBundle data2(&data);
+                    if (!data2.isValid()) {
+                        return BAD_VALUE;
+                    }
+                    BinderLibTestBundle reply2;
+                    binder->transact(indirect_code, data2, &reply2);
+                    reply2.appendTo(reply);
+                }
+                return NO_ERROR;
+            }
+            case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
+                reply->setError(data.readInt32());
+                return NO_ERROR;
+            case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
+                reply->writeInt32(sizeof(void *));
+                return NO_ERROR;
+            case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
+                return NO_ERROR;
+            case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
+                m_strongRef = data.readStrongBinder();
+                return NO_ERROR;
+            case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
+                int ret;
+                Parcel data2, reply2;
+                sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
+                sp<IBinder> target;
+                sp<IBinder> callback;
+
+                target = data.readStrongBinder();
+                if (target == NULL) {
+                    return BAD_VALUE;
+                }
+                callback = data.readStrongBinder();
+                if (callback == NULL) {
+                    return BAD_VALUE;
+                }
+                ret = target->linkToDeath(testDeathRecipient);
+                if (ret == NO_ERROR)
+                    ret = testDeathRecipient->waitEvent(5);
+                data2.writeInt32(ret);
+                callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
+                return NO_ERROR;
+            }
+            case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
+                int ret;
+                int32_t size;
+                const void *buf;
+                int fd;
+
+                fd = data.readFileDescriptor();
+                if (fd < 0) {
+                    return BAD_VALUE;
+                }
+                ret = data.readInt32(&size);
+                if (ret != NO_ERROR) {
+                    return ret;
+                }
+                buf = data.readInplace(size);
+                if (buf == NULL) {
+                    return BAD_VALUE;
+                }
+                ret = write(fd, buf, size);
+                if (ret != size)
+                    return UNKNOWN_ERROR;
+                return NO_ERROR;
+            }
+            case BINDER_LIB_TEST_PROMOTE_WEAK_REF_TRANSACTION: {
+                int ret;
+                wp<IBinder> weak;
+                sp<IBinder> strong;
+                Parcel data2, reply2;
+                sp<IServiceManager> sm = defaultServiceManager();
+                sp<IBinder> server = sm->getService(binderLibTestServiceName);
+
+                weak = data.readWeakBinder();
+                if (weak == NULL) {
+                    return BAD_VALUE;
+                }
+                strong = weak.promote();
+
+                ret = server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data2, &reply2);
+                if (ret != NO_ERROR)
+                    exit(EXIT_FAILURE);
+
+                if (strong == NULL) {
+                    reply->setError(1);
+                }
+                return NO_ERROR;
+            }
+            case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
+                alarm(10);
+                return NO_ERROR;
+            case BINDER_LIB_TEST_EXIT_TRANSACTION:
+                while (wait(NULL) != -1 || errno != ECHILD)
+                    ;
+                exit(EXIT_SUCCESS);
+            default:
+                return UNKNOWN_TRANSACTION;
+            };
+        }
+    private:
+        int32_t m_id;
+        int32_t m_nextServerId;
+        pthread_mutex_t m_serverWaitMutex;
+        pthread_cond_t m_serverWaitCond;
+        bool m_serverStartRequested;
+        sp<IBinder> m_serverStarted;
+        sp<IBinder> m_strongRef;
+};
+
+int run_server(int index, int readypipefd)
+{
+    status_t ret;
+    sp<IServiceManager> sm = defaultServiceManager();
+    {
+        sp<BinderLibTestService> testService = new BinderLibTestService(index);
+        if (index == 0) {
+            ret = sm->addService(binderLibTestServiceName, testService);
+        } else {
+            sp<IBinder> server = sm->getService(binderLibTestServiceName);
+            Parcel data, reply;
+            data.writeInt32(index);
+            data.writeStrongBinder(testService);
+
+            ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
+        }
+    }
+    write(readypipefd, &ret, sizeof(ret));
+    close(readypipefd);
+    //printf("%s: ret %d\n", __func__, ret);
+    if (ret)
+        return 1;
+    //printf("%s: joinThreadPool\n", __func__);
+    ProcessState::self()->startThreadPool();
+    IPCThreadState::self()->joinThreadPool();
+    //printf("%s: joinThreadPool returned\n", __func__);
+    return 1; /* joinThreadPool should not return */
+}
+
+int main(int argc, char **argv) {
+    int ret;
+
+    if (argc == 3 && !strcmp(argv[1], "--servername")) {
+        binderservername = argv[2];
+    } else {
+        binderservername = argv[0];
+    }
+
+    if (argc == 4 && !strcmp(argv[1], binderserverarg)) {
+        return run_server(atoi(argv[2]), atoi(argv[3]));
+    }
+
+    ::testing::InitGoogleTest(&argc, argv);
+    binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
+    ProcessState::self()->startThreadPool();
+    return RUN_ALL_TESTS();
+}
+
diff --git a/libs/gui/Android.mk b/libs/gui/Android.mk
index ca94aa3..8a965dd 100644
--- a/libs/gui/Android.mk
+++ b/libs/gui/Android.mk
@@ -1,7 +1,42 @@
-LOCAL_PATH:= $(call my-dir)
+# Copyright 2010 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
 include $(CLEAR_VARS)
 
-LOCAL_SRC_FILES:= \
+LOCAL_CLANG := true
+LOCAL_CPPFLAGS := -std=c++1y -Weverything -Werror
+
+# The static constructors and destructors in this library have not been noted to
+# introduce significant overheads
+LOCAL_CPPFLAGS += -Wno-exit-time-destructors
+LOCAL_CPPFLAGS += -Wno-global-constructors
+
+# We only care about compiling as C++14
+LOCAL_CPPFLAGS += -Wno-c++98-compat-pedantic
+
+# We don't need to enumerate every case in a switch as long as a default case
+# is present
+LOCAL_CPPFLAGS += -Wno-switch-enum
+
+# Allow calling variadic macros without a __VA_ARGS__ list
+LOCAL_CPPFLAGS += -Wno-gnu-zero-variadic-macro-arguments
+
+# Don't warn about struct padding
+LOCAL_CPPFLAGS += -Wno-padded
+
+LOCAL_SRC_FILES := \
 	IGraphicBufferConsumer.cpp \
 	IConsumerListener.cpp \
 	BitTube.cpp \
@@ -47,7 +82,7 @@
 	liblog
 
 
-LOCAL_MODULE:= libgui
+LOCAL_MODULE := libgui
 
 ifeq ($(TARGET_BOARD_PLATFORM), tegra)
 	LOCAL_CFLAGS += -DDONT_USE_FENCE_SYNC
diff --git a/libs/gui/BitTube.cpp b/libs/gui/BitTube.cpp
index 3ed1f37..b653c5b 100644
--- a/libs/gui/BitTube.cpp
+++ b/libs/gui/BitTube.cpp
@@ -149,12 +149,12 @@
     ssize_t size = tube->write(vaddr, count*objSize);
 
     // should never happen because of SOCK_SEQPACKET
-    LOG_ALWAYS_FATAL_IF((size >= 0) && (size % objSize),
+    LOG_ALWAYS_FATAL_IF((size >= 0) && (size % static_cast<ssize_t>(objSize)),
             "BitTube::sendObjects(count=%zu, size=%zu), res=%zd (partial events were sent!)",
             count, objSize, size);
 
     //ALOGE_IF(size<0, "error %d sending %d events", size, count);
-    return size < 0 ? size : size / objSize;
+    return size < 0 ? size : size / static_cast<ssize_t>(objSize);
 }
 
 ssize_t BitTube::recvObjects(const sp<BitTube>& tube,
@@ -164,12 +164,12 @@
     ssize_t size = tube->read(vaddr, count*objSize);
 
     // should never happen because of SOCK_SEQPACKET
-    LOG_ALWAYS_FATAL_IF((size >= 0) && (size % objSize),
+    LOG_ALWAYS_FATAL_IF((size >= 0) && (size % static_cast<ssize_t>(objSize)),
             "BitTube::recvObjects(count=%zu, size=%zu), res=%zd (partial events were received!)",
             count, objSize, size);
 
     //ALOGE_IF(size<0, "error %d receiving %d events", size, count);
-    return size < 0 ? size : size / objSize;
+    return size < 0 ? size : size / static_cast<ssize_t>(objSize);
 }
 
 // ----------------------------------------------------------------------------
diff --git a/libs/gui/BufferItemConsumer.cpp b/libs/gui/BufferItemConsumer.cpp
index 2d976e5..61de69a 100644
--- a/libs/gui/BufferItemConsumer.cpp
+++ b/libs/gui/BufferItemConsumer.cpp
@@ -16,15 +16,15 @@
 
 //#define LOG_NDEBUG 0
 #define LOG_TAG "BufferItemConsumer"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
+//#define ATRACE_TAG ATRACE_TAG_GRAPHICS
 #include <utils/Log.h>
 
 #include <gui/BufferItemConsumer.h>
 
-#define BI_LOGV(x, ...) ALOGV("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define BI_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define BI_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define BI_LOGW(x, ...) ALOGW("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define BI_LOGV(x, ...) ALOGV("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define BI_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define BI_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define BI_LOGW(x, ...) ALOGW("[%s] " x, mName.string(), ##__VA_ARGS__)
 #define BI_LOGE(x, ...) ALOGE("[%s] " x, mName.string(), ##__VA_ARGS__)
 
 namespace android {
@@ -44,8 +44,7 @@
     }
 }
 
-BufferItemConsumer::~BufferItemConsumer() {
-}
+BufferItemConsumer::~BufferItemConsumer() {}
 
 void BufferItemConsumer::setName(const String8& name) {
     Mutex::Autolock _l(mMutex);
@@ -105,7 +104,7 @@
     return mConsumer->setDefaultBufferSize(w, h);
 }
 
-status_t BufferItemConsumer::setDefaultBufferFormat(uint32_t defaultFormat) {
+status_t BufferItemConsumer::setDefaultBufferFormat(PixelFormat defaultFormat) {
     Mutex::Autolock _l(mMutex);
     return mConsumer->setDefaultBufferFormat(defaultFormat);
 }
diff --git a/libs/gui/BufferQueueConsumer.cpp b/libs/gui/BufferQueueConsumer.cpp
index 36e3c06..a798b18 100644
--- a/libs/gui/BufferQueueConsumer.cpp
+++ b/libs/gui/BufferQueueConsumer.cpp
@@ -488,7 +488,7 @@
     mConsumerName = name;
 }
 
-status_t BufferQueueConsumer::setDefaultBufferFormat(uint32_t defaultFormat) {
+status_t BufferQueueConsumer::setDefaultBufferFormat(PixelFormat defaultFormat) {
     ATRACE_CALL();
     BQ_LOGV("setDefaultBufferFormat: %u", defaultFormat);
     Mutex::Autolock lock(mCore->mMutex);
diff --git a/libs/gui/BufferQueueProducer.cpp b/libs/gui/BufferQueueProducer.cpp
index d2fd3b0..ef2a7e8 100644
--- a/libs/gui/BufferQueueProducer.cpp
+++ b/libs/gui/BufferQueueProducer.cpp
@@ -245,7 +245,7 @@
 
 status_t BufferQueueProducer::dequeueBuffer(int *outSlot,
         sp<android::Fence> *outFence, bool async,
-        uint32_t width, uint32_t height, uint32_t format, uint32_t usage) {
+        uint32_t width, uint32_t height, PixelFormat format, uint32_t usage) {
     ATRACE_CALL();
     { // Autolock scope
         Mutex::Autolock lock(mCore->mMutex);
@@ -306,7 +306,7 @@
         if ((buffer == NULL) ||
                 (static_cast<uint32_t>(buffer->width) != width) ||
                 (static_cast<uint32_t>(buffer->height) != height) ||
-                (static_cast<uint32_t>(buffer->format) != format) ||
+                (buffer->format != format) ||
                 ((static_cast<uint32_t>(buffer->usage) & usage) != usage))
         {
             mSlots[found].mAcquireCalled = false;
@@ -336,7 +336,7 @@
         status_t error;
         BQ_LOGV("dequeueBuffer: allocating a new buffer for slot %d", *outSlot);
         sp<GraphicBuffer> graphicBuffer(mCore->mAllocator->createGraphicBuffer(
-                    width, height, format, usage, &error));
+                width, height, format, usage, &error));
         if (graphicBuffer == NULL) {
             BQ_LOGE("dequeueBuffer: createGraphicBuffer failed");
             return error;
@@ -579,8 +579,8 @@
         BQ_LOGV("queueBuffer: slot=%d/%" PRIu64 " time=%" PRIu64
                 " crop=[%d,%d,%d,%d] transform=%#x scale=%s",
                 slot, mCore->mFrameCounter + 1, timestamp,
-                crop.left, crop.top, crop.right, crop.bottom,
-                transform, BufferItem::scalingModeName(scalingMode));
+                crop.left, crop.top, crop.right, crop.bottom, transform,
+                BufferItem::scalingModeName(static_cast<uint32_t>(scalingMode)));
 
         const sp<GraphicBuffer>& graphicBuffer(mSlots[slot].mGraphicBuffer);
         Rect bufferRect(graphicBuffer->getWidth(), graphicBuffer->getHeight());
@@ -601,10 +601,11 @@
         item.mAcquireCalled = mSlots[slot].mAcquireCalled;
         item.mGraphicBuffer = mSlots[slot].mGraphicBuffer;
         item.mCrop = crop;
-        item.mTransform = transform & ~NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY;
+        item.mTransform = transform &
+                ~static_cast<uint32_t>(NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY);
         item.mTransformToDisplayInverse =
-                bool(transform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY);
-        item.mScalingMode = scalingMode;
+                (transform & NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY) != 0;
+        item.mScalingMode = static_cast<uint32_t>(scalingMode);
         item.mTimestamp = timestamp;
         item.mIsAutoTimestamp = isAutoTimestamp;
         item.mFrameNumber = mCore->mFrameCounter;
@@ -644,7 +645,8 @@
         mCore->mDequeueCondition.broadcast();
 
         output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight,
-                mCore->mTransformHint, mCore->mQueue.size());
+                mCore->mTransformHint,
+                static_cast<uint32_t>(mCore->mQueue.size()));
 
         ATRACE_INT(mCore->mConsumerName.string(), mCore->mQueue.size());
     } // Autolock scope
@@ -703,25 +705,25 @@
     int value;
     switch (what) {
         case NATIVE_WINDOW_WIDTH:
-            value = mCore->mDefaultWidth;
+            value = static_cast<int32_t>(mCore->mDefaultWidth);
             break;
         case NATIVE_WINDOW_HEIGHT:
-            value = mCore->mDefaultHeight;
+            value = static_cast<int32_t>(mCore->mDefaultHeight);
             break;
         case NATIVE_WINDOW_FORMAT:
-            value = mCore->mDefaultBufferFormat;
+            value = static_cast<int32_t>(mCore->mDefaultBufferFormat);
             break;
         case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
             value = mCore->getMinUndequeuedBufferCountLocked(false);
             break;
         case NATIVE_WINDOW_STICKY_TRANSFORM:
-            value = static_cast<int>(mStickyTransform);
+            value = static_cast<int32_t>(mStickyTransform);
             break;
         case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND:
             value = (mCore->mQueue.size() > 1);
             break;
         case NATIVE_WINDOW_CONSUMER_USAGE_BITS:
-            value = mCore->mConsumerUsageBits;
+            value = static_cast<int32_t>(mCore->mConsumerUsageBits);
             break;
         default:
             return BAD_VALUE;
@@ -769,13 +771,14 @@
         case NATIVE_WINDOW_API_CAMERA:
             mCore->mConnectedApi = api;
             output->inflate(mCore->mDefaultWidth, mCore->mDefaultHeight,
-                    mCore->mTransformHint, mCore->mQueue.size());
+                    mCore->mTransformHint,
+                    static_cast<uint32_t>(mCore->mQueue.size()));
 
             // Set up a death notification so that we can disconnect
             // automatically if the remote producer dies
             if (listener != NULL &&
-                    listener->asBinder()->remoteBinder() != NULL) {
-                status = listener->asBinder()->linkToDeath(
+                    IInterface::asBinder(listener)->remoteBinder() != NULL) {
+                status = IInterface::asBinder(listener)->linkToDeath(
                         static_cast<IBinder::DeathRecipient*>(this));
                 if (status != NO_ERROR) {
                     BQ_LOGE("connect(P): linkToDeath failed: %s (%d)",
@@ -824,7 +827,7 @@
                     // Remove our death notification callback if we have one
                     if (mCore->mConnectedProducerListener != NULL) {
                         sp<IBinder> token =
-                                mCore->mConnectedProducerListener->asBinder();
+                                IInterface::asBinder(mCore->mConnectedProducerListener);
                         // This can fail if we're here because of the death
                         // notification, but we just ignore it
                         token->unlinkToDeath(
@@ -871,14 +874,14 @@
 }
 
 void BufferQueueProducer::allocateBuffers(bool async, uint32_t width,
-        uint32_t height, uint32_t format, uint32_t usage) {
+        uint32_t height, PixelFormat format, uint32_t usage) {
     ATRACE_CALL();
     while (true) {
         Vector<int> freeSlots;
         size_t newBufferCount = 0;
         uint32_t allocWidth = 0;
         uint32_t allocHeight = 0;
-        uint32_t allocFormat = 0;
+        PixelFormat allocFormat = PIXEL_FORMAT_UNKNOWN;
         uint32_t allocUsage = 0;
         { // Autolock scope
             Mutex::Autolock lock(mCore->mMutex);
@@ -904,7 +907,8 @@
                     currentBufferCount, maxBufferCount);
             if (maxBufferCount <= currentBufferCount)
                 return;
-            newBufferCount = maxBufferCount - currentBufferCount;
+            newBufferCount =
+                    static_cast<size_t>(maxBufferCount - currentBufferCount);
             if (freeSlots.size() < newBufferCount) {
                 BQ_LOGE("allocateBuffers: ran out of free slots");
                 return;
@@ -917,7 +921,7 @@
             mCore->mIsAllocating = true;
         } // Autolock scope
 
-        Vector<sp<GraphicBuffer> > buffers;
+        Vector<sp<GraphicBuffer>> buffers;
         for (size_t i = 0; i <  newBufferCount; ++i) {
             status_t result = NO_ERROR;
             sp<GraphicBuffer> graphicBuffer(mCore->mAllocator->createGraphicBuffer(
@@ -937,7 +941,8 @@
             Mutex::Autolock lock(mCore->mMutex);
             uint32_t checkWidth = width > 0 ? width : mCore->mDefaultWidth;
             uint32_t checkHeight = height > 0 ? height : mCore->mDefaultHeight;
-            uint32_t checkFormat = format != 0 ? format : mCore->mDefaultBufferFormat;
+            PixelFormat checkFormat = format != 0 ?
+                    format : mCore->mDefaultBufferFormat;
             uint32_t checkUsage = usage | mCore->mConsumerUsageBits;
             if (checkWidth != allocWidth || checkHeight != allocHeight ||
                 checkFormat != allocFormat || checkUsage != allocUsage) {
diff --git a/libs/gui/BufferSlot.cpp b/libs/gui/BufferSlot.cpp
index b8877fe..01595de 100644
--- a/libs/gui/BufferSlot.cpp
+++ b/libs/gui/BufferSlot.cpp
@@ -24,8 +24,8 @@
         case BufferSlot::QUEUED: return "QUEUED";
         case BufferSlot::FREE: return "FREE";
         case BufferSlot::ACQUIRED: return "ACQUIRED";
-        default: return "Unknown";
     }
+    return "Unknown";
 }
 
 } // namespace android
diff --git a/libs/gui/ConsumerBase.cpp b/libs/gui/ConsumerBase.cpp
index e476c9a..580e0e7 100644
--- a/libs/gui/ConsumerBase.cpp
+++ b/libs/gui/ConsumerBase.cpp
@@ -40,9 +40,9 @@
 
 // Macros for including the ConsumerBase name in log messages
 #define CB_LOGV(x, ...) ALOGV("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define CB_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define CB_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define CB_LOGW(x, ...) ALOGW("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define CB_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define CB_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define CB_LOGW(x, ...) ALOGW("[%s] " x, mName.string(), ##__VA_ARGS__)
 #define CB_LOGE(x, ...) ALOGE("[%s] " x, mName.string(), ##__VA_ARGS__)
 
 namespace android {
diff --git a/libs/gui/CpuConsumer.cpp b/libs/gui/CpuConsumer.cpp
index e55e108..d74d06c 100644
--- a/libs/gui/CpuConsumer.cpp
+++ b/libs/gui/CpuConsumer.cpp
@@ -16,22 +16,22 @@
 
 //#define LOG_NDEBUG 0
 #define LOG_TAG "CpuConsumer"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
+//#define ATRACE_TAG ATRACE_TAG_GRAPHICS
 
 #include <cutils/compiler.h>
 #include <utils/Log.h>
 #include <gui/CpuConsumer.h>
 
-#define CC_LOGV(x, ...) ALOGV("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define CC_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define CC_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define CC_LOGV(x, ...) ALOGV("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define CC_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define CC_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
 #define CC_LOGW(x, ...) ALOGW("[%s] " x, mName.string(), ##__VA_ARGS__)
 #define CC_LOGE(x, ...) ALOGE("[%s] " x, mName.string(), ##__VA_ARGS__)
 
 namespace android {
 
 CpuConsumer::CpuConsumer(const sp<IGraphicBufferConsumer>& bq,
-        uint32_t maxLockedBuffers, bool controlledByApp) :
+        size_t maxLockedBuffers, bool controlledByApp) :
     ConsumerBase(bq, controlledByApp),
     mMaxLockedBuffers(maxLockedBuffers),
     mCurrentLockedBuffers(0)
@@ -40,7 +40,7 @@
     mAcquiredBuffers.insertAt(0, maxLockedBuffers);
 
     mConsumer->setConsumerUsageBits(GRALLOC_USAGE_SW_READ_OFTEN);
-    mConsumer->setMaxAcquiredBufferCount(maxLockedBuffers);
+    mConsumer->setMaxAcquiredBufferCount(static_cast<int32_t>(maxLockedBuffers));
 }
 
 CpuConsumer::~CpuConsumer() {
@@ -61,7 +61,7 @@
     return mConsumer->setDefaultBufferSize(width, height);
 }
 
-status_t CpuConsumer::setDefaultBufferFormat(uint32_t defaultFormat)
+status_t CpuConsumer::setDefaultBufferFormat(PixelFormat defaultFormat)
 {
     Mutex::Autolock _l(mMutex);
     return mConsumer->setDefaultBufferFormat(defaultFormat);
@@ -72,7 +72,7 @@
 
     if (!nativeBuffer) return BAD_VALUE;
     if (mCurrentLockedBuffers == mMaxLockedBuffers) {
-        CC_LOGW("Max buffers have been locked (%d), cannot lock anymore.",
+        CC_LOGW("Max buffers have been locked (%zd), cannot lock anymore.",
                 mMaxLockedBuffers);
         return NOT_ENOUGH_DATA;
     }
@@ -153,7 +153,7 @@
     }
 
     size_t lockedIdx = 0;
-    for (; lockedIdx < mMaxLockedBuffers; lockedIdx++) {
+    for (; lockedIdx < static_cast<size_t>(mMaxLockedBuffers); lockedIdx++) {
         if (mAcquiredBuffers[lockedIdx].mSlot ==
                 BufferQueue::INVALID_BUFFER_SLOT) {
             break;
@@ -172,7 +172,7 @@
     nativeBuffer->height = mSlots[buf].mGraphicBuffer->getHeight();
     nativeBuffer->format = mSlots[buf].mGraphicBuffer->getPixelFormat();
     nativeBuffer->stride = (ycbcr.y != NULL) ?
-            ycbcr.ystride :
+            static_cast<uint32_t>(ycbcr.ystride) :
             mSlots[buf].mGraphicBuffer->getStride();
 
     nativeBuffer->crop        = b.mCrop;
@@ -183,8 +183,8 @@
 
     nativeBuffer->dataCb       = reinterpret_cast<uint8_t*>(ycbcr.cb);
     nativeBuffer->dataCr       = reinterpret_cast<uint8_t*>(ycbcr.cr);
-    nativeBuffer->chromaStride = ycbcr.cstride;
-    nativeBuffer->chromaStep   = ycbcr.chroma_step;
+    nativeBuffer->chromaStride = static_cast<uint32_t>(ycbcr.cstride);
+    nativeBuffer->chromaStep   = static_cast<uint32_t>(ycbcr.chroma_step);
 
     mCurrentLockedBuffers++;
 
@@ -194,10 +194,9 @@
 status_t CpuConsumer::unlockBuffer(const LockedBuffer &nativeBuffer) {
     Mutex::Autolock _l(mMutex);
     size_t lockedIdx = 0;
-    status_t err;
 
     void *bufPtr = reinterpret_cast<void *>(nativeBuffer.data);
-    for (; lockedIdx < mMaxLockedBuffers; lockedIdx++) {
+    for (; lockedIdx < static_cast<size_t>(mMaxLockedBuffers); lockedIdx++) {
         if (bufPtr == mAcquiredBuffers[lockedIdx].mBufferPointer) break;
     }
     if (lockedIdx == mMaxLockedBuffers) {
@@ -208,13 +207,13 @@
     return releaseAcquiredBufferLocked(lockedIdx);
 }
 
-status_t CpuConsumer::releaseAcquiredBufferLocked(int lockedIdx) {
+status_t CpuConsumer::releaseAcquiredBufferLocked(size_t lockedIdx) {
     status_t err;
     int fd = -1;
 
     err = mAcquiredBuffers[lockedIdx].mGraphicBuffer->unlockAsync(&fd);
     if (err != OK) {
-        CC_LOGE("%s: Unable to unlock graphic buffer %d", __FUNCTION__,
+        CC_LOGE("%s: Unable to unlock graphic buffer %zd", __FUNCTION__,
                 lockedIdx);
         return err;
     }
diff --git a/libs/gui/GLConsumer.cpp b/libs/gui/GLConsumer.cpp
index 6ba2ef8..936ad53 100644
--- a/libs/gui/GLConsumer.cpp
+++ b/libs/gui/GLConsumer.cpp
@@ -47,18 +47,28 @@
 namespace android {
 
 // Macros for including the GLConsumer name in log messages
-#define ST_LOGV(x, ...) ALOGV("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define ST_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define ST_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define ST_LOGW(x, ...) ALOGW("[%s] " x, mName.string(), ##__VA_ARGS__)
-#define ST_LOGE(x, ...) ALOGE("[%s] " x, mName.string(), ##__VA_ARGS__)
+#define GLC_LOGV(x, ...) ALOGV("[%s] " x, mName.string(), ##__VA_ARGS__)
+#define GLC_LOGD(x, ...) ALOGD("[%s] " x, mName.string(), ##__VA_ARGS__)
+//#define GLC_LOGI(x, ...) ALOGI("[%s] " x, mName.string(), ##__VA_ARGS__)
+#define GLC_LOGW(x, ...) ALOGW("[%s] " x, mName.string(), ##__VA_ARGS__)
+#define GLC_LOGE(x, ...) ALOGE("[%s] " x, mName.string(), ##__VA_ARGS__)
 
 static const struct {
-    size_t width, height;
+    uint32_t width, height;
     char const* bits;
 } kDebugData = { 15, 12,
-    "___________________________________XX_XX_______X_X_____X_X____X_XXXXXXX_X____XXXXXXXXXXX__"
-    "___XX_XXX_XX_______XXXXXXX_________X___X_________X_____X__________________________________"
+    "_______________"
+    "_______________"
+    "_____XX_XX_____"
+    "__X_X_____X_X__"
+    "__X_XXXXXXX_X__"
+    "__XXXXXXXXXXX__"
+    "___XX_XXX_XX___"
+    "____XXXXXXX____"
+    "_____X___X_____"
+    "____X_____X____"
+    "_______________"
+    "_______________"
 };
 
 // Transform matrices
@@ -135,7 +145,7 @@
     mCurrentTexture(BufferQueue::INVALID_BUFFER_SLOT),
     mAttached(true)
 {
-    ST_LOGV("GLConsumer");
+    GLC_LOGV("GLConsumer");
 
     memcpy(mCurrentTransformMatrix, mtxIdentity,
             sizeof(mCurrentTransformMatrix));
@@ -154,7 +164,7 @@
     mDefaultWidth(1),
     mDefaultHeight(1),
     mFilteringEnabled(true),
-    mTexName(-1),
+    mTexName(0),
     mUseFenceSync(useFenceSync),
     mTexTarget(texTarget),
     mEglDisplay(EGL_NO_DISPLAY),
@@ -162,7 +172,7 @@
     mCurrentTexture(BufferQueue::INVALID_BUFFER_SLOT),
     mAttached(false)
 {
-    ST_LOGV("GLConsumer");
+    GLC_LOGV("GLConsumer");
 
     memcpy(mCurrentTransformMatrix, mtxIdentity,
             sizeof(mCurrentTransformMatrix));
@@ -186,11 +196,11 @@
 
 status_t GLConsumer::updateTexImage() {
     ATRACE_CALL();
-    ST_LOGV("updateTexImage");
+    GLC_LOGV("updateTexImage");
     Mutex::Autolock lock(mMutex);
 
     if (mAbandoned) {
-        ST_LOGE("updateTexImage: GLConsumer is abandoned!");
+        GLC_LOGE("updateTexImage: GLConsumer is abandoned!");
         return NO_INIT;
     }
 
@@ -209,11 +219,11 @@
     if (err != NO_ERROR) {
         if (err == BufferQueue::NO_BUFFER_AVAILABLE) {
             // We always bind the texture even if we don't update its contents.
-            ST_LOGV("updateTexImage: no buffers were available");
+            GLC_LOGV("updateTexImage: no buffers were available");
             glBindTexture(mTexTarget, mTexName);
             err = NO_ERROR;
         } else {
-            ST_LOGE("updateTexImage: acquire failed: %s (%d)",
+            GLC_LOGE("updateTexImage: acquire failed: %s (%d)",
                 strerror(-err), err);
         }
         return err;
@@ -234,11 +244,11 @@
 
 status_t GLConsumer::releaseTexImage() {
     ATRACE_CALL();
-    ST_LOGV("releaseTexImage");
+    GLC_LOGV("releaseTexImage");
     Mutex::Autolock lock(mMutex);
 
     if (mAbandoned) {
-        ST_LOGE("releaseTexImage: GLConsumer is abandoned!");
+        GLC_LOGE("releaseTexImage: GLConsumer is abandoned!");
         return NO_INIT;
     }
 
@@ -258,13 +268,13 @@
     int buf = mCurrentTexture;
     if (buf != BufferQueue::INVALID_BUFFER_SLOT) {
 
-        ST_LOGV("releaseTexImage: (slot=%d, mAttached=%d)", buf, mAttached);
+        GLC_LOGV("releaseTexImage: (slot=%d, mAttached=%d)", buf, mAttached);
 
         if (mAttached) {
             // Do whatever sync ops we need to do before releasing the slot.
             err = syncForReleaseLocked(mEglDisplay);
             if (err != NO_ERROR) {
-                ST_LOGE("syncForReleaseLocked failed (slot=%d), err=%d", buf, err);
+                GLC_LOGE("syncForReleaseLocked failed (slot=%d), err=%d", buf, err);
                 return err;
             }
         } else {
@@ -274,7 +284,7 @@
 
         err = releaseBufferLocked(buf, mSlots[buf].mGraphicBuffer, mEglDisplay, EGL_NO_SYNC_KHR);
         if (err < NO_ERROR) {
-            ST_LOGE("releaseTexImage: failed to release buffer: %s (%d)",
+            GLC_LOGE("releaseTexImage: failed to release buffer: %s (%d)",
                     strerror(-err), err);
             return err;
         }
@@ -293,9 +303,9 @@
 
         if (mAttached) {
             // This binds a dummy buffer (mReleasedTexImage).
-            status_t err =  bindTextureImageLocked();
-            if (err != NO_ERROR) {
-                return err;
+            status_t result = bindTextureImageLocked();
+            if (result != NO_ERROR) {
+                return result;
             }
         } else {
             // detached, don't touch the texture (and we may not even have an
@@ -316,14 +326,15 @@
                 GraphicBuffer::USAGE_SW_WRITE_RARELY);
         uint32_t* bits;
         buffer->lock(GraphicBuffer::USAGE_SW_WRITE_RARELY, reinterpret_cast<void**>(&bits));
-        size_t w = buffer->getStride();
-        size_t h = buffer->getHeight();
-        memset(bits, 0, w*h*4);
-        for (size_t y=0 ; y<kDebugData.height ; y++) {
-            for (size_t x=0 ; x<kDebugData.width ; x++) {
-                bits[x] = (kDebugData.bits[y*kDebugData.width+x] == 'X') ? 0xFF000000 : 0xFFFFFFFF;
+        uint32_t stride = buffer->getStride();
+        uint32_t height = buffer->getHeight();
+        memset(bits, 0, stride * height * 4);
+        for (uint32_t y = 0; y < kDebugData.height; y++) {
+            for (uint32_t x = 0; x < kDebugData.width; x++) {
+                bits[x] = (kDebugData.bits[y + kDebugData.width + x] == 'X') ?
+                    0xFF000000 : 0xFFFFFFFF;
             }
-            bits += w;
+            bits += stride;
         }
         buffer->unlock();
         sReleasedTexImageBuffer = buffer;
@@ -369,7 +380,7 @@
     int buf = item.mBuf;
 
     if (!mAttached) {
-        ST_LOGE("updateAndRelease: GLConsumer is not attached to an OpenGL "
+        GLC_LOGE("updateAndRelease: GLConsumer is not attached to an OpenGL "
                 "ES context");
         releaseBufferLocked(buf, mSlots[buf].mGraphicBuffer,
                 mEglDisplay, EGL_NO_SYNC_KHR);
@@ -391,7 +402,7 @@
     // means the buffer was previously acquired).
     err = mEglSlots[buf].mEglImage->createIfNeeded(mEglDisplay, item.mCrop);
     if (err != NO_ERROR) {
-        ST_LOGW("updateAndRelease: unable to createImage on display=%p slot=%d",
+        GLC_LOGW("updateAndRelease: unable to createImage on display=%p slot=%d",
                 mEglDisplay, buf);
         releaseBufferLocked(buf, mSlots[buf].mGraphicBuffer,
                 mEglDisplay, EGL_NO_SYNC_KHR);
@@ -410,7 +421,7 @@
         return err;
     }
 
-    ST_LOGV("updateAndRelease: (slot=%d buf=%p) -> (slot=%d buf=%p)",
+    GLC_LOGV("updateAndRelease: (slot=%d buf=%p) -> (slot=%d buf=%p)",
             mCurrentTexture, mCurrentTextureImage != NULL ?
                     mCurrentTextureImage->graphicBufferHandle() : 0,
             buf, mSlots[buf].mGraphicBuffer->handle);
@@ -421,7 +432,7 @@
                 mCurrentTexture, mCurrentTextureImage->graphicBuffer(),
                 mEglDisplay, mEglSlots[mCurrentTexture].mEglFence);
         if (status < NO_ERROR) {
-            ST_LOGE("updateAndRelease: failed to release buffer: %s (%d)",
+            GLC_LOGE("updateAndRelease: failed to release buffer: %s (%d)",
                    strerror(-status), status);
             err = status;
             // keep going, with error raised [?]
@@ -449,22 +460,22 @@
         return INVALID_OPERATION;
     }
 
-    GLint error;
+    GLenum error;
     while ((error = glGetError()) != GL_NO_ERROR) {
-        ST_LOGW("bindTextureImage: clearing GL error: %#04x", error);
+        GLC_LOGW("bindTextureImage: clearing GL error: %#04x", error);
     }
 
     glBindTexture(mTexTarget, mTexName);
     if (mCurrentTexture == BufferQueue::INVALID_BUFFER_SLOT &&
             mCurrentTextureImage == NULL) {
-        ST_LOGE("bindTextureImage: no currently-bound texture");
+        GLC_LOGE("bindTextureImage: no currently-bound texture");
         return NO_INIT;
     }
 
     status_t err = mCurrentTextureImage->createIfNeeded(mEglDisplay,
                                                         mCurrentCrop);
     if (err != NO_ERROR) {
-        ST_LOGW("bindTextureImage: can't create image on display=%p slot=%d",
+        GLC_LOGW("bindTextureImage: can't create image on display=%p slot=%d",
                 mEglDisplay, mCurrentTexture);
         return UNKNOWN_ERROR;
     }
@@ -476,17 +487,17 @@
     // forcing the creation of a new image.
     if ((error = glGetError()) != GL_NO_ERROR) {
         glBindTexture(mTexTarget, mTexName);
-        status_t err = mCurrentTextureImage->createIfNeeded(mEglDisplay,
-                                                            mCurrentCrop,
-                                                            true);
-        if (err != NO_ERROR) {
-            ST_LOGW("bindTextureImage: can't create image on display=%p slot=%d",
+        status_t result = mCurrentTextureImage->createIfNeeded(mEglDisplay,
+                                                               mCurrentCrop,
+                                                               true);
+        if (result != NO_ERROR) {
+            GLC_LOGW("bindTextureImage: can't create image on display=%p slot=%d",
                     mEglDisplay, mCurrentTexture);
             return UNKNOWN_ERROR;
         }
         mCurrentTextureImage->bindToTextureTarget(mTexTarget);
         if ((error = glGetError()) != GL_NO_ERROR) {
-            ST_LOGE("bindTextureImage: error binding external image: %#04x", error);
+            GLC_LOGE("bindTextureImage: error binding external image: %#04x", error);
             return UNKNOWN_ERROR;
         }
     }
@@ -511,12 +522,12 @@
     }
 
     if (mEglDisplay != dpy || dpy == EGL_NO_DISPLAY) {
-        ST_LOGE("checkAndUpdateEglState: invalid current EGLDisplay");
+        GLC_LOGE("checkAndUpdateEglState: invalid current EGLDisplay");
         return INVALID_OPERATION;
     }
 
     if (mEglContext != ctx || ctx == EGL_NO_CONTEXT) {
-        ST_LOGE("checkAndUpdateEglState: invalid current EGLContext");
+        GLC_LOGE("checkAndUpdateEglState: invalid current EGLContext");
         return INVALID_OPERATION;
     }
 
@@ -531,7 +542,7 @@
         status_t err = addReleaseFence(mCurrentTexture,
                 mCurrentTextureImage->graphicBuffer(), fence);
         if (err != OK) {
-            ST_LOGE("setReleaseFence: failed to add the fence: %s (%d)",
+            GLC_LOGE("setReleaseFence: failed to add the fence: %s (%d)",
                     strerror(-err), err);
         }
     }
@@ -539,16 +550,16 @@
 
 status_t GLConsumer::detachFromContext() {
     ATRACE_CALL();
-    ST_LOGV("detachFromContext");
+    GLC_LOGV("detachFromContext");
     Mutex::Autolock lock(mMutex);
 
     if (mAbandoned) {
-        ST_LOGE("detachFromContext: abandoned GLConsumer");
+        GLC_LOGE("detachFromContext: abandoned GLConsumer");
         return NO_INIT;
     }
 
     if (!mAttached) {
-        ST_LOGE("detachFromContext: GLConsumer is not attached to a "
+        GLC_LOGE("detachFromContext: GLConsumer is not attached to a "
                 "context");
         return INVALID_OPERATION;
     }
@@ -557,12 +568,12 @@
     EGLContext ctx = eglGetCurrentContext();
 
     if (mEglDisplay != dpy && mEglDisplay != EGL_NO_DISPLAY) {
-        ST_LOGE("detachFromContext: invalid current EGLDisplay");
+        GLC_LOGE("detachFromContext: invalid current EGLDisplay");
         return INVALID_OPERATION;
     }
 
     if (mEglContext != ctx && mEglContext != EGL_NO_CONTEXT) {
-        ST_LOGE("detachFromContext: invalid current EGLContext");
+        GLC_LOGE("detachFromContext: invalid current EGLContext");
         return INVALID_OPERATION;
     }
 
@@ -584,16 +595,16 @@
 
 status_t GLConsumer::attachToContext(uint32_t tex) {
     ATRACE_CALL();
-    ST_LOGV("attachToContext");
+    GLC_LOGV("attachToContext");
     Mutex::Autolock lock(mMutex);
 
     if (mAbandoned) {
-        ST_LOGE("attachToContext: abandoned GLConsumer");
+        GLC_LOGE("attachToContext: abandoned GLConsumer");
         return NO_INIT;
     }
 
     if (mAttached) {
-        ST_LOGE("attachToContext: GLConsumer is already attached to a "
+        GLC_LOGE("attachToContext: GLConsumer is already attached to a "
                 "context");
         return INVALID_OPERATION;
     }
@@ -602,12 +613,12 @@
     EGLContext ctx = eglGetCurrentContext();
 
     if (dpy == EGL_NO_DISPLAY) {
-        ST_LOGE("attachToContext: invalid current EGLDisplay");
+        GLC_LOGE("attachToContext: invalid current EGLDisplay");
         return INVALID_OPERATION;
     }
 
     if (ctx == EGL_NO_CONTEXT) {
-        ST_LOGE("attachToContext: invalid current EGLContext");
+        GLC_LOGE("attachToContext: invalid current EGLContext");
         return INVALID_OPERATION;
     }
 
@@ -636,14 +647,14 @@
 
 
 status_t GLConsumer::syncForReleaseLocked(EGLDisplay dpy) {
-    ST_LOGV("syncForReleaseLocked");
+    GLC_LOGV("syncForReleaseLocked");
 
     if (mCurrentTexture != BufferQueue::INVALID_BUFFER_SLOT) {
         if (SyncFeatures::getInstance().useNativeFenceSync()) {
             EGLSyncKHR sync = eglCreateSyncKHR(dpy,
                     EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
             if (sync == EGL_NO_SYNC_KHR) {
-                ST_LOGE("syncForReleaseLocked: error creating EGL fence: %#x",
+                GLC_LOGE("syncForReleaseLocked: error creating EGL fence: %#x",
                         eglGetError());
                 return UNKNOWN_ERROR;
             }
@@ -651,7 +662,7 @@
             int fenceFd = eglDupNativeFenceFDANDROID(dpy, sync);
             eglDestroySyncKHR(dpy, sync);
             if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
-                ST_LOGE("syncForReleaseLocked: error dup'ing native fence "
+                GLC_LOGE("syncForReleaseLocked: error dup'ing native fence "
                         "fd: %#x", eglGetError());
                 return UNKNOWN_ERROR;
             }
@@ -659,7 +670,7 @@
             status_t err = addReleaseFenceLocked(mCurrentTexture,
                     mCurrentTextureImage->graphicBuffer(), fence);
             if (err != OK) {
-                ST_LOGE("syncForReleaseLocked: error adding release fence: "
+                GLC_LOGE("syncForReleaseLocked: error adding release fence: "
                         "%s (%d)", strerror(-err), err);
                 return err;
             }
@@ -672,11 +683,11 @@
                 // before the producer accesses it.
                 EGLint result = eglClientWaitSyncKHR(dpy, fence, 0, 1000000000);
                 if (result == EGL_FALSE) {
-                    ST_LOGE("syncForReleaseLocked: error waiting for previous "
+                    GLC_LOGE("syncForReleaseLocked: error waiting for previous "
                             "fence: %#x", eglGetError());
                     return UNKNOWN_ERROR;
                 } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
-                    ST_LOGE("syncForReleaseLocked: timeout waiting for previous "
+                    GLC_LOGE("syncForReleaseLocked: timeout waiting for previous "
                             "fence");
                     return TIMED_OUT;
                 }
@@ -687,7 +698,7 @@
             // OpenGL ES context.
             fence = eglCreateSyncKHR(dpy, EGL_SYNC_FENCE_KHR, NULL);
             if (fence == EGL_NO_SYNC_KHR) {
-                ST_LOGE("syncForReleaseLocked: error creating fence: %#x",
+                GLC_LOGE("syncForReleaseLocked: error creating fence: %#x",
                         eglGetError());
                 return UNKNOWN_ERROR;
             }
@@ -699,7 +710,7 @@
     return OK;
 }
 
-bool GLConsumer::isExternalFormat(uint32_t format)
+bool GLConsumer::isExternalFormat(PixelFormat format)
 {
     switch (format) {
     // supported YUV formats
@@ -730,14 +741,14 @@
 void GLConsumer::setFilteringEnabled(bool enabled) {
     Mutex::Autolock lock(mMutex);
     if (mAbandoned) {
-        ST_LOGE("setFilteringEnabled: GLConsumer is abandoned!");
+        GLC_LOGE("setFilteringEnabled: GLConsumer is abandoned!");
         return;
     }
     bool needsRecompute = mFilteringEnabled != enabled;
     mFilteringEnabled = enabled;
 
     if (needsRecompute && mCurrentTextureImage==NULL) {
-        ST_LOGD("setFilteringEnabled called with mCurrentTextureImage == NULL");
+        GLC_LOGD("setFilteringEnabled called with mCurrentTextureImage == NULL");
     }
 
     if (needsRecompute && mCurrentTextureImage != NULL) {
@@ -746,7 +757,7 @@
 }
 
 void GLConsumer::computeCurrentTransformMatrixLocked() {
-    ST_LOGV("computeCurrentTransformMatrixLocked");
+    GLC_LOGV("computeCurrentTransformMatrixLocked");
 
     float xform[16];
     for (int i = 0; i < 16; i++) {
@@ -778,7 +789,7 @@
             NULL : mCurrentTextureImage->graphicBuffer();
 
     if (buf == NULL) {
-        ST_LOGD("computeCurrentTransformMatrixLocked: mCurrentTextureImage is NULL");
+        GLC_LOGD("computeCurrentTransformMatrixLocked: mCurrentTextureImage is NULL");
     }
 
     float mtxBeforeFlipV[16];
@@ -850,13 +861,13 @@
 }
 
 nsecs_t GLConsumer::getTimestamp() {
-    ST_LOGV("getTimestamp");
+    GLC_LOGV("getTimestamp");
     Mutex::Autolock lock(mMutex);
     return mCurrentTimestamp;
 }
 
-nsecs_t GLConsumer::getFrameNumber() {
-    ST_LOGV("getFrameNumber");
+uint64_t GLConsumer::getFrameNumber() {
+    GLC_LOGV("getFrameNumber");
     Mutex::Autolock lock(mMutex);
     return mCurrentFrameNumber;
 }
@@ -872,30 +883,33 @@
 
     Rect outCrop = mCurrentCrop;
     if (mCurrentScalingMode == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP) {
-        int32_t newWidth = mCurrentCrop.width();
-        int32_t newHeight = mCurrentCrop.height();
+        uint32_t newWidth = static_cast<uint32_t>(mCurrentCrop.width());
+        uint32_t newHeight = static_cast<uint32_t>(mCurrentCrop.height());
 
         if (newWidth * mDefaultHeight > newHeight * mDefaultWidth) {
             newWidth = newHeight * mDefaultWidth / mDefaultHeight;
-            ST_LOGV("too wide: newWidth = %d", newWidth);
+            GLC_LOGV("too wide: newWidth = %d", newWidth);
         } else if (newWidth * mDefaultHeight < newHeight * mDefaultWidth) {
             newHeight = newWidth * mDefaultHeight / mDefaultWidth;
-            ST_LOGV("too tall: newHeight = %d", newHeight);
+            GLC_LOGV("too tall: newHeight = %d", newHeight);
         }
 
+        uint32_t currentWidth = static_cast<uint32_t>(mCurrentCrop.width());
+        uint32_t currentHeight = static_cast<uint32_t>(mCurrentCrop.height());
+
         // The crop is too wide
-        if (newWidth < mCurrentCrop.width()) {
-            int32_t dw = (newWidth - mCurrentCrop.width())/2;
+        if (newWidth < currentWidth) {
+            uint32_t dw = (newWidth - currentWidth) / 2;
             outCrop.left -=dw;
             outCrop.right += dw;
         // The crop is too tall
-        } else if (newHeight < mCurrentCrop.height()) {
-            int32_t dh = (newHeight - mCurrentCrop.height())/2;
+        } else if (newHeight < currentHeight) {
+            uint32_t dh = (newHeight - currentHeight) / 2;
             outCrop.top -= dh;
             outCrop.bottom += dh;
         }
 
-        ST_LOGV("getCurrentCrop final crop [%d,%d,%d,%d]",
+        GLC_LOGV("getCurrentCrop final crop [%d,%d,%d,%d]",
             outCrop.left, outCrop.top,
             outCrop.right,outCrop.bottom);
     }
@@ -929,12 +943,12 @@
     EGLContext ctx = eglGetCurrentContext();
 
     if (mEglDisplay != dpy || mEglDisplay == EGL_NO_DISPLAY) {
-        ST_LOGE("doGLFenceWait: invalid current EGLDisplay");
+        GLC_LOGE("doGLFenceWait: invalid current EGLDisplay");
         return INVALID_OPERATION;
     }
 
     if (mEglContext != ctx || mEglContext == EGL_NO_CONTEXT) {
-        ST_LOGE("doGLFenceWait: invalid current EGLContext");
+        GLC_LOGE("doGLFenceWait: invalid current EGLContext");
         return INVALID_OPERATION;
     }
 
@@ -943,7 +957,7 @@
             // Create an EGLSyncKHR from the current fence.
             int fenceFd = mCurrentFence->dup();
             if (fenceFd == -1) {
-                ST_LOGE("doGLFenceWait: error dup'ing fence fd: %d", errno);
+                GLC_LOGE("doGLFenceWait: error dup'ing fence fd: %d", errno);
                 return -errno;
             }
             EGLint attribs[] = {
@@ -954,7 +968,7 @@
                     EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
             if (sync == EGL_NO_SYNC_KHR) {
                 close(fenceFd);
-                ST_LOGE("doGLFenceWait: error creating EGL fence: %#x",
+                GLC_LOGE("doGLFenceWait: error creating EGL fence: %#x",
                         eglGetError());
                 return UNKNOWN_ERROR;
             }
@@ -966,7 +980,7 @@
             EGLint eglErr = eglGetError();
             eglDestroySyncKHR(dpy, sync);
             if (eglErr != EGL_SUCCESS) {
-                ST_LOGE("doGLFenceWait: error waiting for EGL fence: %#x",
+                GLC_LOGE("doGLFenceWait: error waiting for EGL fence: %#x",
                         eglErr);
                 return UNKNOWN_ERROR;
             }
@@ -974,7 +988,7 @@
             status_t err = mCurrentFence->waitForever(
                     "GLConsumer::doGLFenceWaitLocked");
             if (err != NO_ERROR) {
-                ST_LOGE("doGLFenceWait: error waiting for fence: %d", err);
+                GLC_LOGE("doGLFenceWait: error waiting for fence: %d", err);
                 return err;
             }
         }
@@ -984,7 +998,7 @@
 }
 
 void GLConsumer::freeBufferLocked(int slotIndex) {
-    ST_LOGV("freeBufferLocked: slotIndex=%d", slotIndex);
+    GLC_LOGV("freeBufferLocked: slotIndex=%d", slotIndex);
     if (slotIndex == mCurrentTexture) {
         mCurrentTexture = BufferQueue::INVALID_BUFFER_SLOT;
     }
@@ -993,7 +1007,7 @@
 }
 
 void GLConsumer::abandonLocked() {
-    ST_LOGV("abandonLocked");
+    GLC_LOGV("abandonLocked");
     mCurrentTextureImage.clear();
     ConsumerBase::abandonLocked();
 }
@@ -1004,7 +1018,7 @@
     mConsumer->setConsumerName(name);
 }
 
-status_t GLConsumer::setDefaultBufferFormat(uint32_t defaultFormat) {
+status_t GLConsumer::setDefaultBufferFormat(PixelFormat defaultFormat) {
     Mutex::Autolock lock(mMutex);
     return mConsumer->setDefaultBufferFormat(defaultFormat);
 }
@@ -1105,12 +1119,14 @@
 }
 
 void GLConsumer::EglImage::bindToTextureTarget(uint32_t texTarget) {
-    glEGLImageTargetTexture2DOES(texTarget, (GLeglImageOES)mEglImage);
+    glEGLImageTargetTexture2DOES(texTarget,
+            static_cast<GLeglImageOES>(mEglImage));
 }
 
 EGLImageKHR GLConsumer::EglImage::createImage(EGLDisplay dpy,
         const sp<GraphicBuffer>& graphicBuffer, const Rect& crop) {
-    EGLClientBuffer cbuf = (EGLClientBuffer)graphicBuffer->getNativeBuffer();
+    EGLClientBuffer cbuf =
+            static_cast<EGLClientBuffer>(graphicBuffer->getNativeBuffer());
     EGLint attrs[] = {
         EGL_IMAGE_PRESERVED_KHR,        EGL_TRUE,
         EGL_IMAGE_CROP_LEFT_ANDROID,    crop.left,
diff --git a/libs/gui/GraphicBufferAlloc.cpp b/libs/gui/GraphicBufferAlloc.cpp
index b360e81..9643402 100644
--- a/libs/gui/GraphicBufferAlloc.cpp
+++ b/libs/gui/GraphicBufferAlloc.cpp
@@ -31,9 +31,10 @@
 GraphicBufferAlloc::~GraphicBufferAlloc() {
 }
 
-sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h,
-        PixelFormat format, uint32_t usage, status_t* error) {
-    sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage));
+sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t width,
+        uint32_t height, PixelFormat format, uint32_t usage, status_t* error) {
+    sp<GraphicBuffer> graphicBuffer(
+            new GraphicBuffer(width, height, format, usage));
     status_t err = graphicBuffer->initCheck();
     *error = err;
     if (err != 0 || graphicBuffer->handle == 0) {
@@ -42,7 +43,7 @@
         }
         ALOGE("GraphicBufferAlloc::createGraphicBuffer(w=%d, h=%d) "
              "failed (%s), handle=%p",
-                w, h, strerror(-err), graphicBuffer->handle);
+                width, height, strerror(-err), graphicBuffer->handle);
         return 0;
     }
     return graphicBuffer;
diff --git a/libs/gui/IConsumerListener.cpp b/libs/gui/IConsumerListener.cpp
index 4ccf0ac..32d7920 100644
--- a/libs/gui/IConsumerListener.cpp
+++ b/libs/gui/IConsumerListener.cpp
@@ -39,6 +39,8 @@
         : BpInterface<IConsumerListener>(impl) {
     }
 
+    virtual ~BpConsumerListener();
+
     virtual void onFrameAvailable() {
         Parcel data, reply;
         data.writeInterfaceToken(IConsumerListener::getInterfaceDescriptor());
@@ -58,6 +60,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpConsumerListener::~BpConsumerListener() {}
+
 IMPLEMENT_META_INTERFACE(ConsumerListener, "android.gui.IConsumerListener");
 
 // ----------------------------------------------------------------------
diff --git a/libs/gui/IDisplayEventConnection.cpp b/libs/gui/IDisplayEventConnection.cpp
index 887d176..9890f44 100644
--- a/libs/gui/IDisplayEventConnection.cpp
+++ b/libs/gui/IDisplayEventConnection.cpp
@@ -44,6 +44,8 @@
     {
     }
 
+    virtual ~BpDisplayEventConnection();
+
     virtual sp<BitTube> getDataChannel() const
     {
         Parcel data, reply;
@@ -55,7 +57,7 @@
     virtual void setVsyncRate(uint32_t count) {
         Parcel data, reply;
         data.writeInterfaceToken(IDisplayEventConnection::getInterfaceDescriptor());
-        data.writeInt32(count);
+        data.writeUint32(count);
         remote()->transact(SET_VSYNC_RATE, data, &reply);
     }
 
@@ -66,6 +68,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpDisplayEventConnection::~BpDisplayEventConnection() {}
+
 IMPLEMENT_META_INTERFACE(DisplayEventConnection, "android.gui.DisplayEventConnection");
 
 // ----------------------------------------------------------------------------
@@ -79,17 +85,17 @@
             sp<BitTube> channel(getDataChannel());
             channel->writeToParcel(reply);
             return NO_ERROR;
-        } break;
+        }
         case SET_VSYNC_RATE: {
             CHECK_INTERFACE(IDisplayEventConnection, data, reply);
-            setVsyncRate(data.readInt32());
+            setVsyncRate(data.readUint32());
             return NO_ERROR;
-        } break;
+        }
         case REQUEST_NEXT_VSYNC: {
             CHECK_INTERFACE(IDisplayEventConnection, data, reply);
             requestNextVsync();
             return NO_ERROR;
-        } break;
+        }
     }
     return BBinder::onTransact(code, data, reply, flags);
 }
diff --git a/libs/gui/IGraphicBufferAlloc.cpp b/libs/gui/IGraphicBufferAlloc.cpp
index 139f219..09b63a1 100644
--- a/libs/gui/IGraphicBufferAlloc.cpp
+++ b/libs/gui/IGraphicBufferAlloc.cpp
@@ -42,14 +42,17 @@
     {
     }
 
-    virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t w, uint32_t h,
-            PixelFormat format, uint32_t usage, status_t* error) {
+    virtual ~BpGraphicBufferAlloc();
+
+    virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t width,
+            uint32_t height, PixelFormat format, uint32_t usage,
+            status_t* error) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferAlloc::getInterfaceDescriptor());
-        data.writeInt32(w);
-        data.writeInt32(h);
-        data.writeInt32(format);
-        data.writeInt32(usage);
+        data.writeUint32(width);
+        data.writeUint32(height);
+        data.writeInt32(static_cast<int32_t>(format));
+        data.writeUint32(usage);
         remote()->transact(CREATE_GRAPHIC_BUFFER, data, &reply);
         sp<GraphicBuffer> graphicBuffer;
         status_t result = reply.readInt32();
@@ -65,6 +68,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpGraphicBufferAlloc::~BpGraphicBufferAlloc() {}
+
 IMPLEMENT_META_INTERFACE(GraphicBufferAlloc, "android.ui.IGraphicBufferAlloc");
 
 // ----------------------------------------------------------------------
@@ -74,27 +81,26 @@
 {
     // codes that don't require permission check
 
-    /* BufferReference just keeps a strong reference to a
-     * GraphicBuffer until it is destroyed (that is, until
-     * no local or remote process have a reference to it).
-     */
+    // BufferReference just keeps a strong reference to a GraphicBuffer until it
+    // is destroyed (that is, until no local or remote process have a reference
+    // to it).
     class BufferReference : public BBinder {
-        sp<GraphicBuffer> buffer;
+        sp<GraphicBuffer> mBuffer;
     public:
-        BufferReference(const sp<GraphicBuffer>& buffer) : buffer(buffer) { }
+        BufferReference(const sp<GraphicBuffer>& buffer) : mBuffer(buffer) {}
     };
 
 
-    switch(code) {
+    switch (code) {
         case CREATE_GRAPHIC_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferAlloc, data, reply);
-            uint32_t w = data.readInt32();
-            uint32_t h = data.readInt32();
-            PixelFormat format = data.readInt32();
-            uint32_t usage = data.readInt32();
+            uint32_t width = data.readUint32();
+            uint32_t height = data.readUint32();
+            PixelFormat format = static_cast<PixelFormat>(data.readInt32());
+            uint32_t usage = data.readUint32();
             status_t error;
             sp<GraphicBuffer> result =
-                    createGraphicBuffer(w, h, format, usage, &error);
+                    createGraphicBuffer(width, height, format, usage, &error);
             reply->writeInt32(error);
             if (result != 0) {
                 reply->write(*result);
@@ -107,7 +113,7 @@
                 reply->writeStrongBinder( new BufferReference(result) );
             }
             return NO_ERROR;
-        } break;
+        }
         default:
             return BBinder::onTransact(code, data, reply, flags);
     }
diff --git a/libs/gui/IGraphicBufferConsumer.cpp b/libs/gui/IGraphicBufferConsumer.cpp
index f6d087d..2602884 100644
--- a/libs/gui/IGraphicBufferConsumer.cpp
+++ b/libs/gui/IGraphicBufferConsumer.cpp
@@ -215,6 +215,8 @@
     {
     }
 
+    virtual ~BpGraphicBufferConsumer();
+
     virtual status_t acquireBuffer(BufferItem *buffer, nsecs_t presentWhen) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor());
@@ -261,7 +263,7 @@
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor());
         data.writeInt32(buf);
-        data.writeInt64(frameNumber);
+        data.writeInt64(static_cast<int64_t>(frameNumber));
         data.write(*releaseFence);
         status_t result = remote()->transact(RELEASE_BUFFER, data, &reply);
         if (result != NO_ERROR) {
@@ -273,7 +275,7 @@
     virtual status_t consumerConnect(const sp<IConsumerListener>& consumer, bool controlledByApp) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor());
-        data.writeStrongBinder(consumer->asBinder());
+        data.writeStrongBinder(IInterface::asBinder(consumer));
         data.writeInt32(controlledByApp);
         status_t result = remote()->transact(CONSUMER_CONNECT, data, &reply);
         if (result != NO_ERROR) {
@@ -303,15 +305,15 @@
         if (result != NO_ERROR) {
             return result;
         }
-        *slotMask = reply.readInt64();
+        *slotMask = static_cast<uint64_t>(reply.readInt64());
         return reply.readInt32();
     }
 
-    virtual status_t setDefaultBufferSize(uint32_t w, uint32_t h) {
+    virtual status_t setDefaultBufferSize(uint32_t width, uint32_t height) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor());
-        data.writeInt32(w);
-        data.writeInt32(h);
+        data.writeUint32(width);
+        data.writeUint32(height);
         status_t result = remote()->transact(SET_DEFAULT_BUFFER_SIZE, data, &reply);
         if (result != NO_ERROR) {
             return result;
@@ -358,10 +360,10 @@
         remote()->transact(SET_CONSUMER_NAME, data, &reply);
     }
 
-    virtual status_t setDefaultBufferFormat(uint32_t defaultFormat) {
+    virtual status_t setDefaultBufferFormat(PixelFormat defaultFormat) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor());
-        data.writeInt32(defaultFormat);
+        data.writeInt32(static_cast<int32_t>(defaultFormat));
         status_t result = remote()->transact(SET_DEFAULT_BUFFER_FORMAT, data, &reply);
         if (result != NO_ERROR) {
             return result;
@@ -372,7 +374,7 @@
     virtual status_t setConsumerUsageBits(uint32_t usage) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor());
-        data.writeInt32(usage);
+        data.writeUint32(usage);
         status_t result = remote()->transact(SET_CONSUMER_USAGE_BITS, data, &reply);
         if (result != NO_ERROR) {
             return result;
@@ -383,7 +385,7 @@
     virtual status_t setTransformHint(uint32_t hint) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferConsumer::getInterfaceDescriptor());
-        data.writeInt32(hint);
+        data.writeUint32(hint);
         status_t result = remote()->transact(SET_TRANSFORM_HINT, data, &reply);
         if (result != NO_ERROR) {
             return result;
@@ -415,6 +417,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpGraphicBufferConsumer::~BpGraphicBufferConsumer() {}
+
 IMPLEMENT_META_INTERFACE(GraphicBufferConsumer, "android.gui.IGraphicBufferConsumer");
 
 // ----------------------------------------------------------------------
@@ -432,14 +438,14 @@
             if (err) return err;
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case DETACH_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             int slot = data.readInt32();
             int result = detachBuffer(slot);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case ATTACH_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             sp<GraphicBuffer> buffer = new GraphicBuffer();
@@ -449,11 +455,11 @@
             reply->writeInt32(slot);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case RELEASE_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             int buf = data.readInt32();
-            uint64_t frameNumber = data.readInt64();
+            uint64_t frameNumber = static_cast<uint64_t>(data.readInt64());
             sp<Fence> releaseFence = new Fence();
             status_t err = data.read(*releaseFence);
             if (err) return err;
@@ -461,7 +467,7 @@
                     EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, releaseFence);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case CONSUMER_CONNECT: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             sp<IConsumerListener> consumer = IConsumerListener::asInterface( data.readStrongBinder() );
@@ -469,75 +475,75 @@
             status_t result = consumerConnect(consumer, controlledByApp);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case CONSUMER_DISCONNECT: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             status_t result = consumerDisconnect();
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case GET_RELEASED_BUFFERS: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             uint64_t slotMask;
             status_t result = getReleasedBuffers(&slotMask);
-            reply->writeInt64(slotMask);
+            reply->writeInt64(static_cast<int64_t>(slotMask));
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case SET_DEFAULT_BUFFER_SIZE: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
-            uint32_t w = data.readInt32();
-            uint32_t h = data.readInt32();
-            status_t result = setDefaultBufferSize(w, h);
+            uint32_t width = data.readUint32();
+            uint32_t height = data.readUint32();
+            status_t result = setDefaultBufferSize(width, height);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case SET_DEFAULT_MAX_BUFFER_COUNT: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
-            uint32_t bufferCount = data.readInt32();
+            int bufferCount = data.readInt32();
             status_t result = setDefaultMaxBufferCount(bufferCount);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case DISABLE_ASYNC_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             status_t result = disableAsyncBuffer();
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case SET_MAX_ACQUIRED_BUFFER_COUNT: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
-            uint32_t maxAcquiredBuffers = data.readInt32();
+            int maxAcquiredBuffers = data.readInt32();
             status_t result = setMaxAcquiredBufferCount(maxAcquiredBuffers);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case SET_CONSUMER_NAME: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             setConsumerName( data.readString8() );
             return NO_ERROR;
-        } break;
+        }
         case SET_DEFAULT_BUFFER_FORMAT: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
-            uint32_t defaultFormat = data.readInt32();
+            PixelFormat defaultFormat = static_cast<PixelFormat>(data.readInt32());
             status_t result = setDefaultBufferFormat(defaultFormat);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case SET_CONSUMER_USAGE_BITS: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
-            uint32_t usage = data.readInt32();
+            uint32_t usage = data.readUint32();
             status_t result = setConsumerUsageBits(usage);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case SET_TRANSFORM_HINT: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
-            uint32_t hint = data.readInt32();
+            uint32_t hint = data.readUint32();
             status_t result = setTransformHint(hint);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case DUMP: {
             CHECK_INTERFACE(IGraphicBufferConsumer, data, reply);
             String8 result = data.readString8();
diff --git a/libs/gui/IGraphicBufferProducer.cpp b/libs/gui/IGraphicBufferProducer.cpp
index 1e28f9b..63d881e 100644
--- a/libs/gui/IGraphicBufferProducer.cpp
+++ b/libs/gui/IGraphicBufferProducer.cpp
@@ -56,6 +56,8 @@
     {
     }
 
+    virtual ~BpGraphicBufferProducer();
+
     virtual status_t requestBuffer(int bufferIdx, sp<GraphicBuffer>* buf) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferProducer::getInterfaceDescriptor());
@@ -91,14 +93,15 @@
     }
 
     virtual status_t dequeueBuffer(int *buf, sp<Fence>* fence, bool async,
-            uint32_t w, uint32_t h, uint32_t format, uint32_t usage) {
+            uint32_t width, uint32_t height, PixelFormat format,
+            uint32_t usage) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferProducer::getInterfaceDescriptor());
-        data.writeInt32(async);
-        data.writeInt32(w);
-        data.writeInt32(h);
-        data.writeInt32(format);
-        data.writeInt32(usage);
+        data.writeInt32(static_cast<int32_t>(async));
+        data.writeUint32(width);
+        data.writeUint32(height);
+        data.writeInt32(static_cast<int32_t>(format));
+        data.writeUint32(usage);
         status_t result = remote()->transact(DEQUEUE_BUFFER, data, &reply);
         if (result != NO_ERROR) {
             return result;
@@ -211,7 +214,7 @@
         data.writeInterfaceToken(IGraphicBufferProducer::getInterfaceDescriptor());
         if (listener != NULL) {
             data.writeInt32(1);
-            data.writeStrongBinder(listener->asBinder());
+            data.writeStrongBinder(IInterface::asBinder(listener));
         } else {
             data.writeInt32(0);
         }
@@ -255,14 +258,14 @@
     }
 
     virtual void allocateBuffers(bool async, uint32_t width, uint32_t height,
-            uint32_t format, uint32_t usage) {
+            PixelFormat format, uint32_t usage) {
         Parcel data, reply;
         data.writeInterfaceToken(IGraphicBufferProducer::getInterfaceDescriptor());
         data.writeInt32(static_cast<int32_t>(async));
-        data.writeInt32(static_cast<int32_t>(width));
-        data.writeInt32(static_cast<int32_t>(height));
+        data.writeUint32(width);
+        data.writeUint32(height);
         data.writeInt32(static_cast<int32_t>(format));
-        data.writeInt32(static_cast<int32_t>(usage));
+        data.writeUint32(usage);
         status_t result = remote()->transact(ALLOCATE_BUFFERS, data, &reply);
         if (result != NO_ERROR) {
             ALOGE("allocateBuffers failed to transact: %d", result);
@@ -270,6 +273,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpGraphicBufferProducer::~BpGraphicBufferProducer() {}
+
 IMPLEMENT_META_INTERFACE(GraphicBufferProducer, "android.gui.IGraphicBufferProducer");
 
 // ----------------------------------------------------------------------
@@ -289,24 +296,25 @@
             }
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case SET_BUFFER_COUNT: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             int bufferCount = data.readInt32();
             int result = setBufferCount(bufferCount);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case DEQUEUE_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
-            bool async      = data.readInt32();
-            uint32_t w      = data.readInt32();
-            uint32_t h      = data.readInt32();
-            uint32_t format = data.readInt32();
-            uint32_t usage  = data.readInt32();
+            bool async = static_cast<bool>(data.readInt32());
+            uint32_t width = data.readUint32();
+            uint32_t height = data.readUint32();
+            PixelFormat format = static_cast<PixelFormat>(data.readInt32());
+            uint32_t usage = data.readUint32();
             int buf;
             sp<Fence> fence;
-            int result = dequeueBuffer(&buf, &fence, async, w, h, format, usage);
+            int result = dequeueBuffer(&buf, &fence, async, width, height,
+                    format, usage);
             reply->writeInt32(buf);
             reply->writeInt32(fence != NULL);
             if (fence != NULL) {
@@ -314,14 +322,14 @@
             }
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case DETACH_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             int slot = data.readInt32();
             int result = detachBuffer(slot);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case DETACH_NEXT_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             sp<GraphicBuffer> buffer;
@@ -339,7 +347,7 @@
                 }
             }
             return NO_ERROR;
-        } break;
+        }
         case ATTACH_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             sp<GraphicBuffer> buffer = new GraphicBuffer();
@@ -349,7 +357,7 @@
             reply->writeInt32(slot);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case QUEUE_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             int buf = data.readInt32();
@@ -360,7 +368,7 @@
             status_t result = queueBuffer(buf, input, output);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case CANCEL_BUFFER: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             int buf = data.readInt32();
@@ -368,7 +376,7 @@
             data.read(*fence.get());
             cancelBuffer(buf, fence);
             return NO_ERROR;
-        } break;
+        }
         case QUERY: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             int value;
@@ -377,7 +385,7 @@
             reply->writeInt32(value);
             reply->writeInt32(res);
             return NO_ERROR;
-        } break;
+        }
         case CONNECT: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             sp<IProducerListener> listener;
@@ -392,14 +400,14 @@
             status_t res = connect(listener, api, producerControlledByApp, output);
             reply->writeInt32(res);
             return NO_ERROR;
-        } break;
+        }
         case DISCONNECT: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             int api = data.readInt32();
             status_t res = disconnect(api);
             reply->writeInt32(res);
             return NO_ERROR;
-        } break;
+        }
         case SET_SIDEBAND_STREAM: {
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             sp<NativeHandle> stream;
@@ -409,14 +417,14 @@
             status_t result = setSidebandStream(stream);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case ALLOCATE_BUFFERS:
             CHECK_INTERFACE(IGraphicBufferProducer, data, reply);
             bool async = static_cast<bool>(data.readInt32());
-            uint32_t width = static_cast<uint32_t>(data.readInt32());
-            uint32_t height = static_cast<uint32_t>(data.readInt32());
-            uint32_t format = static_cast<uint32_t>(data.readInt32());
-            uint32_t usage = static_cast<uint32_t>(data.readInt32());
+            uint32_t width = data.readUint32();
+            uint32_t height = data.readUint32();
+            PixelFormat format = static_cast<PixelFormat>(data.readInt32());
+            uint32_t usage = data.readUint32();
             allocateBuffers(async, width, height, format, usage);
             return NO_ERROR;
     }
diff --git a/libs/gui/IProducerListener.cpp b/libs/gui/IProducerListener.cpp
index efe4069..81adc95 100644
--- a/libs/gui/IProducerListener.cpp
+++ b/libs/gui/IProducerListener.cpp
@@ -30,6 +30,8 @@
     BpProducerListener(const sp<IBinder>& impl)
         : BpInterface<IProducerListener>(impl) {}
 
+    virtual ~BpProducerListener();
+
     virtual void onBufferReleased() {
         Parcel data, reply;
         data.writeInterfaceToken(IProducerListener::getInterfaceDescriptor());
@@ -37,6 +39,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpProducerListener::~BpProducerListener() {}
+
 IMPLEMENT_META_INTERFACE(ProducerListener, "android.gui.IProducerListener")
 
 status_t BnProducerListener::onTransact(uint32_t code, const Parcel& data,
diff --git a/libs/gui/ISensorEventConnection.cpp b/libs/gui/ISensorEventConnection.cpp
index 28fcb53..dc7a35c 100644
--- a/libs/gui/ISensorEventConnection.cpp
+++ b/libs/gui/ISensorEventConnection.cpp
@@ -45,6 +45,8 @@
     {
     }
 
+    virtual ~BpSensorEventConnection();
+
     virtual sp<BitTube> getSensorChannel() const
     {
         Parcel data, reply;
@@ -85,6 +87,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpSensorEventConnection::~BpSensorEventConnection() {}
+
 IMPLEMENT_META_INTERFACE(SensorEventConnection, "android.gui.SensorEventConnection");
 
 // ----------------------------------------------------------------------------
@@ -98,7 +104,7 @@
             sp<BitTube> channel(getSensorChannel());
             channel->writeToParcel(reply);
             return NO_ERROR;
-        } break;
+        }
         case ENABLE_DISABLE: {
             CHECK_INTERFACE(ISensorEventConnection, data, reply);
             int handle = data.readInt32();
@@ -110,21 +116,21 @@
                                             maxBatchReportLatencyNs, reservedFlags);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case SET_EVENT_RATE: {
             CHECK_INTERFACE(ISensorEventConnection, data, reply);
             int handle = data.readInt32();
-            int ns = data.readInt64();
+            nsecs_t ns = data.readInt64();
             status_t result = setEventRate(handle, ns);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case FLUSH_SENSOR: {
             CHECK_INTERFACE(ISensorEventConnection, data, reply);
             status_t result = flush();
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
     }
     return BBinder::onTransact(code, data, reply, flags);
 }
diff --git a/libs/gui/ISensorServer.cpp b/libs/gui/ISensorServer.cpp
index 0b76f37..8e09e7c 100644
--- a/libs/gui/ISensorServer.cpp
+++ b/libs/gui/ISensorServer.cpp
@@ -45,6 +45,8 @@
     {
     }
 
+    virtual ~BpSensorServer();
+
     virtual Vector<Sensor> getSensorList()
     {
         Parcel data, reply;
@@ -52,7 +54,7 @@
         remote()->transact(GET_SENSOR_LIST, data, &reply);
         Sensor s;
         Vector<Sensor> v;
-        int32_t n = reply.readInt32();
+        uint32_t n = reply.readUint32();
         v.setCapacity(n);
         while (n--) {
             reply.read(s);
@@ -70,6 +72,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpSensorServer::~BpSensorServer() {}
+
 IMPLEMENT_META_INTERFACE(SensorServer, "android.gui.SensorServer");
 
 // ----------------------------------------------------------------------
@@ -82,18 +88,18 @@
             CHECK_INTERFACE(ISensorServer, data, reply);
             Vector<Sensor> v(getSensorList());
             size_t n = v.size();
-            reply->writeInt32(n);
-            for (size_t i=0 ; i<n ; i++) {
+            reply->writeUint32(static_cast<uint32_t>(n));
+            for (size_t i = 0; i < n; i++) {
                 reply->write(v[i]);
             }
             return NO_ERROR;
-        } break;
+        }
         case CREATE_SENSOR_EVENT_CONNECTION: {
             CHECK_INTERFACE(ISensorServer, data, reply);
             sp<ISensorEventConnection> connection(createSensorEventConnection());
-            reply->writeStrongBinder(connection->asBinder());
+            reply->writeStrongBinder(IInterface::asBinder(connection));
             return NO_ERROR;
-        } break;
+        }
     }
     return BBinder::onTransact(code, data, reply, flags);
 }
diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp
index 81e8336..78886d5 100644
--- a/libs/gui/ISurfaceComposer.cpp
+++ b/libs/gui/ISurfaceComposer.cpp
@@ -51,9 +51,10 @@
     {
     }
 
+    virtual ~BpSurfaceComposer();
+
     virtual sp<ISurfaceComposerClient> createConnection()
     {
-        uint32_t n;
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
         remote()->transact(BnSurfaceComposer::CREATE_CONNECTION, data, &reply);
@@ -62,7 +63,6 @@
 
     virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc()
     {
-        uint32_t n;
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
         remote()->transact(BnSurfaceComposer::CREATE_GRAPHIC_BUFFER_ALLOC, data, &reply);
@@ -76,23 +76,18 @@
     {
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
-        {
-            Vector<ComposerState>::const_iterator b(state.begin());
-            Vector<ComposerState>::const_iterator e(state.end());
-            data.writeInt32(state.size());
-            for ( ; b != e ; ++b ) {
-                b->write(data);
-            }
+
+        data.writeUint32(static_cast<uint32_t>(state.size()));
+        for (const auto& s : state) {
+            s.write(data);
         }
-        {
-            Vector<DisplayState>::const_iterator b(displays.begin());
-            Vector<DisplayState>::const_iterator e(displays.end());
-            data.writeInt32(displays.size());
-            for ( ; b != e ; ++b ) {
-                b->write(data);
-            }
+
+        data.writeUint32(static_cast<uint32_t>(displays.size()));
+        for (const auto& d : displays) {
+            d.write(data);
         }
-        data.writeInt32(flags);
+
+        data.writeUint32(flags);
         remote()->transact(BnSurfaceComposer::SET_TRANSACTION_STATE, data, &reply);
     }
 
@@ -113,12 +108,12 @@
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
         data.writeStrongBinder(display);
-        data.writeStrongBinder(producer->asBinder());
+        data.writeStrongBinder(IInterface::asBinder(producer));
         data.write(sourceCrop);
-        data.writeInt32(reqWidth);
-        data.writeInt32(reqHeight);
-        data.writeInt32(minLayerZ);
-        data.writeInt32(maxLayerZ);
+        data.writeUint32(reqWidth);
+        data.writeUint32(reqHeight);
+        data.writeUint32(minLayerZ);
+        data.writeUint32(maxLayerZ);
         data.writeInt32(static_cast<int32_t>(useIdentityTransform));
         data.writeInt32(static_cast<int32_t>(rotation));
         remote()->transact(BnSurfaceComposer::CAPTURE_SCREEN, data, &reply);
@@ -137,7 +132,7 @@
                     "interface descriptor: %s (%d)", strerror(-err), -err);
             return false;
         }
-        err = data.writeStrongBinder(bufferProducer->asBinder());
+        err = data.writeStrongBinder(IInterface::asBinder(bufferProducer));
         if (err != NO_ERROR) {
             ALOGE("ISurfaceComposer::authenticateSurfaceTexture: error writing "
                     "strong binder to parcel: %s (%d)", strerror(-err), -err);
@@ -226,7 +221,7 @@
         remote()->transact(BnSurfaceComposer::GET_DISPLAY_CONFIGS, data, &reply);
         status_t result = reply.readInt32();
         if (result == NO_ERROR) {
-            size_t numConfigs = static_cast<size_t>(reply.readInt32());
+            size_t numConfigs = reply.readUint32();
             configs->clear();
             configs->resize(numConfigs);
             for (size_t c = 0; c < numConfigs; ++c) {
@@ -289,6 +284,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpSurfaceComposer::~BpSurfaceComposer() {}
+
 IMPLEMENT_META_INTERFACE(SurfaceComposer, "android.ui.ISurfaceComposer");
 
 // ----------------------------------------------------------------------
@@ -299,36 +298,49 @@
     switch(code) {
         case CREATE_CONNECTION: {
             CHECK_INTERFACE(ISurfaceComposer, data, reply);
-            sp<IBinder> b = createConnection()->asBinder();
+            sp<IBinder> b = IInterface::asBinder(createConnection());
             reply->writeStrongBinder(b);
             return NO_ERROR;
         }
         case CREATE_GRAPHIC_BUFFER_ALLOC: {
             CHECK_INTERFACE(ISurfaceComposer, data, reply);
-            sp<IBinder> b = createGraphicBufferAlloc()->asBinder();
+            sp<IBinder> b = IInterface::asBinder(createGraphicBufferAlloc());
             reply->writeStrongBinder(b);
             return NO_ERROR;
         }
         case SET_TRANSACTION_STATE: {
             CHECK_INTERFACE(ISurfaceComposer, data, reply);
-            size_t count = data.readInt32();
+
+            size_t count = data.readUint32();
+            if (count > data.dataSize()) {
+                return BAD_VALUE;
+            }
             ComposerState s;
             Vector<ComposerState> state;
             state.setCapacity(count);
-            for (size_t i=0 ; i<count ; i++) {
-                s.read(data);
+            for (size_t i = 0; i < count; i++) {
+                if (s.read(data) == BAD_VALUE) {
+                    return BAD_VALUE;
+                }
                 state.add(s);
             }
-            count = data.readInt32();
+
+            count = data.readUint32();
+            if (count > data.dataSize()) {
+                return BAD_VALUE;
+            }
             DisplayState d;
             Vector<DisplayState> displays;
             displays.setCapacity(count);
-            for (size_t i=0 ; i<count ; i++) {
-                d.read(data);
+            for (size_t i = 0; i < count; i++) {
+                if (d.read(data) == BAD_VALUE) {
+                    return BAD_VALUE;
+                }
                 displays.add(d);
             }
-            uint32_t flags = data.readInt32();
-            setTransactionState(state, displays, flags);
+
+            uint32_t stateFlags = data.readUint32();
+            setTransactionState(state, displays, stateFlags);
             return NO_ERROR;
         }
         case BOOT_FINISHED: {
@@ -343,12 +355,12 @@
                     interface_cast<IGraphicBufferProducer>(data.readStrongBinder());
             Rect sourceCrop;
             data.read(sourceCrop);
-            uint32_t reqWidth = data.readInt32();
-            uint32_t reqHeight = data.readInt32();
-            uint32_t minLayerZ = data.readInt32();
-            uint32_t maxLayerZ = data.readInt32();
+            uint32_t reqWidth = data.readUint32();
+            uint32_t reqHeight = data.readUint32();
+            uint32_t minLayerZ = data.readUint32();
+            uint32_t maxLayerZ = data.readUint32();
             bool useIdentityTransform = static_cast<bool>(data.readInt32());
-            uint32_t rotation = data.readInt32();
+            int32_t rotation = data.readInt32();
 
             status_t res = captureScreen(display, producer,
                     sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
@@ -368,7 +380,7 @@
         case CREATE_DISPLAY_EVENT_CONNECTION: {
             CHECK_INTERFACE(ISurfaceComposer, data, reply);
             sp<IDisplayEventConnection> connection(createDisplayEventConnection());
-            reply->writeStrongBinder(connection->asBinder());
+            reply->writeStrongBinder(IInterface::asBinder(connection));
             return NO_ERROR;
         }
         case CREATE_DISPLAY: {
@@ -399,7 +411,7 @@
             status_t result = getDisplayConfigs(display, &configs);
             reply->writeInt32(result);
             if (result == NO_ERROR) {
-                reply->writeInt32(static_cast<int32_t>(configs.size()));
+                reply->writeUint32(static_cast<uint32_t>(configs.size()));
                 for (size_t c = 0; c < configs.size(); ++c) {
                     memcpy(reply->writeInplace(sizeof(DisplayInfo)),
                             &configs[c], sizeof(DisplayInfo));
@@ -459,8 +471,6 @@
             return BBinder::onTransact(code, data, reply, flags);
         }
     }
-    // should be unreachable
-    return NO_ERROR;
 }
 
 // ----------------------------------------------------------------------------
diff --git a/libs/gui/ISurfaceComposerClient.cpp b/libs/gui/ISurfaceComposerClient.cpp
index f199e9f..2ecb908 100644
--- a/libs/gui/ISurfaceComposerClient.cpp
+++ b/libs/gui/ISurfaceComposerClient.cpp
@@ -51,17 +51,19 @@
         : BpInterface<ISurfaceComposerClient>(impl) {
     }
 
-    virtual status_t createSurface(const String8& name, uint32_t w,
-            uint32_t h, PixelFormat format, uint32_t flags,
+    virtual ~BpSurfaceComposerClient();
+
+    virtual status_t createSurface(const String8& name, uint32_t width,
+            uint32_t height, PixelFormat format, uint32_t flags,
             sp<IBinder>* handle,
             sp<IGraphicBufferProducer>* gbp) {
         Parcel data, reply;
         data.writeInterfaceToken(ISurfaceComposerClient::getInterfaceDescriptor());
         data.writeString8(name);
-        data.writeInt32(w);
-        data.writeInt32(h);
-        data.writeInt32(format);
-        data.writeInt32(flags);
+        data.writeUint32(width);
+        data.writeUint32(height);
+        data.writeInt32(static_cast<int32_t>(format));
+        data.writeUint32(flags);
         remote()->transact(CREATE_SURFACE, data, &reply);
         *handle = reply.readStrongBinder();
         *gbp = interface_cast<IGraphicBufferProducer>(reply.readStrongBinder());
@@ -94,6 +96,10 @@
     }
 };
 
+// Out-of-line virtual method definition to trigger vtable emission in this
+// translation unit (see clang warning -Wweak-vtables)
+BpSurfaceComposerClient::~BpSurfaceComposerClient() {}
+
 IMPLEMENT_META_INTERFACE(SurfaceComposerClient, "android.ui.ISurfaceComposerClient");
 
 // ----------------------------------------------------------------------
@@ -105,31 +111,31 @@
         case CREATE_SURFACE: {
             CHECK_INTERFACE(ISurfaceComposerClient, data, reply);
             String8 name = data.readString8();
-            uint32_t w = data.readInt32();
-            uint32_t h = data.readInt32();
-            PixelFormat format = data.readInt32();
-            uint32_t flags = data.readInt32();
+            uint32_t width = data.readUint32();
+            uint32_t height = data.readUint32();
+            PixelFormat format = static_cast<PixelFormat>(data.readInt32());
+            uint32_t createFlags = data.readUint32();
             sp<IBinder> handle;
             sp<IGraphicBufferProducer> gbp;
-            status_t result = createSurface(name, w, h, format, flags,
-                    &handle, &gbp);
+            status_t result = createSurface(name, width, height, format,
+                    createFlags, &handle, &gbp);
             reply->writeStrongBinder(handle);
-            reply->writeStrongBinder(gbp != NULL ? gbp->asBinder() : NULL);
+            reply->writeStrongBinder(IInterface::asBinder(gbp));
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case DESTROY_SURFACE: {
             CHECK_INTERFACE(ISurfaceComposerClient, data, reply);
             reply->writeInt32(destroySurface( data.readStrongBinder() ) );
             return NO_ERROR;
-        } break;
+        }
        case CLEAR_LAYER_FRAME_STATS: {
             CHECK_INTERFACE(ISurfaceComposerClient, data, reply);
             sp<IBinder> handle = data.readStrongBinder();
             status_t result = clearLayerFrameStats(handle);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         case GET_LAYER_FRAME_STATS: {
             CHECK_INTERFACE(ISurfaceComposerClient, data, reply);
             sp<IBinder> handle = data.readStrongBinder();
@@ -138,7 +144,7 @@
             reply->write(stats);
             reply->writeInt32(result);
             return NO_ERROR;
-        } break;
+        }
         default:
             return BBinder::onTransact(code, data, reply, flags);
     }
diff --git a/libs/gui/LayerState.cpp b/libs/gui/LayerState.cpp
index 9d3f116..00323dc 100644
--- a/libs/gui/LayerState.cpp
+++ b/libs/gui/LayerState.cpp
@@ -25,16 +25,16 @@
 status_t layer_state_t::write(Parcel& output) const
 {
     output.writeStrongBinder(surface);
-    output.writeInt32(what);
+    output.writeUint32(what);
     output.writeFloat(x);
     output.writeFloat(y);
-    output.writeInt32(z);
-    output.writeInt32(w);
-    output.writeInt32(h);
-    output.writeInt32(layerStack);
+    output.writeUint32(z);
+    output.writeUint32(w);
+    output.writeUint32(h);
+    output.writeUint32(layerStack);
     output.writeFloat(alpha);
-    output.writeInt32(flags);
-    output.writeInt32(mask);
+    output.writeUint32(flags);
+    output.writeUint32(mask);
     *reinterpret_cast<layer_state_t::matrix22_t *>(
             output.writeInplace(sizeof(layer_state_t::matrix22_t))) = matrix;
     output.write(crop);
@@ -45,25 +45,29 @@
 status_t layer_state_t::read(const Parcel& input)
 {
     surface = input.readStrongBinder();
-    what = input.readInt32();
+    what = input.readUint32();
     x = input.readFloat();
     y = input.readFloat();
-    z = input.readInt32();
-    w = input.readInt32();
-    h = input.readInt32();
-    layerStack = input.readInt32();
+    z = input.readUint32();
+    w = input.readUint32();
+    h = input.readUint32();
+    layerStack = input.readUint32();
     alpha = input.readFloat();
-    flags = input.readInt32();
-    mask = input.readInt32();
-    matrix = *reinterpret_cast<layer_state_t::matrix22_t const *>(
-            input.readInplace(sizeof(layer_state_t::matrix22_t)));
+    flags = static_cast<uint8_t>(input.readUint32());
+    mask = static_cast<uint8_t>(input.readUint32());
+    const void* matrix_data = input.readInplace(sizeof(layer_state_t::matrix22_t));
+    if (matrix_data) {
+        matrix = *reinterpret_cast<layer_state_t::matrix22_t const *>(matrix_data);
+    } else {
+        return BAD_VALUE;
+    }
     input.read(crop);
     input.read(transparentRegion);
     return NO_ERROR;
 }
 
 status_t ComposerState::write(Parcel& output) const {
-    output.writeStrongBinder(client->asBinder());
+    output.writeStrongBinder(IInterface::asBinder(client));
     return state.write(output);
 }
 
@@ -75,27 +79,27 @@
 
 status_t DisplayState::write(Parcel& output) const {
     output.writeStrongBinder(token);
-    output.writeStrongBinder(surface != NULL ? surface->asBinder() : NULL);
-    output.writeInt32(what);
-    output.writeInt32(layerStack);
-    output.writeInt32(orientation);
+    output.writeStrongBinder(IInterface::asBinder(surface));
+    output.writeUint32(what);
+    output.writeUint32(layerStack);
+    output.writeUint32(orientation);
     output.write(viewport);
     output.write(frame);
-    output.writeInt32(width);
-    output.writeInt32(height);
+    output.writeUint32(width);
+    output.writeUint32(height);
     return NO_ERROR;
 }
 
 status_t DisplayState::read(const Parcel& input) {
     token = input.readStrongBinder();
     surface = interface_cast<IGraphicBufferProducer>(input.readStrongBinder());
-    what = input.readInt32();
-    layerStack = input.readInt32();
-    orientation = input.readInt32();
+    what = input.readUint32();
+    layerStack = input.readUint32();
+    orientation = input.readUint32();
     input.read(viewport);
     input.read(frame);
-    width = input.readInt32();
-    height = input.readInt32();
+    width = input.readUint32();
+    height = input.readUint32();
     return NO_ERROR;
 }
 
diff --git a/libs/gui/Sensor.cpp b/libs/gui/Sensor.cpp
index b4291bb..8d38eef 100644
--- a/libs/gui/Sensor.cpp
+++ b/libs/gui/Sensor.cpp
@@ -72,7 +72,7 @@
                   static_cast<int64_t>(hwSensor->maxDelay));
             mMaxDelay = INT_MAX;
         } else {
-            mMaxDelay = (int32_t) hwSensor->maxDelay;
+            mMaxDelay = static_cast<int32_t>(hwSensor->maxDelay);
         }
     } else {
         // For older hals set maxDelay to 0.
@@ -214,7 +214,7 @@
         }
 
         if (halVersion >= SENSORS_DEVICE_API_VERSION_1_3) {
-            mFlags = (int32_t) hwSensor->flags;
+            mFlags = static_cast<uint32_t>(hwSensor->flags);
         } else {
             // This is an OEM defined sensor on an older HAL. Use minDelay to determine the
             // reporting mode of the sensor.
@@ -295,11 +295,11 @@
     return mVersion;
 }
 
-int32_t Sensor::getFifoReservedEventCount() const {
+uint32_t Sensor::getFifoReservedEventCount() const {
     return mFifoReservedEventCount;
 }
 
-int32_t Sensor::getFifoMaxEventCount() const {
+uint32_t Sensor::getFifoMaxEventCount() const {
     return mFifoMaxEventCount;
 }
 
@@ -315,7 +315,7 @@
     return mMaxDelay;
 }
 
-int32_t Sensor::getFlags() const {
+uint32_t Sensor::getFlags() const {
     return mFlags;
 }
 
@@ -407,7 +407,7 @@
 
 void Sensor::flattenString8(void*& buffer, size_t& size,
         const String8& string8) {
-    uint32_t len = string8.length();
+    uint32_t len = static_cast<uint32_t>(string8.length());
     FlattenableUtils::write(buffer, size, len);
     memcpy(static_cast<char*>(buffer), string8.string(), len);
     FlattenableUtils::advance(buffer, size, FlattenableUtils::align<4>(len));
diff --git a/libs/gui/SensorEventQueue.cpp b/libs/gui/SensorEventQueue.cpp
index 1305e9f..76ae470 100644
--- a/libs/gui/SensorEventQueue.cpp
+++ b/libs/gui/SensorEventQueue.cpp
@@ -16,6 +16,7 @@
 
 #define LOG_TAG "Sensors"
 
+#include <algorithm>
 #include <stdint.h>
 #include <sys/types.h>
 #include <sys/socket.h>
@@ -31,6 +32,8 @@
 
 #include <android/sensor.h>
 
+using std::min;
+
 // ----------------------------------------------------------------------------
 namespace android {
 // ----------------------------------------------------------------------------
@@ -68,14 +71,14 @@
         if (err < 0) {
             return err;
         }
-        mAvailable = err;
+        mAvailable = static_cast<size_t>(err);
         mConsumed = 0;
     }
-    size_t count = numEvents < mAvailable ? numEvents : mAvailable;
-    memcpy(events, mRecBuffer + mConsumed, count*sizeof(ASensorEvent));
+    size_t count = min(numEvents, mAvailable);
+    memcpy(events, mRecBuffer + mConsumed, count * sizeof(ASensorEvent));
     mAvailable -= count;
     mConsumed += count;
-    return count;
+    return static_cast<ssize_t>(count);
 }
 
 sp<Looper> SensorEventQueue::getLooper() const
@@ -157,7 +160,7 @@
         ssize_t size = ::send(mSensorChannel->getFd(), &mNumAcksToSend, sizeof(mNumAcksToSend),
                 MSG_DONTWAIT | MSG_NOSIGNAL);
         if (size < 0) {
-            ALOGE("sendAck failure %d %d", size, mNumAcksToSend);
+            ALOGE("sendAck failure %zd %d", size, mNumAcksToSend);
         } else {
             mNumAcksToSend = 0;
         }
diff --git a/libs/gui/SensorManager.cpp b/libs/gui/SensorManager.cpp
index 7b4fa2f..d6df404 100644
--- a/libs/gui/SensorManager.cpp
+++ b/libs/gui/SensorManager.cpp
@@ -86,11 +86,12 @@
         };
 
         mDeathObserver = new DeathObserver(*const_cast<SensorManager *>(this));
-        mSensorServer->asBinder()->linkToDeath(mDeathObserver);
+        IInterface::asBinder(mSensorServer)->linkToDeath(mDeathObserver);
 
         mSensors = mSensorServer->getSensorList();
         size_t count = mSensors.size();
-        mSensorList = (Sensor const**)malloc(count * sizeof(Sensor*));
+        mSensorList =
+                static_cast<Sensor const**>(malloc(count * sizeof(Sensor*)));
         for (size_t i=0 ; i<count ; i++) {
             mSensorList[i] = mSensors.array() + i;
         }
@@ -106,10 +107,10 @@
     Mutex::Autolock _l(mLock);
     status_t err = assertStateLocked();
     if (err < 0) {
-        return ssize_t(err);
+        return static_cast<ssize_t>(err);
     }
     *list = mSensorList;
-    return mSensors.size();
+    return static_cast<ssize_t>(mSensors.size());
 }
 
 Sensor const* SensorManager::getDefaultSensor(int type)
diff --git a/libs/gui/StreamSplitter.cpp b/libs/gui/StreamSplitter.cpp
index 771b263..4a1f9e0 100644
--- a/libs/gui/StreamSplitter.cpp
+++ b/libs/gui/StreamSplitter.cpp
@@ -80,7 +80,7 @@
 
     IGraphicBufferProducer::QueueBufferOutput queueBufferOutput;
     sp<OutputListener> listener(new OutputListener(this, outputQueue));
-    outputQueue->asBinder()->linkToDeath(listener);
+    IInterface::asBinder(outputQueue)->linkToDeath(listener);
     status_t status = outputQueue->connect(listener, NATIVE_WINDOW_API_CPU,
             /* producerControlledByApp */ false, &queueBufferOutput);
     if (status != NO_ERROR) {
@@ -141,7 +141,7 @@
 
     IGraphicBufferProducer::QueueBufferInput queueInput(
             bufferItem.mTimestamp, bufferItem.mIsAutoTimestamp,
-            bufferItem.mCrop, bufferItem.mScalingMode,
+            bufferItem.mCrop, static_cast<int32_t>(bufferItem.mScalingMode),
             bufferItem.mTransform, bufferItem.mIsDroppable,
             bufferItem.mFence);
 
diff --git a/libs/gui/Surface.cpp b/libs/gui/Surface.cpp
index 0e2baa2..aa4aee4 100644
--- a/libs/gui/Surface.cpp
+++ b/libs/gui/Surface.cpp
@@ -96,8 +96,8 @@
 void Surface::allocateBuffers() {
     uint32_t reqWidth = mReqWidth ? mReqWidth : mUserWidth;
     uint32_t reqHeight = mReqHeight ? mReqHeight : mUserHeight;
-    mGraphicBufferProducer->allocateBuffers(mSwapIntervalZero, mReqWidth,
-            mReqHeight, mReqFormat, mReqUsage);
+    mGraphicBufferProducer->allocateBuffers(mSwapIntervalZero, reqWidth,
+            reqHeight, mReqFormat, mReqUsage);
 }
 
 int Surface::hook_setSwapInterval(ANativeWindow* window, int interval) {
@@ -193,17 +193,17 @@
     ATRACE_CALL();
     ALOGV("Surface::dequeueBuffer");
 
-    int reqW;
-    int reqH;
+    uint32_t reqWidth;
+    uint32_t reqHeight;
     bool swapIntervalZero;
-    uint32_t reqFormat;
+    PixelFormat reqFormat;
     uint32_t reqUsage;
 
     {
         Mutex::Autolock lock(mMutex);
 
-        reqW = mReqWidth ? mReqWidth : mUserWidth;
-        reqH = mReqHeight ? mReqHeight : mUserHeight;
+        reqWidth = mReqWidth ? mReqWidth : mUserWidth;
+        reqHeight = mReqHeight ? mReqHeight : mUserHeight;
 
         swapIntervalZero = mSwapIntervalZero;
         reqFormat = mReqFormat;
@@ -213,12 +213,12 @@
     int buf = -1;
     sp<Fence> fence;
     status_t result = mGraphicBufferProducer->dequeueBuffer(&buf, &fence, swapIntervalZero,
-            reqW, reqH, reqFormat, reqUsage);
+            reqWidth, reqHeight, reqFormat, reqUsage);
 
     if (result < 0) {
         ALOGV("dequeueBuffer: IGraphicBufferProducer::dequeueBuffer(%d, %d, %d, %d, %d)"
-             "failed: %d", swapIntervalZero, reqW, reqH, reqFormat, reqUsage,
-             result);
+             "failed: %d", swapIntervalZero, reqWidth, reqHeight, reqFormat,
+             reqUsage, result);
         return result;
     }
 
@@ -274,7 +274,6 @@
 
 int Surface::getSlotFromBufferLocked(
         android_native_buffer_t* buffer) const {
-    bool dumpedState = false;
     for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
         if (mSlots[i].buffer != NULL &&
                 mSlots[i].buffer->handle == buffer->handle) {
@@ -347,7 +346,7 @@
         switch (what) {
             case NATIVE_WINDOW_FORMAT:
                 if (mReqFormat) {
-                    *value = mReqFormat;
+                    *value = static_cast<int>(mReqFormat);
                     return NO_ERROR;
                 }
                 break;
@@ -365,13 +364,15 @@
                 *value = NATIVE_WINDOW_SURFACE;
                 return NO_ERROR;
             case NATIVE_WINDOW_DEFAULT_WIDTH:
-                *value = mUserWidth ? mUserWidth : mDefaultWidth;
+                *value = static_cast<int>(
+                        mUserWidth ? mUserWidth : mDefaultWidth);
                 return NO_ERROR;
             case NATIVE_WINDOW_DEFAULT_HEIGHT:
-                *value = mUserHeight ? mUserHeight : mDefaultHeight;
+                *value = static_cast<int>(
+                        mUserHeight ? mUserHeight : mDefaultHeight);
                 return NO_ERROR;
             case NATIVE_WINDOW_TRANSFORM_HINT:
-                *value = mTransformHint;
+                *value = static_cast<int>(mTransformHint);
                 return NO_ERROR;
             case NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND: {
                 status_t err = NO_ERROR;
@@ -467,7 +468,7 @@
 
 int Surface::dispatchSetUsage(va_list args) {
     int usage = va_arg(args, int);
-    return setUsage(usage);
+    return setUsage(static_cast<uint32_t>(usage));
 }
 
 int Surface::dispatchSetCrop(va_list args) {
@@ -477,49 +478,49 @@
 
 int Surface::dispatchSetBufferCount(va_list args) {
     size_t bufferCount = va_arg(args, size_t);
-    return setBufferCount(bufferCount);
+    return setBufferCount(static_cast<int32_t>(bufferCount));
 }
 
 int Surface::dispatchSetBuffersGeometry(va_list args) {
-    int w = va_arg(args, int);
-    int h = va_arg(args, int);
-    int f = va_arg(args, int);
-    int err = setBuffersDimensions(w, h);
+    uint32_t width = va_arg(args, uint32_t);
+    uint32_t height = va_arg(args, uint32_t);
+    PixelFormat format = va_arg(args, PixelFormat);
+    int err = setBuffersDimensions(width, height);
     if (err != 0) {
         return err;
     }
-    return setBuffersFormat(f);
+    return setBuffersFormat(format);
 }
 
 int Surface::dispatchSetBuffersDimensions(va_list args) {
-    int w = va_arg(args, int);
-    int h = va_arg(args, int);
-    return setBuffersDimensions(w, h);
+    uint32_t width = va_arg(args, uint32_t);
+    uint32_t height = va_arg(args, uint32_t);
+    return setBuffersDimensions(width, height);
 }
 
 int Surface::dispatchSetBuffersUserDimensions(va_list args) {
-    int w = va_arg(args, int);
-    int h = va_arg(args, int);
-    return setBuffersUserDimensions(w, h);
+    uint32_t width = va_arg(args, uint32_t);
+    uint32_t height = va_arg(args, uint32_t);
+    return setBuffersUserDimensions(width, height);
 }
 
 int Surface::dispatchSetBuffersFormat(va_list args) {
-    int f = va_arg(args, int);
-    return setBuffersFormat(f);
+    PixelFormat format = va_arg(args, PixelFormat);
+    return setBuffersFormat(format);
 }
 
 int Surface::dispatchSetScalingMode(va_list args) {
-    int m = va_arg(args, int);
-    return setScalingMode(m);
+    int mode = va_arg(args, int);
+    return setScalingMode(mode);
 }
 
 int Surface::dispatchSetBuffersTransform(va_list args) {
-    int transform = va_arg(args, int);
+    uint32_t transform = va_arg(args, uint32_t);
     return setBuffersTransform(transform);
 }
 
 int Surface::dispatchSetBuffersStickyTransform(va_list args) {
-    int transform = va_arg(args, int);
+    uint32_t transform = va_arg(args, uint32_t);
     return setBuffersStickyTransform(transform);
 }
 
@@ -639,47 +640,38 @@
     return err;
 }
 
-int Surface::setBuffersDimensions(int w, int h)
+int Surface::setBuffersDimensions(uint32_t width, uint32_t height)
 {
     ATRACE_CALL();
     ALOGV("Surface::setBuffersDimensions");
 
-    if (w<0 || h<0)
-        return BAD_VALUE;
-
-    if ((w && !h) || (!w && h))
+    if ((width && !height) || (!width && height))
         return BAD_VALUE;
 
     Mutex::Autolock lock(mMutex);
-    mReqWidth = w;
-    mReqHeight = h;
+    mReqWidth = width;
+    mReqHeight = height;
     return NO_ERROR;
 }
 
-int Surface::setBuffersUserDimensions(int w, int h)
+int Surface::setBuffersUserDimensions(uint32_t width, uint32_t height)
 {
     ATRACE_CALL();
     ALOGV("Surface::setBuffersUserDimensions");
 
-    if (w<0 || h<0)
-        return BAD_VALUE;
-
-    if ((w && !h) || (!w && h))
+    if ((width && !height) || (!width && height))
         return BAD_VALUE;
 
     Mutex::Autolock lock(mMutex);
-    mUserWidth = w;
-    mUserHeight = h;
+    mUserWidth = width;
+    mUserHeight = height;
     return NO_ERROR;
 }
 
-int Surface::setBuffersFormat(int format)
+int Surface::setBuffersFormat(PixelFormat format)
 {
     ALOGV("Surface::setBuffersFormat");
 
-    if (format<0)
-        return BAD_VALUE;
-
     Mutex::Autolock lock(mMutex);
     mReqFormat = format;
     return NO_ERROR;
@@ -705,7 +697,7 @@
     return NO_ERROR;
 }
 
-int Surface::setBuffersTransform(int transform)
+int Surface::setBuffersTransform(uint32_t transform)
 {
     ATRACE_CALL();
     ALOGV("Surface::setBuffersTransform");
@@ -714,7 +706,7 @@
     return NO_ERROR;
 }
 
-int Surface::setBuffersStickyTransform(int transform)
+int Surface::setBuffersStickyTransform(uint32_t transform)
 {
     ATRACE_CALL();
     ALOGV("Surface::setBuffersStickyTransform");
@@ -748,30 +740,34 @@
     // src and dst with, height and format must be identical. no verification
     // is done here.
     status_t err;
-    uint8_t const * src_bits = NULL;
-    err = src->lock(GRALLOC_USAGE_SW_READ_OFTEN, reg.bounds(), (void**)&src_bits);
+    uint8_t* src_bits = NULL;
+    err = src->lock(GRALLOC_USAGE_SW_READ_OFTEN, reg.bounds(),
+            reinterpret_cast<void**>(&src_bits));
     ALOGE_IF(err, "error locking src buffer %s", strerror(-err));
 
     uint8_t* dst_bits = NULL;
-    err = dst->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, reg.bounds(), (void**)&dst_bits);
+    err = dst->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, reg.bounds(),
+            reinterpret_cast<void**>(&dst_bits));
     ALOGE_IF(err, "error locking dst buffer %s", strerror(-err));
 
     Region::const_iterator head(reg.begin());
     Region::const_iterator tail(reg.end());
     if (head != tail && src_bits && dst_bits) {
         const size_t bpp = bytesPerPixel(src->format);
-        const size_t dbpr = dst->stride * bpp;
-        const size_t sbpr = src->stride * bpp;
+        const size_t dbpr = static_cast<uint32_t>(dst->stride) * bpp;
+        const size_t sbpr = static_cast<uint32_t>(src->stride) * bpp;
 
         while (head != tail) {
             const Rect& r(*head++);
-            ssize_t h = r.height();
+            int32_t h = r.height();
             if (h <= 0) continue;
-            size_t size = r.width() * bpp;
-            uint8_t const * s = src_bits + (r.left + src->stride * r.top) * bpp;
-            uint8_t       * d = dst_bits + (r.left + dst->stride * r.top) * bpp;
+            size_t size = static_cast<uint32_t>(r.width()) * bpp;
+            uint8_t const * s = src_bits +
+                    static_cast<uint32_t>(r.left + src->stride * r.top) * bpp;
+            uint8_t       * d = dst_bits +
+                    static_cast<uint32_t>(r.left + dst->stride * r.top) * bpp;
             if (dbpr==sbpr && size==sbpr) {
-                size *= h;
+                size *= static_cast<size_t>(h);
                 h = 1;
             }
             do {
diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp
index 6446926..707a321 100644
--- a/libs/gui/SurfaceComposerClient.cpp
+++ b/libs/gui/SurfaceComposerClient.cpp
@@ -71,7 +71,7 @@
     };
 
     mDeathObserver = new DeathObserver(*const_cast<ComposerService*>(this));
-    mComposerService->asBinder()->linkToDeath(mDeathObserver);
+    IInterface::asBinder(mComposerService)->linkToDeath(mDeathObserver);
 }
 
 /*static*/ sp<ISurfaceComposer> ComposerService::getComposerService() {
@@ -143,7 +143,7 @@
     status_t setSize(const sp<SurfaceComposerClient>& client, const sp<IBinder>& id,
             uint32_t w, uint32_t h);
     status_t setLayer(const sp<SurfaceComposerClient>& client, const sp<IBinder>& id,
-            int32_t z);
+            uint32_t z);
     status_t setFlags(const sp<SurfaceComposerClient>& client, const sp<IBinder>& id,
             uint32_t flags, uint32_t mask);
     status_t setTransparentRegionHint(
@@ -293,7 +293,7 @@
 }
 
 status_t Composer::setLayer(const sp<SurfaceComposerClient>& client,
-        const sp<IBinder>& id, int32_t z) {
+        const sp<IBinder>& id, uint32_t z) {
     Mutex::Autolock _l(mLock);
     layer_state_t* s = getLayerStateLocked(client, id);
     if (!s)
@@ -395,7 +395,7 @@
         s.what = 0;
         index = mDisplayStates.add(s);
     }
-    return mDisplayStates.editItemAt(index);
+    return mDisplayStates.editItemAt(static_cast<size_t>(index));
 }
 
 void Composer::setDisplaySurface(const sp<IBinder>& token,
@@ -462,14 +462,14 @@
 }
 
 sp<IBinder> SurfaceComposerClient::connection() const {
-    return (mClient != 0) ? mClient->asBinder() : 0;
+    return IInterface::asBinder(mClient);
 }
 
 status_t SurfaceComposerClient::linkToComposerDeath(
         const sp<IBinder::DeathRecipient>& recipient,
         void* cookie, uint32_t flags) {
     sp<ISurfaceComposer> sm(ComposerService::getComposerService());
-    return sm->asBinder()->linkToDeath(recipient, cookie, flags);
+    return IInterface::asBinder(sm)->linkToDeath(recipient, cookie, flags);
 }
 
 void SurfaceComposerClient::dispose() {
@@ -571,7 +571,7 @@
     return getComposer().setSize(this, id, w, h);
 }
 
-status_t SurfaceComposerClient::setLayer(const sp<IBinder>& id, int32_t z) {
+status_t SurfaceComposerClient::setLayer(const sp<IBinder>& id, uint32_t z) {
     return getComposer().setLayer(this, id, z);
 }
 
@@ -657,7 +657,7 @@
         return NAME_NOT_FOUND;
     }
 
-    *info = configs[activeId];
+    *info = configs[static_cast<size_t>(activeId)];
     return NO_ERROR;
 }
 
@@ -752,14 +752,14 @@
 
 status_t ScreenshotClient::update(const sp<IBinder>& display, Rect sourceCrop,
         bool useIdentityTransform) {
-    return ScreenshotClient::update(display, sourceCrop, 0, 0, 0, -1UL,
+    return ScreenshotClient::update(display, sourceCrop, 0, 0, 0, -1U,
             useIdentityTransform, ISurfaceComposer::eRotateNone);
 }
 
 status_t ScreenshotClient::update(const sp<IBinder>& display, Rect sourceCrop,
         uint32_t reqWidth, uint32_t reqHeight, bool useIdentityTransform) {
     return ScreenshotClient::update(display, sourceCrop, reqWidth, reqHeight,
-            0, -1UL, useIdentityTransform, ISurfaceComposer::eRotateNone);
+            0, -1U, useIdentityTransform, ISurfaceComposer::eRotateNone);
 }
 
 void ScreenshotClient::release() {
diff --git a/libs/gui/SurfaceControl.cpp b/libs/gui/SurfaceControl.cpp
index 7597c99..1983027 100644
--- a/libs/gui/SurfaceControl.cpp
+++ b/libs/gui/SurfaceControl.cpp
@@ -89,12 +89,12 @@
     return lhs->mHandle == rhs->mHandle;
 }
 
-status_t SurfaceControl::setLayerStack(int32_t layerStack) {
+status_t SurfaceControl::setLayerStack(uint32_t layerStack) {
     status_t err = validate();
     if (err < 0) return err;
     return mClient->setLayerStack(mHandle, layerStack);
 }
-status_t SurfaceControl::setLayer(int32_t layer) {
+status_t SurfaceControl::setLayer(uint32_t layer) {
     status_t err = validate();
     if (err < 0) return err;
     return mClient->setLayer(mHandle, layer);
@@ -176,7 +176,7 @@
     if (control != NULL) {
         bp = control->mGraphicBufferProducer;
     }
-    return parcel->writeStrongBinder(bp->asBinder());
+    return parcel->writeStrongBinder(IInterface::asBinder(bp));
 }
 
 sp<Surface> SurfaceControl::getSurface() const
diff --git a/libs/gui/SyncFeatures.cpp b/libs/gui/SyncFeatures.cpp
index e5804a7..187b211 100644
--- a/libs/gui/SyncFeatures.cpp
+++ b/libs/gui/SyncFeatures.cpp
@@ -16,7 +16,6 @@
 
 #define LOG_TAG "GLConsumer"
 
-#define GL_GLEXT_PROTOTYPES
 #define EGL_EGLEXT_PROTOTYPES
 
 #include <EGL/egl.h>
@@ -78,10 +77,11 @@
     // on some devices it's better to not use EGL_KHR_fence_sync
     // even if they have it
     return false;
-#endif
+#else
     // currently we shall only attempt to use EGL_KHR_fence_sync if
     // USE_FENCE_SYNC is set in our makefile
     return !mHasNativeFenceSync && mHasFenceSync;
+#endif
 }
 bool SyncFeatures::useWaitSync() const {
     return (useNativeFenceSync() || useFenceSync()) && mHasWaitSync;
diff --git a/libs/gui/tests/BufferQueue_test.cpp b/libs/gui/tests/BufferQueue_test.cpp
index c781366..5cccc9b 100644
--- a/libs/gui/tests/BufferQueue_test.cpp
+++ b/libs/gui/tests/BufferQueue_test.cpp
@@ -87,8 +87,8 @@
         sp<IGraphicBufferConsumer> consumer;
         BufferQueue::createBufferQueue(&producer, &consumer);
         sp<IServiceManager> serviceManager = defaultServiceManager();
-        serviceManager->addService(PRODUCER_NAME, producer->asBinder());
-        serviceManager->addService(CONSUMER_NAME, consumer->asBinder());
+        serviceManager->addService(PRODUCER_NAME, IInterface::asBinder(producer));
+        serviceManager->addService(CONSUMER_NAME, IInterface::asBinder(consumer));
         ProcessState::self()->startThreadPool();
         IPCThreadState::self()->joinThreadPool();
         LOG_ALWAYS_FATAL("Shouldn't be here");
diff --git a/libs/ui/Android.mk b/libs/ui/Android.mk
index eec97be..1ce8626 100644
--- a/libs/ui/Android.mk
+++ b/libs/ui/Android.mk
@@ -12,10 +12,28 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-LOCAL_PATH:= $(call my-dir)
+LOCAL_PATH := $(call my-dir)
 include $(CLEAR_VARS)
 
-LOCAL_SRC_FILES:= \
+LOCAL_CLANG := true
+LOCAL_CPPFLAGS := -std=c++1y -Weverything -Werror
+
+# The static constructors and destructors in this library have not been noted to
+# introduce significant overheads
+LOCAL_CPPFLAGS += -Wno-exit-time-destructors
+LOCAL_CPPFLAGS += -Wno-global-constructors
+
+# We only care about compiling as C++14
+LOCAL_CPPFLAGS += -Wno-c++98-compat-pedantic
+
+# We use four-character constants for the GraphicBuffer header, and don't care
+# that they're non-portable as long as they're consistent within one execution
+LOCAL_CPPFLAGS += -Wno-four-char-constants
+
+# Don't warn about struct padding
+LOCAL_CPPFLAGS += -Wno-padded
+
+LOCAL_SRC_FILES := \
 	Fence.cpp \
 	FramebufferNativeWindow.cpp \
 	FrameStats.cpp \
@@ -38,7 +56,7 @@
 LOCAL_CFLAGS += -DFRAMEBUFFER_FORCE_FORMAT=$(BOARD_FRAMEBUFFER_FORCE_FORMAT)
 endif
 
-LOCAL_MODULE:= libui
+LOCAL_MODULE := libui
 
 include $(BUILD_SHARED_LIBRARY)
 
diff --git a/libs/ui/Fence.cpp b/libs/ui/Fence.cpp
index 3c0306c..9cf2881 100644
--- a/libs/ui/Fence.cpp
+++ b/libs/ui/Fence.cpp
@@ -18,10 +18,13 @@
 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
 //#define LOG_NDEBUG 0
 
- // This is needed for stdint.h to define INT64_MAX in C++
- #define __STDC_LIMIT_MACROS
-
+// We would eliminate the non-conforming zero-length array, but we can't since
+// this is effectively included from the Linux kernel
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wzero-length-array"
 #include <sync/sync.h>
+#pragma clang diagnostic pop
+
 #include <ui/Fence.h>
 #include <unistd.h>
 #include <utils/Log.h>
@@ -45,7 +48,7 @@
     }
 }
 
-status_t Fence::wait(unsigned int timeout) {
+status_t Fence::wait(int timeout) {
     ATRACE_CALL();
     if (mFenceFd == -1) {
         return NO_ERROR;
@@ -59,7 +62,7 @@
     if (mFenceFd == -1) {
         return NO_ERROR;
     }
-    unsigned int warningTimeout = 3000;
+    int warningTimeout = 3000;
     int err = sync_wait(mFenceFd, warningTimeout);
     if (err < 0 && errno == ETIME) {
         ALOGE("%s: fence %d didn't signal in %u ms", logname, mFenceFd,
@@ -138,7 +141,7 @@
     if (size < getFlattenedSize() || count < getFdCount()) {
         return NO_MEMORY;
     }
-    FlattenableUtils::write(buffer, size, (uint32_t)getFdCount());
+    FlattenableUtils::write(buffer, size, getFdCount());
     if (isValid()) {
         *fds++ = mFenceFd;
         count--;
diff --git a/libs/ui/FramebufferNativeWindow.cpp b/libs/ui/FramebufferNativeWindow.cpp
index 918f2e7..3ead25c 100644
--- a/libs/ui/FramebufferNativeWindow.cpp
+++ b/libs/ui/FramebufferNativeWindow.cpp
@@ -1,17 +1,17 @@
-/* 
+/*
 **
 ** Copyright 2007 The Android Open Source Project
 **
-** Licensed under the Apache License Version 2.0(the "License"); 
-** you may not use this file except in compliance with the License. 
-** You may obtain a copy of the License at 
+** 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 
+**     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 
+** 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.
 */
 
@@ -29,7 +29,9 @@
 
 #include <ui/ANativeObjectBase.h>
 #include <ui/Fence.h>
+#define INCLUDED_FROM_FRAMEBUFFER_NATIVE_WINDOW_CPP
 #include <ui/FramebufferNativeWindow.h>
+#undef INCLUDED_FROM_FRAMEBUFFER_NATIVE_WINDOW_CPP
 #include <ui/Rect.h>
 
 #include <EGL/egl.h>
@@ -41,11 +43,11 @@
 namespace android {
 // ----------------------------------------------------------------------------
 
-class NativeBuffer 
+class NativeBuffer final
     : public ANativeObjectBase<
-        ANativeWindowBuffer, 
-        NativeBuffer, 
-        LightRefBase<NativeBuffer> >
+        ANativeWindowBuffer,
+        NativeBuffer,
+        LightRefBase<NativeBuffer>>
 {
 public:
     NativeBuffer(int w, int h, int f, int u) : BASE() {
@@ -55,43 +57,41 @@
         ANativeWindowBuffer::usage  = u;
     }
 private:
-    friend class LightRefBase<NativeBuffer>;    
-    ~NativeBuffer() { }; // this class cannot be overloaded
+    friend class LightRefBase<NativeBuffer>;
 };
 
 
 /*
  * This implements the (main) framebuffer management. This class is used
  * mostly by SurfaceFlinger, but also by command line GL application.
- * 
+ *
  * In fact this is an implementation of ANativeWindow on top of
  * the framebuffer.
- * 
- * Currently it is pretty simple, it manages only two buffers (the front and 
+ *
+ * Currently it is pretty simple, it manages only two buffers (the front and
  * back buffer).
- * 
+ *
  */
 
-FramebufferNativeWindow::FramebufferNativeWindow() 
+FramebufferNativeWindow::FramebufferNativeWindow()
     : BASE(), fbDev(0), grDev(0), mUpdateOnDemand(false)
 {
     hw_module_t const* module;
     if (hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module) == 0) {
-        int stride;
         int err;
         int i;
         err = framebuffer_open(module, &fbDev);
         ALOGE_IF(err, "couldn't open framebuffer HAL (%s)", strerror(-err));
-        
+
         err = gralloc_open(module, &grDev);
         ALOGE_IF(err, "couldn't open gralloc HAL (%s)", strerror(-err));
 
         // bail out if we can't initialize the modules
         if (!fbDev || !grDev)
             return;
-        
+
         mUpdateOnDemand = (fbDev->setUpdateRect != 0);
-        
+
         // initialize the buffer FIFO
         if(fbDev->numFramebuffers >= MIN_NUM_FRAME_BUFFERS &&
            fbDev->numFramebuffers <= MAX_NUM_FRAME_BUFFERS){
@@ -114,36 +114,37 @@
         *((uint32_t *)&fbDev->format) = FRAMEBUFFER_FORCE_FORMAT;
 #endif
 
-        for (i = 0; i < mNumBuffers; i++)
-        {
-                buffers[i] = new NativeBuffer(
-                        fbDev->width, fbDev->height, fbDev->format, GRALLOC_USAGE_HW_FB);
+        for (i = 0; i < mNumBuffers; i++) {
+            buffers[i] = new NativeBuffer(
+                    static_cast<int>(fbDev->width),
+                    static_cast<int>(fbDev->height),
+                    fbDev->format, GRALLOC_USAGE_HW_FB);
         }
 
-        for (i = 0; i < mNumBuffers; i++)
-        {
-                err = grDev->alloc(grDev,
-                        fbDev->width, fbDev->height, fbDev->format,
-                        GRALLOC_USAGE_HW_FB, &buffers[i]->handle, &buffers[i]->stride);
+        for (i = 0; i < mNumBuffers; i++) {
+            err = grDev->alloc(grDev,
+                    static_cast<int>(fbDev->width),
+                    static_cast<int>(fbDev->height),
+                    fbDev->format, GRALLOC_USAGE_HW_FB,
+                    &buffers[i]->handle, &buffers[i]->stride);
 
-                ALOGE_IF(err, "fb buffer %d allocation failed w=%d, h=%d, err=%s",
-                        i, fbDev->width, fbDev->height, strerror(-err));
+            ALOGE_IF(err, "fb buffer %d allocation failed w=%d, h=%d, err=%s",
+                    i, fbDev->width, fbDev->height, strerror(-err));
 
-                if (err)
-                {
-                        mNumBuffers = i;
-                        mNumFreeBuffers = i;
-                        mBufferHead = mNumBuffers-1;
-                        break;
-                }
+            if (err) {
+                mNumBuffers = i;
+                mNumFreeBuffers = i;
+                mBufferHead = mNumBuffers-1;
+                break;
+            }
         }
 
-        const_cast<uint32_t&>(ANativeWindow::flags) = fbDev->flags; 
+        const_cast<uint32_t&>(ANativeWindow::flags) = fbDev->flags;
         const_cast<float&>(ANativeWindow::xdpi) = fbDev->xdpi;
         const_cast<float&>(ANativeWindow::ydpi) = fbDev->ydpi;
-        const_cast<int&>(ANativeWindow::minSwapInterval) = 
+        const_cast<int&>(ANativeWindow::minSwapInterval) =
             fbDev->minSwapInterval;
-        const_cast<int&>(ANativeWindow::maxSwapInterval) = 
+        const_cast<int&>(ANativeWindow::maxSwapInterval) =
             fbDev->maxSwapInterval;
     } else {
         ALOGE("Couldn't get gralloc module");
@@ -160,7 +161,7 @@
     ANativeWindow::queueBuffer_DEPRECATED = queueBuffer_DEPRECATED;
 }
 
-FramebufferNativeWindow::~FramebufferNativeWindow() 
+FramebufferNativeWindow::~FramebufferNativeWindow()
 {
     if (grDev) {
         for(int i = 0; i < mNumBuffers; i++) {
@@ -176,7 +177,7 @@
     }
 }
 
-status_t FramebufferNativeWindow::setUpdateRectangle(const Rect& r) 
+status_t FramebufferNativeWindow::setUpdateRectangle(const Rect& r)
 {
     if (!mUpdateOnDemand) {
         return INVALID_OPERATION;
@@ -193,7 +194,7 @@
 }
 
 int FramebufferNativeWindow::setSwapInterval(
-        ANativeWindow* window, int interval) 
+        ANativeWindow* window, int interval)
 {
     framebuffer_device_t* fb = getSelf(window)->fbDev;
     return fb->setSwapInterval(fb, interval);
@@ -217,7 +218,7 @@
     return index;
 }
 
-int FramebufferNativeWindow::dequeueBuffer_DEPRECATED(ANativeWindow* window, 
+int FramebufferNativeWindow::dequeueBuffer_DEPRECATED(ANativeWindow* window,
         ANativeWindowBuffer** buffer)
 {
     int fenceFd = -1;
@@ -232,12 +233,11 @@
     return result;
 }
 
-int FramebufferNativeWindow::dequeueBuffer(ANativeWindow* window, 
+int FramebufferNativeWindow::dequeueBuffer(ANativeWindow* window,
         ANativeWindowBuffer** buffer, int* fenceFd)
 {
     FramebufferNativeWindow* self = getSelf(window);
     Mutex::Autolock _l(self->mutex);
-    framebuffer_device_t* fb = self->fbDev;
 
     int index = self->mBufferHead++;
     if (self->mBufferHead >= self->mNumBuffers)
@@ -247,7 +247,7 @@
     while (self->mNumFreeBuffers < 2) {
         self->mCondition.wait(self->mutex);
     }
-    ALOG_ASSERT(self->buffers[index] != self->front);
+    ALOG_ASSERT(self->buffers[index] != self->front, "");
 
     // get this buffer
     self->mNumFreeBuffers--;
@@ -259,19 +259,19 @@
     return 0;
 }
 
-int FramebufferNativeWindow::lockBuffer_DEPRECATED(ANativeWindow* /*window*/, 
+int FramebufferNativeWindow::lockBuffer_DEPRECATED(ANativeWindow* /*window*/,
         ANativeWindowBuffer* /*buffer*/)
 {
     return NO_ERROR;
 }
 
-int FramebufferNativeWindow::queueBuffer_DEPRECATED(ANativeWindow* window, 
+int FramebufferNativeWindow::queueBuffer_DEPRECATED(ANativeWindow* window,
         ANativeWindowBuffer* buffer)
 {
     return queueBuffer(window, buffer, -1);
 }
 
-int FramebufferNativeWindow::queueBuffer(ANativeWindow* window, 
+int FramebufferNativeWindow::queueBuffer(ANativeWindow* window,
         ANativeWindowBuffer* buffer, int fenceFd)
 {
     FramebufferNativeWindow* self = getSelf(window);
@@ -282,7 +282,6 @@
     sp<Fence> fence(new Fence(fenceFd));
     fence->wait(Fence::TIMEOUT_NEVER);
 
-    const int index = self->mCurrentBufferIndex;
     int res = fb->post(fb, handle);
     self->front = static_cast<NativeBuffer*>(buffer);
     self->mNumFreeBuffers++;
@@ -291,17 +290,17 @@
 }
 
 int FramebufferNativeWindow::query(const ANativeWindow* window,
-        int what, int* value) 
+        int what, int* value)
 {
     const FramebufferNativeWindow* self = getSelf(window);
     Mutex::Autolock _l(self->mutex);
     framebuffer_device_t* fb = self->fbDev;
     switch (what) {
         case NATIVE_WINDOW_WIDTH:
-            *value = fb->width;
+            *value = static_cast<int>(fb->width);
             return NO_ERROR;
         case NATIVE_WINDOW_HEIGHT:
-            *value = fb->height;
+            *value = static_cast<int>(fb->height);
             return NO_ERROR;
         case NATIVE_WINDOW_FORMAT:
             *value = fb->format;
@@ -313,10 +312,10 @@
             *value = 0;
             return NO_ERROR;
         case NATIVE_WINDOW_DEFAULT_WIDTH:
-            *value = fb->width;
+            *value = static_cast<int>(fb->width);
             return NO_ERROR;
         case NATIVE_WINDOW_DEFAULT_HEIGHT:
-            *value = fb->height;
+            *value = static_cast<int>(fb->height);
             return NO_ERROR;
         case NATIVE_WINDOW_TRANSFORM_HINT:
             *value = 0;
@@ -357,7 +356,8 @@
 }; // namespace android
 // ----------------------------------------------------------------------------
 
-using namespace android;
+using android::sp;
+using android::FramebufferNativeWindow;
 
 EGLNativeWindowType android_createDisplaySurface(void)
 {
@@ -368,5 +368,5 @@
         sp<FramebufferNativeWindow> ref(w);
         return NULL;
     }
-    return (EGLNativeWindowType)w;
+    return static_cast<EGLNativeWindowType>(w);
 }
diff --git a/libs/ui/GraphicBuffer.cpp b/libs/ui/GraphicBuffer.cpp
index 9b0bd60..425df38 100644
--- a/libs/ui/GraphicBuffer.cpp
+++ b/libs/ui/GraphicBuffer.cpp
@@ -45,40 +45,40 @@
     : BASE(), mOwner(ownData), mBufferMapper(GraphicBufferMapper::get()),
       mInitCheck(NO_ERROR), mId(getUniqueId())
 {
-    width  = 
-    height = 
-    stride = 
-    format = 
+    width  =
+    height =
+    stride =
+    format =
     usage  = 0;
     handle = NULL;
 }
 
-GraphicBuffer::GraphicBuffer(uint32_t w, uint32_t h, 
-        PixelFormat reqFormat, uint32_t reqUsage)
+GraphicBuffer::GraphicBuffer(uint32_t inWidth, uint32_t inHeight,
+        PixelFormat inFormat, uint32_t inUsage)
     : BASE(), mOwner(ownData), mBufferMapper(GraphicBufferMapper::get()),
       mInitCheck(NO_ERROR), mId(getUniqueId())
 {
-    width  = 
-    height = 
-    stride = 
-    format = 
+    width  =
+    height =
+    stride =
+    format =
     usage  = 0;
     handle = NULL;
-    mInitCheck = initSize(w, h, reqFormat, reqUsage);
+    mInitCheck = initSize(inWidth, inHeight, inFormat, inUsage);
 }
 
-GraphicBuffer::GraphicBuffer(uint32_t w, uint32_t h,
-        PixelFormat inFormat, uint32_t inUsage,
-        uint32_t inStride, native_handle_t* inHandle, bool keepOwnership)
+GraphicBuffer::GraphicBuffer(uint32_t inWidth, uint32_t inHeight,
+        PixelFormat inFormat, uint32_t inUsage, uint32_t inStride,
+        native_handle_t* inHandle, bool keepOwnership)
     : BASE(), mOwner(keepOwnership ? ownHandle : ownNone),
       mBufferMapper(GraphicBufferMapper::get()),
       mInitCheck(NO_ERROR), mId(getUniqueId())
 {
-    width  = w;
-    height = h;
-    stride = inStride;
+    width  = static_cast<int>(inWidth);
+    height = static_cast<int>(inHeight);
+    stride = static_cast<int>(inStride);
     format = inFormat;
-    usage  = inUsage;
+    usage  = static_cast<int>(inUsage);
     handle = inHandle;
 }
 
@@ -116,7 +116,7 @@
 }
 
 status_t GraphicBuffer::initCheck() const {
-    return mInitCheck;
+    return static_cast<status_t>(mInitCheck);
 }
 
 void GraphicBuffer::dumpAllocationsToSystemLog()
@@ -131,13 +131,17 @@
             const_cast<GraphicBuffer*>(this));
 }
 
-status_t GraphicBuffer::reallocate(uint32_t w, uint32_t h, PixelFormat f,
-        uint32_t reqUsage)
+status_t GraphicBuffer::reallocate(uint32_t inWidth, uint32_t inHeight,
+        PixelFormat inFormat, uint32_t inUsage)
 {
     if (mOwner != ownData)
         return INVALID_OPERATION;
 
-    if (handle && w==width && h==height && f==format && reqUsage==usage)
+    if (handle &&
+            static_cast<int>(inWidth) == width &&
+            static_cast<int>(inHeight) == height &&
+            inFormat == format &&
+            static_cast<int>(inUsage) == usage)
         return NO_ERROR;
 
     if (handle) {
@@ -145,61 +149,64 @@
         allocator.free(handle);
         handle = 0;
     }
-    return initSize(w, h, f, reqUsage);
+    return initSize(inWidth, inHeight, inFormat, inUsage);
 }
 
-status_t GraphicBuffer::initSize(uint32_t w, uint32_t h, PixelFormat format,
-        uint32_t reqUsage)
+status_t GraphicBuffer::initSize(uint32_t inWidth, uint32_t inHeight,
+        PixelFormat inFormat, uint32_t inUsage)
 {
     GraphicBufferAllocator& allocator = GraphicBufferAllocator::get();
-    status_t err = allocator.alloc(w, h, format, reqUsage, &handle, &stride);
+    uint32_t outStride = 0;
+    status_t err = allocator.alloc(inWidth, inHeight, inFormat, inUsage,
+            &handle, &outStride);
     if (err == NO_ERROR) {
-        this->width  = w;
-        this->height = h;
-        this->format = format;
-        this->usage  = reqUsage;
+        width = static_cast<int>(inWidth);
+        height = static_cast<int>(inHeight);
+        format = inFormat;
+        usage = static_cast<int>(inUsage);
+        stride = static_cast<int>(outStride);
     }
     return err;
 }
 
-status_t GraphicBuffer::lock(uint32_t usage, void** vaddr)
+status_t GraphicBuffer::lock(uint32_t inUsage, void** vaddr)
 {
     const Rect lockBounds(width, height);
-    status_t res = lock(usage, lockBounds, vaddr);
+    status_t res = lock(inUsage, lockBounds, vaddr);
     return res;
 }
 
-status_t GraphicBuffer::lock(uint32_t usage, const Rect& rect, void** vaddr)
+status_t GraphicBuffer::lock(uint32_t inUsage, const Rect& rect, void** vaddr)
 {
-    if (rect.left < 0 || rect.right  > this->width || 
-        rect.top  < 0 || rect.bottom > this->height) {
-        ALOGE("locking pixels (%d,%d,%d,%d) outside of buffer (w=%d, h=%d)",
-                rect.left, rect.top, rect.right, rect.bottom, 
-                this->width, this->height);
-        return BAD_VALUE;
-    }
-    status_t res = getBufferMapper().lock(handle, usage, rect, vaddr);
-    return res;
-}
-
-status_t GraphicBuffer::lockYCbCr(uint32_t usage, android_ycbcr *ycbcr)
-{
-    const Rect lockBounds(width, height);
-    status_t res = lockYCbCr(usage, lockBounds, ycbcr);
-    return res;
-}
-
-status_t GraphicBuffer::lockYCbCr(uint32_t usage, const Rect& rect,
-        android_ycbcr *ycbcr)
-{
-    if (rect.left < 0 || rect.right  > this->width ||
-        rect.top  < 0 || rect.bottom > this->height) {
+    if (rect.left < 0 || rect.right  > width ||
+        rect.top  < 0 || rect.bottom > height) {
         ALOGE("locking pixels (%d,%d,%d,%d) outside of buffer (w=%d, h=%d)",
                 rect.left, rect.top, rect.right, rect.bottom,
-                this->width, this->height);
+                width, height);
         return BAD_VALUE;
     }
-    status_t res = getBufferMapper().lockYCbCr(handle, usage, rect, ycbcr);
+    status_t res = getBufferMapper().lock(handle, inUsage, rect, vaddr);
+    return res;
+}
+
+status_t GraphicBuffer::lockYCbCr(uint32_t inUsage, android_ycbcr* ycbcr)
+{
+    const Rect lockBounds(width, height);
+    status_t res = lockYCbCr(inUsage, lockBounds, ycbcr);
+    return res;
+}
+
+status_t GraphicBuffer::lockYCbCr(uint32_t inUsage, const Rect& rect,
+        android_ycbcr* ycbcr)
+{
+    if (rect.left < 0 || rect.right  > width ||
+        rect.top  < 0 || rect.bottom > height) {
+        ALOGE("locking pixels (%d,%d,%d,%d) outside of buffer (w=%d, h=%d)",
+                rect.left, rect.top, rect.right, rect.bottom,
+                width, height);
+        return BAD_VALUE;
+    }
+    status_t res = getBufferMapper().lockYCbCr(handle, inUsage, rect, ycbcr);
     return res;
 }
 
@@ -209,43 +216,48 @@
     return res;
 }
 
-status_t GraphicBuffer::lockAsync(uint32_t usage, void** vaddr, int fenceFd)
+status_t GraphicBuffer::lockAsync(uint32_t inUsage, void** vaddr, int fenceFd)
 {
     const Rect lockBounds(width, height);
-    status_t res = lockAsync(usage, lockBounds, vaddr, fenceFd);
+    status_t res = lockAsync(inUsage, lockBounds, vaddr, fenceFd);
     return res;
 }
 
-status_t GraphicBuffer::lockAsync(uint32_t usage, const Rect& rect, void** vaddr, int fenceFd)
+status_t GraphicBuffer::lockAsync(uint32_t inUsage, const Rect& rect,
+        void** vaddr, int fenceFd)
 {
-    if (rect.left < 0 || rect.right  > this->width ||
-        rect.top  < 0 || rect.bottom > this->height) {
+    if (rect.left < 0 || rect.right  > width ||
+        rect.top  < 0 || rect.bottom > height) {
         ALOGE("locking pixels (%d,%d,%d,%d) outside of buffer (w=%d, h=%d)",
                 rect.left, rect.top, rect.right, rect.bottom,
-                this->width, this->height);
+                width, height);
         return BAD_VALUE;
     }
-    status_t res = getBufferMapper().lockAsync(handle, usage, rect, vaddr, fenceFd);
+    status_t res = getBufferMapper().lockAsync(handle, inUsage, rect, vaddr,
+            fenceFd);
     return res;
 }
 
-status_t GraphicBuffer::lockAsyncYCbCr(uint32_t usage, android_ycbcr *ycbcr, int fenceFd)
+status_t GraphicBuffer::lockAsyncYCbCr(uint32_t inUsage, android_ycbcr* ycbcr,
+        int fenceFd)
 {
     const Rect lockBounds(width, height);
-    status_t res = lockAsyncYCbCr(usage, lockBounds, ycbcr, fenceFd);
+    status_t res = lockAsyncYCbCr(inUsage, lockBounds, ycbcr, fenceFd);
     return res;
 }
 
-status_t GraphicBuffer::lockAsyncYCbCr(uint32_t usage, const Rect& rect, android_ycbcr *ycbcr, int fenceFd)
+status_t GraphicBuffer::lockAsyncYCbCr(uint32_t inUsage, const Rect& rect,
+        android_ycbcr* ycbcr, int fenceFd)
 {
-    if (rect.left < 0 || rect.right  > this->width ||
-        rect.top  < 0 || rect.bottom > this->height) {
+    if (rect.left < 0 || rect.right  > width ||
+        rect.top  < 0 || rect.bottom > height) {
         ALOGE("locking pixels (%d,%d,%d,%d) outside of buffer (w=%d, h=%d)",
                 rect.left, rect.top, rect.right, rect.bottom,
-                this->width, this->height);
+                width, height);
         return BAD_VALUE;
     }
-    status_t res = getBufferMapper().lockAsyncYCbCr(handle, usage, rect, ycbcr, fenceFd);
+    status_t res = getBufferMapper().lockAsyncYCbCr(handle, inUsage, rect,
+            ycbcr, fenceFd);
     return res;
 }
 
@@ -256,11 +268,11 @@
 }
 
 size_t GraphicBuffer::getFlattenedSize() const {
-    return (10 + (handle ? handle->numInts : 0))*sizeof(int);
+    return static_cast<size_t>(10 + (handle ? handle->numInts : 0)) * sizeof(int);
 }
 
 size_t GraphicBuffer::getFdCount() const {
-    return handle ? handle->numFds : 0;
+    return static_cast<size_t>(handle ? handle->numFds : 0);
 }
 
 status_t GraphicBuffer::flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const {
@@ -285,16 +297,17 @@
     if (handle) {
         buf[8] = handle->numFds;
         buf[9] = handle->numInts;
-        native_handle_t const* const h = handle;
-        memcpy(fds,     h->data,             h->numFds*sizeof(int));
-        memcpy(&buf[10], h->data + h->numFds, h->numInts*sizeof(int));
+        memcpy(fds, handle->data,
+                static_cast<size_t>(handle->numFds) * sizeof(int));
+        memcpy(&buf[10], handle->data + handle->numFds,
+                static_cast<size_t>(handle->numInts) * sizeof(int));
     }
 
     buffer = reinterpret_cast<void*>(static_cast<int*>(buffer) + sizeNeeded);
     size -= sizeNeeded;
     if (handle) {
         fds += handle->numFds;
-        count -= handle->numFds;
+        count -= static_cast<size_t>(handle->numFds);
     }
 
     return NO_ERROR;
@@ -307,13 +320,22 @@
     int const* buf = static_cast<int const*>(buffer);
     if (buf[0] != 'GBFR') return BAD_TYPE;
 
-    const size_t numFds  = buf[8];
-    const size_t numInts = buf[9];
+    const size_t numFds  = static_cast<size_t>(buf[8]);
+    const size_t numInts = static_cast<size_t>(buf[9]);
+
+    const size_t maxNumber = UINT_MAX / sizeof(int);
+    if (numFds >= maxNumber || numInts >= (maxNumber - 10)) {
+        width = height = stride = format = usage = 0;
+        handle = NULL;
+        ALOGE("unflatten: numFds or numInts is too large: %zd, %zd",
+                numFds, numInts);
+        return BAD_VALUE;
+    }
 
     const size_t sizeNeeded = (10 + numInts) * sizeof(int);
     if (size < sizeNeeded) return NO_MEMORY;
 
-    size_t fdCountNeeded = 0;
+    size_t fdCountNeeded = numFds;
     if (count < fdCountNeeded) return NO_MEMORY;
 
     if (handle) {
@@ -327,9 +349,16 @@
         stride = buf[3];
         format = buf[4];
         usage  = buf[5];
-        native_handle* h = native_handle_create(numFds, numInts);
-        memcpy(h->data,          fds,     numFds*sizeof(int));
-        memcpy(h->data + numFds, &buf[10], numInts*sizeof(int));
+        native_handle* h = native_handle_create(
+                static_cast<int>(numFds), static_cast<int>(numInts));
+        if (!h) {
+            width = height = stride = format = usage = 0;
+            handle = NULL;
+            ALOGE("unflatten: native_handle_create failed");
+            return NO_MEMORY;
+        }
+        memcpy(h->data, fds, numFds * sizeof(int));
+        memcpy(h->data + numFds, &buf[10], numInts * sizeof(int));
         handle = h;
     } else {
         width = height = stride = format = usage = 0;
diff --git a/libs/ui/GraphicBufferAllocator.cpp b/libs/ui/GraphicBufferAllocator.cpp
index ff550d9..85e9675 100644
--- a/libs/ui/GraphicBufferAllocator.cpp
+++ b/libs/ui/GraphicBufferAllocator.cpp
@@ -1,17 +1,17 @@
-/* 
+/*
 **
 ** Copyright 2009, The Android Open Source Project
 **
-** Licensed under the Apache License, Version 2.0 (the "License"); 
-** you may not use this file except in compliance with the License. 
-** You may obtain a copy of the License at 
+** 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 
+**     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 
+** 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.
 */
 
@@ -66,11 +66,11 @@
         if (rec.size) {
             snprintf(buffer, SIZE, "%10p: %7.2f KiB | %4u (%4u) x %4u | %8X | 0x%08x\n",
                     list.keyAt(i), rec.size/1024.0f,
-                    rec.w, rec.s, rec.h, rec.format, rec.usage);
+                    rec.width, rec.stride, rec.height, rec.format, rec.usage);
         } else {
             snprintf(buffer, SIZE, "%10p: unknown     | %4u (%4u) x %4u | %8X | 0x%08x\n",
                     list.keyAt(i),
-                    rec.w, rec.s, rec.h, rec.format, rec.usage);
+                    rec.width, rec.stride, rec.height, rec.format, rec.usage);
         }
         result.append(buffer);
         total += rec.size;
@@ -90,39 +90,40 @@
     ALOGD("%s", s.string());
 }
 
-status_t GraphicBufferAllocator::alloc(uint32_t w, uint32_t h, PixelFormat format,
-        int usage, buffer_handle_t* handle, int32_t* stride)
+status_t GraphicBufferAllocator::alloc(uint32_t width, uint32_t height,
+        PixelFormat format, uint32_t usage, buffer_handle_t* handle,
+        uint32_t* stride)
 {
     ATRACE_CALL();
+
     // make sure to not allocate a N x 0 or 0 x N buffer, since this is
     // allowed from an API stand-point allocate a 1x1 buffer instead.
-    if (!w || !h)
-        w = h = 1;
+    if (!width || !height)
+        width = height = 1;
 
     // we have a h/w allocator and h/w buffer is requested
-    status_t err; 
-    
-    err = mAllocDev->alloc(mAllocDev, w, h, format, usage, handle, stride);
+    status_t err;
+
+    int outStride = 0;
+    err = mAllocDev->alloc(mAllocDev, static_cast<int>(width),
+            static_cast<int>(height), format, static_cast<int>(usage), handle,
+            &outStride);
+    *stride = static_cast<uint32_t>(outStride);
 
     ALOGW_IF(err, "alloc(%u, %u, %d, %08x, ...) failed %d (%s)",
-            w, h, format, usage, err, strerror(-err));
-    
+            width, height, format, usage, err, strerror(-err));
+
     if (err == NO_ERROR) {
         Mutex::Autolock _l(sLock);
         KeyedVector<buffer_handle_t, alloc_rec_t>& list(sAllocList);
-        int bpp = bytesPerPixel(format);
-        if (bpp < 0) {
-            // probably a HAL custom format. in any case, we don't know
-            // what its pixel size is.
-            bpp = 0;
-        }
+        uint32_t bpp = bytesPerPixel(format);
         alloc_rec_t rec;
-        rec.w = w;
-        rec.h = h;
-        rec.s = *stride;
+        rec.width = width;
+        rec.height = height;
+        rec.stride = *stride;
         rec.format = format;
         rec.usage = usage;
-        rec.size = h * stride[0] * bpp;
+        rec.size = static_cast<size_t>(height * (*stride) * bpp);
         list.add(*handle, rec);
     }
 
diff --git a/libs/ui/GraphicBufferMapper.cpp b/libs/ui/GraphicBufferMapper.cpp
index 320b6c0..01acdc8 100644
--- a/libs/ui/GraphicBufferMapper.cpp
+++ b/libs/ui/GraphicBufferMapper.cpp
@@ -20,7 +20,12 @@
 #include <stdint.h>
 #include <errno.h>
 
+// We would eliminate the non-conforming zero-length array, but we can't since
+// this is effectively included from the Linux kernel
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wzero-length-array"
 #include <sync/sync.h>
+#pragma clang diagnostic pop
 
 #include <utils/Errors.h>
 #include <utils/Log.h>
@@ -44,7 +49,7 @@
     int err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module);
     ALOGE_IF(err, "FATAL: can't find the %s module", GRALLOC_HARDWARE_MODULE_ID);
     if (err == 0) {
-        mAllocMod = (gralloc_module_t const *)module;
+        mAllocMod = reinterpret_cast<gralloc_module_t const *>(module);
     }
 }
 
@@ -72,13 +77,13 @@
     return err;
 }
 
-status_t GraphicBufferMapper::lock(buffer_handle_t handle, 
-        int usage, const Rect& bounds, void** vaddr)
+status_t GraphicBufferMapper::lock(buffer_handle_t handle,
+        uint32_t usage, const Rect& bounds, void** vaddr)
 {
     ATRACE_CALL();
     status_t err;
 
-    err = mAllocMod->lock(mAllocMod, handle, usage,
+    err = mAllocMod->lock(mAllocMod, handle, static_cast<int>(usage),
             bounds.left, bounds.top, bounds.width(), bounds.height(),
             vaddr);
 
@@ -87,12 +92,12 @@
 }
 
 status_t GraphicBufferMapper::lockYCbCr(buffer_handle_t handle,
-        int usage, const Rect& bounds, android_ycbcr *ycbcr)
+        uint32_t usage, const Rect& bounds, android_ycbcr *ycbcr)
 {
     ATRACE_CALL();
     status_t err;
 
-    err = mAllocMod->lock_ycbcr(mAllocMod, handle, usage,
+    err = mAllocMod->lock_ycbcr(mAllocMod, handle, static_cast<int>(usage),
             bounds.left, bounds.top, bounds.width(), bounds.height(),
             ycbcr);
 
@@ -112,19 +117,19 @@
 }
 
 status_t GraphicBufferMapper::lockAsync(buffer_handle_t handle,
-        int usage, const Rect& bounds, void** vaddr, int fenceFd)
+        uint32_t usage, const Rect& bounds, void** vaddr, int fenceFd)
 {
     ATRACE_CALL();
     status_t err;
 
     if (mAllocMod->common.module_api_version >= GRALLOC_MODULE_API_VERSION_0_3) {
-        err = mAllocMod->lockAsync(mAllocMod, handle, usage,
+        err = mAllocMod->lockAsync(mAllocMod, handle, static_cast<int>(usage),
                 bounds.left, bounds.top, bounds.width(), bounds.height(),
                 vaddr, fenceFd);
     } else {
         sync_wait(fenceFd, -1);
         close(fenceFd);
-        err = mAllocMod->lock(mAllocMod, handle, usage,
+        err = mAllocMod->lock(mAllocMod, handle, static_cast<int>(usage),
                 bounds.left, bounds.top, bounds.width(), bounds.height(),
                 vaddr);
     }
@@ -134,19 +139,19 @@
 }
 
 status_t GraphicBufferMapper::lockAsyncYCbCr(buffer_handle_t handle,
-        int usage, const Rect& bounds, android_ycbcr *ycbcr, int fenceFd)
+        uint32_t usage, const Rect& bounds, android_ycbcr *ycbcr, int fenceFd)
 {
     ATRACE_CALL();
     status_t err;
 
     if (mAllocMod->common.module_api_version >= GRALLOC_MODULE_API_VERSION_0_3) {
-        err = mAllocMod->lockAsync_ycbcr(mAllocMod, handle, usage,
-                bounds.left, bounds.top, bounds.width(), bounds.height(),
-                ycbcr, fenceFd);
+        err = mAllocMod->lockAsync_ycbcr(mAllocMod, handle,
+                static_cast<int>(usage), bounds.left, bounds.top,
+                bounds.width(), bounds.height(), ycbcr, fenceFd);
     } else {
         sync_wait(fenceFd, -1);
         close(fenceFd);
-        err = mAllocMod->lock_ycbcr(mAllocMod, handle, usage,
+        err = mAllocMod->lock_ycbcr(mAllocMod, handle, static_cast<int>(usage),
                 bounds.left, bounds.top, bounds.width(), bounds.height(),
                 ycbcr);
     }
diff --git a/libs/ui/PixelFormat.cpp b/libs/ui/PixelFormat.cpp
index 5ce7fba..99ed6f7 100644
--- a/libs/ui/PixelFormat.cpp
+++ b/libs/ui/PixelFormat.cpp
@@ -15,13 +15,12 @@
  */
 
 #include <ui/PixelFormat.h>
-#include <hardware/hardware.h>
 
 // ----------------------------------------------------------------------------
 namespace android {
 // ----------------------------------------------------------------------------
 
-ssize_t bytesPerPixel(PixelFormat format) {
+uint32_t bytesPerPixel(PixelFormat format) {
     switch (format) {
         case PIXEL_FORMAT_RGBA_8888:
         case PIXEL_FORMAT_RGBX_8888:
@@ -36,10 +35,10 @@
         case PIXEL_FORMAT_RGBA_4444:
             return 2;
     }
-    return BAD_VALUE;
+    return 0;
 }
 
-ssize_t bitsPerPixel(PixelFormat format) {
+uint32_t bitsPerPixel(PixelFormat format) {
     switch (format) {
         case PIXEL_FORMAT_RGBA_8888:
         case PIXEL_FORMAT_RGBX_8888:
@@ -52,7 +51,7 @@
         case PIXEL_FORMAT_RGBA_4444:
             return 16;
     }
-    return BAD_VALUE;
+    return 0;
 }
 
 // ----------------------------------------------------------------------------
diff --git a/libs/ui/Region.cpp b/libs/ui/Region.cpp
index fa812f4..06ab3d0 100644
--- a/libs/ui/Region.cpp
+++ b/libs/ui/Region.cpp
@@ -102,8 +102,8 @@
         current--;
     } while (current->top == lastTop && current >= begin);
 
-    unsigned int beginLastSpan = -1;
-    unsigned int endLastSpan = -1;
+    int beginLastSpan = -1;
+    int endLastSpan = -1;
     int top = -1;
     int bottom = -1;
 
@@ -118,7 +118,7 @@
             } else {
                 beginLastSpan = endLastSpan + 1;
             }
-            endLastSpan = dst.size() - 1;
+            endLastSpan = static_cast<int>(dst.size()) - 1;
 
             top = current->top;
             bottom = current->bottom;
@@ -126,8 +126,12 @@
         int left = current->left;
         int right = current->right;
 
-        for (unsigned int prevIndex = beginLastSpan; prevIndex <= endLastSpan; prevIndex++) {
-            const Rect* prev = &dst[prevIndex];
+        for (int prevIndex = beginLastSpan; prevIndex <= endLastSpan; prevIndex++) {
+            // prevIndex can't be -1 here because if endLastSpan is set to a
+            // value greater than -1 (allowing the loop to execute),
+            // beginLastSpan (and therefore prevIndex) will also be increased
+            const Rect* prev = &dst[static_cast<size_t>(prevIndex)];
+
             if (spanDirection == direction_RTL) {
                 // iterating over previous span RTL, quit if it's too far left
                 if (prev->right <= left) break;
@@ -250,10 +254,10 @@
     mStorage.add(r);
 }
 
-void Region::set(uint32_t w, uint32_t h)
+void Region::set(int32_t w, int32_t h)
 {
     mStorage.clear();
-    mStorage.add(Rect(w,h));
+    mStorage.add(Rect(w, h));
 }
 
 bool Region::isTriviallyEqual(const Region& region) const {
@@ -404,7 +408,7 @@
 
 // This is our region rasterizer, which merges rects and spans together
 // to obtain an optimal region.
-class Region::rasterizer : public region_operator<Rect>::region_rasterizer 
+class Region::rasterizer : public region_operator<Rect>::region_rasterizer
 {
     Rect bounds;
     Vector<Rect>& storage;
@@ -413,81 +417,92 @@
     Vector<Rect> span;
     Rect* cur;
 public:
-    rasterizer(Region& reg) 
+    rasterizer(Region& reg)
         : bounds(INT_MAX, 0, INT_MIN, 0), storage(reg.mStorage), head(), tail(), cur() {
         storage.clear();
     }
 
-    ~rasterizer() {
-        if (span.size()) {
-            flushSpan();
-        }
-        if (storage.size()) {
-            bounds.top = storage.itemAt(0).top;
-            bounds.bottom = storage.top().bottom;
-            if (storage.size() == 1) {
-                storage.clear();
-            }
-        } else {
-            bounds.left  = 0;
-            bounds.right = 0;
-        }
-        storage.add(bounds);
-    }
-    
-    virtual void operator()(const Rect& rect) {
-        //ALOGD(">>> %3d, %3d, %3d, %3d",
-        //        rect.left, rect.top, rect.right, rect.bottom);
-        if (span.size()) {
-            if (cur->top != rect.top) {
-                flushSpan();
-            } else if (cur->right == rect.left) {
-                cur->right = rect.right;
-                return;
-            }
-        }
-        span.add(rect);
-        cur = span.editArray() + (span.size() - 1);
-    }
+    virtual ~rasterizer();
+
+    virtual void operator()(const Rect& rect);
+
 private:
-    template<typename T> 
+    template<typename T>
     static inline T min(T rhs, T lhs) { return rhs < lhs ? rhs : lhs; }
-    template<typename T> 
+    template<typename T>
     static inline T max(T rhs, T lhs) { return rhs > lhs ? rhs : lhs; }
-    void flushSpan() {
-        bool merge = false;
-        if (tail-head == ssize_t(span.size())) {
-            Rect const* p = span.editArray();
-            Rect const* q = head;
-            if (p->top == q->bottom) {
-                merge = true;
-                while (q != tail) {
-                    if ((p->left != q->left) || (p->right != q->right)) {
-                        merge = false;
-                        break;
-                    }
-                    p++, q++;
-                }
-            }
-        }
-        if (merge) {
-            const int bottom = span[0].bottom;
-            Rect* r = head;
-            while (r != tail) {
-                r->bottom = bottom;
-                r++;
-            }
-        } else {
-            bounds.left = min(span.itemAt(0).left, bounds.left);
-            bounds.right = max(span.top().right, bounds.right);
-            storage.appendVector(span);
-            tail = storage.editArray() + storage.size();
-            head = tail - span.size();
-        }
-        span.clear();
-    }
+
+    void flushSpan();
 };
 
+Region::rasterizer::~rasterizer()
+{
+    if (span.size()) {
+        flushSpan();
+    }
+    if (storage.size()) {
+        bounds.top = storage.itemAt(0).top;
+        bounds.bottom = storage.top().bottom;
+        if (storage.size() == 1) {
+            storage.clear();
+        }
+    } else {
+        bounds.left  = 0;
+        bounds.right = 0;
+    }
+    storage.add(bounds);
+}
+
+void Region::rasterizer::operator()(const Rect& rect)
+{
+    //ALOGD(">>> %3d, %3d, %3d, %3d",
+    //        rect.left, rect.top, rect.right, rect.bottom);
+    if (span.size()) {
+        if (cur->top != rect.top) {
+            flushSpan();
+        } else if (cur->right == rect.left) {
+            cur->right = rect.right;
+            return;
+        }
+    }
+    span.add(rect);
+    cur = span.editArray() + (span.size() - 1);
+}
+
+void Region::rasterizer::flushSpan()
+{
+    bool merge = false;
+    if (tail-head == ssize_t(span.size())) {
+        Rect const* p = span.editArray();
+        Rect const* q = head;
+        if (p->top == q->bottom) {
+            merge = true;
+            while (q != tail) {
+                if ((p->left != q->left) || (p->right != q->right)) {
+                    merge = false;
+                    break;
+                }
+                p++, q++;
+            }
+        }
+    }
+    if (merge) {
+        const int bottom = span[0].bottom;
+        Rect* r = head;
+        while (r != tail) {
+            r->bottom = bottom;
+            r++;
+        }
+    } else {
+        bounds.left = min(span.itemAt(0).left, bounds.left);
+        bounds.right = max(span.top().right, bounds.right);
+        storage.appendVector(span);
+        tail = storage.editArray() + storage.size();
+        head = tail - span.size();
+    }
+    span.clear();
+}
+
 bool Region::validate(const Region& reg, const char* name, bool silent)
 {
     bool result = true;
@@ -786,10 +801,8 @@
 }
 
 Rect const* Region::getArray(size_t* count) const {
-    const_iterator const b(begin());
-    const_iterator const e(end());
-    if (count) *count = e-b;
-    return b;
+    if (count) *count = static_cast<size_t>(end() - begin());
+    return begin();
 }
 
 SharedBuffer const* Region::getSharedBuffer(size_t* count) const {
@@ -806,29 +819,22 @@
 
 // ----------------------------------------------------------------------------
 
-void Region::dump(String8& out, const char* what, uint32_t flags) const
+void Region::dump(String8& out, const char* what, uint32_t /* flags */) const
 {
-    (void)flags;
     const_iterator head = begin();
     const_iterator const tail = end();
 
-    size_t SIZE = 256;
-    char buffer[SIZE];
-
-    snprintf(buffer, SIZE, "  Region %s (this=%p, count=%" PRIdPTR ")\n",
-            what, this, tail-head);
-    out.append(buffer);
+    out.appendFormat("  Region %s (this=%p, count=%" PRIdPTR ")\n",
+            what, this, tail - head);
     while (head != tail) {
-        snprintf(buffer, SIZE, "    [%3d, %3d, %3d, %3d]\n",
-                head->left, head->top, head->right, head->bottom);
-        out.append(buffer);
-        head++;
+        out.appendFormat("    [%3d, %3d, %3d, %3d]\n", head->left, head->top,
+                head->right, head->bottom);
+        ++head;
     }
 }
 
-void Region::dump(const char* what, uint32_t flags) const
+void Region::dump(const char* what, uint32_t /* flags */) const
 {
-    (void)flags;
     const_iterator head = begin();
     const_iterator const tail = end();
     ALOGD("  Region %s (this=%p, count=%" PRIdPTR ")\n", what, this, tail-head);
diff --git a/libs/ui/UiConfig.cpp b/libs/ui/UiConfig.cpp
index 8b2130e..9e7ba8e 100644
--- a/libs/ui/UiConfig.cpp
+++ b/libs/ui/UiConfig.cpp
@@ -18,8 +18,11 @@
 
 namespace android {
 
+#ifdef FRAMEBUFFER_FORCE_FORMAT
+// We need the two-level macro to stringify the contents of a macro argument
 #define STRINGIFY(x) #x
 #define TOSTRING(x) STRINGIFY(x)
+#endif
 
 void appendUiConfigString(String8& configStr)
 {
diff --git a/opengl/libs/EGL/egl_display.h b/opengl/libs/EGL/egl_display.h
index 87f27f8..0a6e425 100644
--- a/opengl/libs/EGL/egl_display.h
+++ b/opengl/libs/EGL/egl_display.h
@@ -39,7 +39,7 @@
 
 class egl_object_t;
 class egl_context_t;
-class egl_connection_t;
+struct egl_connection_t;
 
 // ----------------------------------------------------------------------------
 
diff --git a/opengl/libs/GLES_trace/Android.mk b/opengl/libs/GLES_trace/Android.mk
index d74f77a..7af7f69 100644
--- a/opengl/libs/GLES_trace/Android.mk
+++ b/opengl/libs/GLES_trace/Android.mk
@@ -20,8 +20,8 @@
     external \
 
 LOCAL_CFLAGS := -DGOOGLE_PROTOBUF_NO_RTTI
-LOCAL_STATIC_LIBRARIES := libprotobuf-cpp-2.3.0-lite liblzf
-LOCAL_SHARED_LIBRARIES := libcutils libutils liblog
+LOCAL_STATIC_LIBRARIES := liblzf
+LOCAL_SHARED_LIBRARIES := libcutils libutils liblog libprotobuf-cpp-lite
 
 LOCAL_CFLAGS += -DLOG_TAG=\"libGLES_trace\"
 
@@ -31,5 +31,4 @@
 LOCAL_MODULE:= libGLES_trace
 LOCAL_MODULE_TAGS := optional
 
-include external/stlport/libstlport.mk
 include $(BUILD_SHARED_LIBRARY)
diff --git a/opengl/tests/EGLTest/egl_cache_test.cpp b/opengl/tests/EGLTest/egl_cache_test.cpp
index c7d9e3e..c5bf296 100644
--- a/opengl/tests/EGLTest/egl_cache_test.cpp
+++ b/opengl/tests/EGLTest/egl_cache_test.cpp
@@ -41,7 +41,7 @@
 };
 
 TEST_F(EGLCacheTest, UninitializedCacheAlwaysMisses) {
-    char buf[4] = { 0xee, 0xee, 0xee, 0xee };
+    uint8_t buf[4] = { 0xee, 0xee, 0xee, 0xee };
     mCache->setBlob("abcd", 4, "efgh", 4);
     ASSERT_EQ(0, mCache->getBlob("abcd", 4, buf, 4));
     ASSERT_EQ(0xee, buf[0]);
@@ -51,7 +51,7 @@
 }
 
 TEST_F(EGLCacheTest, InitializedCacheAlwaysHits) {
-    char buf[4] = { 0xee, 0xee, 0xee, 0xee };
+    uint8_t buf[4] = { 0xee, 0xee, 0xee, 0xee };
     mCache->initialize(egl_display_t::get(EGL_DEFAULT_DISPLAY));
     mCache->setBlob("abcd", 4, "efgh", 4);
     ASSERT_EQ(4, mCache->getBlob("abcd", 4, buf, 4));
@@ -62,7 +62,7 @@
 }
 
 TEST_F(EGLCacheTest, TerminatedCacheAlwaysMisses) {
-    char buf[4] = { 0xee, 0xee, 0xee, 0xee };
+    uint8_t buf[4] = { 0xee, 0xee, 0xee, 0xee };
     mCache->initialize(egl_display_t::get(EGL_DEFAULT_DISPLAY));
     mCache->setBlob("abcd", 4, "efgh", 4);
     mCache->terminate();
@@ -94,7 +94,7 @@
 };
 
 TEST_F(EGLCacheSerializationTest, ReinitializedCacheContainsValues) {
-    char buf[4] = { 0xee, 0xee, 0xee, 0xee };
+    uint8_t buf[4] = { 0xee, 0xee, 0xee, 0xee };
     mCache->setCacheFilename(mFilename);
     mCache->initialize(egl_display_t::get(EGL_DEFAULT_DISPLAY));
     mCache->setBlob("abcd", 4, "efgh", 4);
diff --git a/opengl/tests/angeles/app-linux.cpp b/opengl/tests/angeles/app-linux.cpp
index e490351..ced8786 100644
--- a/opengl/tests/angeles/app-linux.cpp
+++ b/opengl/tests/angeles/app-linux.cpp
@@ -118,7 +118,7 @@
         fprintf(stderr, "EGL Error: 0x%04x\n", (int)error);
 }
 
-static int initGraphics(unsigned samples, const WindowSurface& windowSurface)
+static int initGraphics(EGLint samples, const WindowSurface& windowSurface)
 {
     EGLint configAttribs[] = {
             EGL_DEPTH_SIZE, 16,
diff --git a/opengl/tests/fillrate/fillrate.cpp b/opengl/tests/fillrate/fillrate.cpp
index 1d9b026..2db63d7 100644
--- a/opengl/tests/fillrate/fillrate.cpp
+++ b/opengl/tests/fillrate/fillrate.cpp
@@ -91,11 +91,13 @@
          }
      }
 
+     const GLfloat fh = h;
+     const GLfloat fw = w;
      const GLfloat vertices[4][2] = {
-             { 0,  0 },
-             { 0,  h },
-             { w,  h },
-             { w,  0 }
+             { 0,   0  },
+             { 0,   fh },
+             { fw,  fh },
+             { fw,  0  }
      };
 
      const GLfloat texCoords[4][2] = {
diff --git a/opengl/tests/filter/filter.cpp b/opengl/tests/filter/filter.cpp
index 289e6cc..287ee93 100644
--- a/opengl/tests/filter/filter.cpp
+++ b/opengl/tests/filter/filter.cpp
@@ -140,11 +140,12 @@
 
      //glDrawTexiOES(0, 0, 0, dim, dim);
      
+     const GLfloat fdim = dim;
      const GLfloat vertices[4][2] = {
-             { 0,    0   },
-             { 0,    dim },
-             { dim,  dim },
-             { dim,  0   }
+             { 0,     0    },
+             { 0,     fdim },
+             { fdim,  fdim },
+             { fdim,  0    }
      };
 
      const GLfloat texCoords[4][2] = {
diff --git a/opengl/tests/hwc/hwcColorEquiv.cpp b/opengl/tests/hwc/hwcColorEquiv.cpp
index c4624d2..06a0191 100644
--- a/opengl/tests/hwc/hwcColorEquiv.cpp
+++ b/opengl/tests/hwc/hwcColorEquiv.cpp
@@ -166,7 +166,6 @@
     int rv, opt;
     bool error;
     char *chptr;
-    unsigned int pass;
     char cmd[MAXCMD];
     string str;
 
@@ -293,14 +292,12 @@
     // Use the upper third of the display for the reference frame and
     // the middle third for the equivalence frame.
     unsigned int refHeight = height / 3;
-    unsigned int refPosY = 0; // Reference frame Y position
     unsigned int refPosX = 0; // Reference frame X position
     unsigned int refWidth = width - refPosX;
     if ((refWidth & refFormat->wMod) != 0) {
         refWidth += refFormat->wMod - (refWidth % refFormat->wMod);
     }
     unsigned int equivHeight = height / 3;
-    unsigned int equivPosY = refHeight; // Equivalence frame Y position
     unsigned int equivPosX = 0;         // Equivalence frame X position
     unsigned int equivWidth = width - equivPosX;
     if ((equivWidth & equivFormat->wMod) != 0) {
diff --git a/opengl/tests/hwc/hwcCommit.cpp b/opengl/tests/hwc/hwcCommit.cpp
index 1bd5fdf..1bcb860 100644
--- a/opengl/tests/hwc/hwcCommit.cpp
+++ b/opengl/tests/hwc/hwcCommit.cpp
@@ -338,7 +338,6 @@
 main(int argc, char *argv[])
 {
     int     rv, opt;
-    char   *chptr;
     bool    error;
     string  str;
     char cmd[MAXCMD];
diff --git a/opengl/tests/hwc/hwcRects.cpp b/opengl/tests/hwc/hwcRects.cpp
index 9b57623..56c1a2a 100644
--- a/opengl/tests/hwc/hwcRects.cpp
+++ b/opengl/tests/hwc/hwcRects.cpp
@@ -204,7 +204,6 @@
 {
     int     rv, opt;
     char   *chptr;
-    bool    error;
     string  str;
     char cmd[MAXCMD];
 
@@ -367,7 +366,6 @@
     istringstream in(rectStr);
     const struct hwcTestGraphicFormat *format;
     Rectangle rect;
-    struct hwc_rect hwcRect;
 
     // Graphic Format
     in >> str;
diff --git a/opengl/tests/hwc/hwcTestLib.cpp b/opengl/tests/hwc/hwcTestLib.cpp
index 9bad460..3b0ca74 100644
--- a/opengl/tests/hwc/hwcTestLib.cpp
+++ b/opengl/tests/hwc/hwcTestLib.cpp
@@ -36,7 +36,6 @@
 // Function Prototypes
 static void printGLString(const char *name, GLenum s);
 static void checkEglError(const char* op, EGLBoolean returnVal = EGL_TRUE);
-static void checkGlError(const char* op);
 static void printEGLConfiguration(EGLDisplay dpy, EGLConfig config);
 
 using namespace std;
@@ -52,8 +51,6 @@
 {
     static EGLContext context;
 
-    int rv;
-
     EGLBoolean returnValue;
     EGLConfig myConfig = {0};
     EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
@@ -669,7 +666,6 @@
 
     for (unsigned int x = 0; x < gBuf->getStride(); x++) {
         for (unsigned int y = 0; y < gBuf->getHeight(); y++) {
-            uint32_t val = pixel;
             hwcTestSetPixel(gBuf, buf, x, y, (x < gBuf->getWidth())
                             ? pixel : testRand());
         }
@@ -966,14 +962,6 @@
     }
 }
 
-static void checkGlError(const char* op)
-{
-    for (GLint error = glGetError(); error; error
-            = glGetError()) {
-        testPrintE("after %s() glError (0x%x)", op, error);
-    }
-}
-
 static void printEGLConfiguration(EGLDisplay dpy, EGLConfig config)
 {
 
diff --git a/opengl/tests/linetex/linetex.cpp b/opengl/tests/linetex/linetex.cpp
index 7921f80..5ad695b 100644
--- a/opengl/tests/linetex/linetex.cpp
+++ b/opengl/tests/linetex/linetex.cpp
@@ -80,9 +80,11 @@
      // default pack-alignment is 4
      const uint16_t t16[64] = { 0xFFFF, 0, 0xF800, 0, 0x07E0, 0, 0x001F, 0 };
 
+     const GLfloat fh = h;
+     const GLfloat fw2 = w/2;
      const GLfloat vertices[4][2] = {
-             { w/2,  0 },
-             { w/2,  h }
+             { fw2,  0  },
+             { fw2,  fh }
      };
 
      const GLfloat texCoords[4][2] = {
diff --git a/opengl/tools/glgen/stubs/egl/EGLExtcHeader.cpp b/opengl/tools/glgen/stubs/egl/EGLExtcHeader.cpp
index 9bd2ca4..4df61d3 100644
--- a/opengl/tools/glgen/stubs/egl/EGLExtcHeader.cpp
+++ b/opengl/tools/glgen/stubs/egl/EGLExtcHeader.cpp
@@ -85,23 +85,19 @@
     eglsurfaceConstructor = _env->GetMethodID(eglsurfaceClass, "<init>", "(J)V");
     eglconfigConstructor = _env->GetMethodID(eglconfigClass, "<init>", "(J)V");
 
-    jobject localeglNoContextObject = _env->NewObject(eglcontextClass, eglcontextConstructor, reinterpret_cast<jlong>(EGL_NO_CONTEXT));
-    eglNoContextObject = _env->NewGlobalRef(localeglNoContextObject);
-    jobject localeglNoDisplayObject = _env->NewObject(egldisplayClass, egldisplayConstructor, reinterpret_cast<jlong>(EGL_NO_DISPLAY));
-    eglNoDisplayObject = _env->NewGlobalRef(localeglNoDisplayObject);
-    jobject localeglNoSurfaceObject = _env->NewObject(eglsurfaceClass, eglsurfaceConstructor, reinterpret_cast<jlong>(EGL_NO_SURFACE));
-    eglNoSurfaceObject = _env->NewGlobalRef(localeglNoSurfaceObject);
-
 
     jclass eglClass = _env->FindClass("android/opengl/EGL14");
     jfieldID noContextFieldID = _env->GetStaticFieldID(eglClass, "EGL_NO_CONTEXT", "Landroid/opengl/EGLContext;");
-    _env->SetStaticObjectField(eglClass, noContextFieldID, eglNoContextObject);
+    jobject localeglNoContextObject = _env->GetStaticObjectField(eglClass, noContextFieldID);
+    eglNoContextObject = _env->NewGlobalRef(localeglNoContextObject);
 
     jfieldID noDisplayFieldID = _env->GetStaticFieldID(eglClass, "EGL_NO_DISPLAY", "Landroid/opengl/EGLDisplay;");
-    _env->SetStaticObjectField(eglClass, noDisplayFieldID, eglNoDisplayObject);
+    jobject localeglNoDisplayObject = _env->GetStaticObjectField(eglClass, noDisplayFieldID);
+    eglNoDisplayObject = _env->NewGlobalRef(localeglNoDisplayObject);
 
     jfieldID noSurfaceFieldID = _env->GetStaticFieldID(eglClass, "EGL_NO_SURFACE", "Landroid/opengl/EGLSurface;");
-    _env->SetStaticObjectField(eglClass, noSurfaceFieldID, eglNoSurfaceObject);
+    jobject localeglNoSurfaceObject = _env->GetStaticObjectField(eglClass, noSurfaceFieldID);
+    eglNoSurfaceObject = _env->NewGlobalRef(localeglNoSurfaceObject);
 }
 
 static void *
diff --git a/services/batteryservice/Android.mk b/services/batteryservice/Android.mk
index 9354b99..e4097d7 100644
--- a/services/batteryservice/Android.mk
+++ b/services/batteryservice/Android.mk
@@ -2,17 +2,19 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:= \
-	BatteryProperties.cpp \
-	BatteryProperty.cpp \
-	IBatteryPropertiesListener.cpp \
-	IBatteryPropertiesRegistrar.cpp
+    BatteryProperties.cpp \
+    BatteryProperty.cpp \
+    IBatteryPropertiesListener.cpp \
+    IBatteryPropertiesRegistrar.cpp
 
 LOCAL_STATIC_LIBRARIES := \
-	libutils \
-	libbinder
+    libutils \
+    libbinder
 
 LOCAL_MODULE:= libbatteryservice
 
 LOCAL_MODULE_TAGS := optional
 
+LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
+
 include $(BUILD_STATIC_LIBRARY)
diff --git a/services/batteryservice/IBatteryPropertiesListener.cpp b/services/batteryservice/IBatteryPropertiesListener.cpp
index 19ac7f0..8aff26c 100644
--- a/services/batteryservice/IBatteryPropertiesListener.cpp
+++ b/services/batteryservice/IBatteryPropertiesListener.cpp
@@ -35,7 +35,7 @@
         data.writeInterfaceToken(IBatteryPropertiesListener::getInterfaceDescriptor());
         data.writeInt32(1);
         props.writeToParcel(&data);
-        status_t err = remote()->transact(TRANSACT_BATTERYPROPERTIESCHANGED, data, &reply, IBinder::FLAG_ONEWAY);
+        remote()->transact(TRANSACT_BATTERYPROPERTIESCHANGED, data, &reply, IBinder::FLAG_ONEWAY);
     }
 };
 
diff --git a/services/batteryservice/IBatteryPropertiesRegistrar.cpp b/services/batteryservice/IBatteryPropertiesRegistrar.cpp
index 296bfab..46934e0 100644
--- a/services/batteryservice/IBatteryPropertiesRegistrar.cpp
+++ b/services/batteryservice/IBatteryPropertiesRegistrar.cpp
@@ -34,14 +34,14 @@
         void registerListener(const sp<IBatteryPropertiesListener>& listener) {
             Parcel data;
             data.writeInterfaceToken(IBatteryPropertiesRegistrar::getInterfaceDescriptor());
-            data.writeStrongBinder(listener->asBinder());
+            data.writeStrongBinder(IInterface::asBinder(listener));
             remote()->transact(REGISTER_LISTENER, data, NULL);
         }
 
         void unregisterListener(const sp<IBatteryPropertiesListener>& listener) {
             Parcel data;
             data.writeInterfaceToken(IBatteryPropertiesRegistrar::getInterfaceDescriptor());
-            data.writeStrongBinder(listener->asBinder());
+            data.writeStrongBinder(IInterface::asBinder(listener));
             remote()->transact(UNREGISTER_LISTENER, data, NULL);
         }
 
diff --git a/services/inputflinger/EventHub.cpp b/services/inputflinger/EventHub.cpp
index dfe5d3d..7a77c30 100644
--- a/services/inputflinger/EventHub.cpp
+++ b/services/inputflinger/EventHub.cpp
@@ -1443,7 +1443,7 @@
 }
 
 bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
-    if (!device->keyMap.haveKeyLayout() || !device->keyBitmask) {
+    if (!device->keyMap.haveKeyLayout()) {
         return false;
     }
     
@@ -1461,7 +1461,7 @@
 }
 
 status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
-    if (!device->keyMap.haveKeyLayout() || !device->ledBitmask) {
+    if (!device->keyMap.haveKeyLayout()) {
         return NAME_NOT_FOUND;
     }
 
diff --git a/services/inputflinger/tests/Android.mk b/services/inputflinger/tests/Android.mk
index 6dae82f..0742a08 100644
--- a/services/inputflinger/tests/Android.mk
+++ b/services/inputflinger/tests/Android.mk
@@ -16,20 +16,11 @@
     libhardware_legacy \
     libui \
     libskia \
-    libstlport \
     libinput \
     libinputflinger \
     libinputservice
 
-static_libraries := \
-    libgtest \
-    libgtest_main
-
 c_includes := \
-    bionic \
-    bionic/libstdc++/include \
-    external/gtest/include \
-    external/stlport/stlport \
     external/skia/include/core
 
 
@@ -38,9 +29,8 @@
 $(foreach file,$(test_src_files), \
     $(eval include $(CLEAR_VARS)) \
     $(eval LOCAL_SHARED_LIBRARIES := $(shared_libraries)) \
-    $(eval LOCAL_STATIC_LIBRARIES := $(static_libraries)) \
     $(eval LOCAL_C_INCLUDES := $(c_includes)) \
-	$(eval LOCAL_CFLAGS += -Wno-unused-parameter) \
+    $(eval LOCAL_CFLAGS += -Wno-unused-parameter) \
     $(eval LOCAL_SRC_FILES := $(file)) \
     $(eval LOCAL_MODULE := $(notdir $(file:%.cpp=%))) \
     $(eval LOCAL_MODULE_TAGS := $(module_tags)) \
diff --git a/services/powermanager/Android.mk b/services/powermanager/Android.mk
index d98b2da..7b24c65 100644
--- a/services/powermanager/Android.mk
+++ b/services/powermanager/Android.mk
@@ -2,14 +2,16 @@
 include $(CLEAR_VARS)
 
 LOCAL_SRC_FILES:= \
-	IPowerManager.cpp
+    IPowerManager.cpp
 
 LOCAL_SHARED_LIBRARIES := \
-	libutils \
-	libbinder
+    libutils \
+    libbinder
 
 LOCAL_MODULE:= libpowermanager
 
 LOCAL_MODULE_TAGS := optional
 
+LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
+
 include $(BUILD_SHARED_LIBRARY)
diff --git a/services/sensorservice/SensorService.cpp b/services/sensorservice/SensorService.cpp
index dc8fa64..9b2acea 100644
--- a/services/sensorservice/SensorService.cpp
+++ b/services/sensorservice/SensorService.cpp
@@ -617,12 +617,9 @@
         if (canAccessSensor(sensor)) {
             accessibleSensorList.add(sensor);
         } else {
-            String8 infoMessage;
-            infoMessage.appendFormat(
-                    "Skipped sensor %s because it requires permission %s",
-                    sensor.getName().string(),
-                    sensor.getRequiredPermission().string());
-            ALOGI(infoMessage.string());
+            ALOGI("Skipped sensor %s because it requires permission %s",
+                  sensor.getName().string(),
+                  sensor.getRequiredPermission().string());
         }
     }
     return accessibleSensorList;
diff --git a/services/sensorservice/SensorService.h b/services/sensorservice/SensorService.h
index 5e3eeb5..2e16677 100644
--- a/services/sensorservice/SensorService.h
+++ b/services/sensorservice/SensorService.h
@@ -37,6 +37,13 @@
 
 #include "SensorInterface.h"
 
+#if __clang__
+// Clang warns about SensorEventConnection::dump hiding BBinder::dump
+// The cause isn't fixable without changing the API, so let's tell clang
+// this is indeed intentional.
+#pragma clang diagnostic ignored "-Woverloaded-virtual"
+#endif
+
 // ---------------------------------------------------------------------------
 
 #define DEBUG_CONNECTIONS   false
diff --git a/services/surfaceflinger/Android.mk b/services/surfaceflinger/Android.mk
index a273c96..342d685 100644
--- a/services/surfaceflinger/Android.mk
+++ b/services/surfaceflinger/Android.mk
@@ -1,10 +1,10 @@
-LOCAL_PATH:= $(call my-dir)
+LOCAL_PATH := $(call my-dir)
 include $(CLEAR_VARS)
 
 LOCAL_CLANG := true
 
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
-LOCAL_SRC_FILES:= \
+LOCAL_SRC_FILES := \
     Client.cpp \
     DisplayDevice.cpp \
     DispSync.cpp \
@@ -37,18 +37,18 @@
     RenderEngine/GLES20RenderEngine.cpp
 
 
-LOCAL_CFLAGS:= -DLOG_TAG=\"SurfaceFlinger\"
+LOCAL_CFLAGS := -DLOG_TAG=\"SurfaceFlinger\"
 LOCAL_CFLAGS += -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
 
 ifeq ($(TARGET_BOARD_PLATFORM),omap4)
-	LOCAL_CFLAGS += -DHAS_CONTEXT_PRIORITY
+    LOCAL_CFLAGS += -DHAS_CONTEXT_PRIORITY
 endif
 ifeq ($(TARGET_BOARD_PLATFORM),s5pc110)
-	LOCAL_CFLAGS += -DHAS_CONTEXT_PRIORITY
+    LOCAL_CFLAGS += -DHAS_CONTEXT_PRIORITY
 endif
 
 ifeq ($(TARGET_DISABLE_TRIPLE_BUFFERING),true)
-	LOCAL_CFLAGS += -DTARGET_DISABLE_TRIPLE_BUFFERING
+    LOCAL_CFLAGS += -DTARGET_DISABLE_TRIPLE_BUFFERING
 endif
 
 ifeq ($(TARGET_FORCE_HWC_FOR_VIRTUAL_DISPLAYS),true)
@@ -56,7 +56,7 @@
 endif
 
 ifneq ($(NUM_FRAMEBUFFER_SURFACE_BUFFERS),)
-  LOCAL_CFLAGS += -DNUM_FRAMEBUFFER_SURFACE_BUFFERS=$(NUM_FRAMEBUFFER_SURFACE_BUFFERS)
+    LOCAL_CFLAGS += -DNUM_FRAMEBUFFER_SURFACE_BUFFERS=$(NUM_FRAMEBUFFER_SURFACE_BUFFERS)
 endif
 
 ifeq ($(TARGET_RUNNING_WITHOUT_SYNC_FRAMEWORK),true)
@@ -84,23 +84,25 @@
 endif
 
 LOCAL_CFLAGS += -fvisibility=hidden -Werror=format
-LOCAL_CFLAGS += -std=c++11
+LOCAL_CPPFLAGS := -std=c++11
 
 LOCAL_SHARED_LIBRARIES := \
-	libcutils \
-	liblog \
-	libdl \
-	libhardware \
-	libutils \
-	libEGL \
-	libGLESv1_CM \
-	libGLESv2 \
-	libbinder \
-	libui \
-	libgui \
-	libpowermanager
+    libcutils \
+    liblog \
+    libdl \
+    libhardware \
+    libutils \
+    libEGL \
+    libGLESv1_CM \
+    libGLESv2 \
+    libbinder \
+    libui \
+    libgui \
+    libpowermanager
 
-LOCAL_MODULE:= libsurfaceflinger
+LOCAL_MODULE := libsurfaceflinger
+
+LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
 
 include $(BUILD_SHARED_LIBRARY)
 
@@ -108,46 +110,56 @@
 # build surfaceflinger's executable
 include $(CLEAR_VARS)
 
-LOCAL_LDFLAGS := -Wl,--version-script,art/sigchainlib/version-script.txt -Wl,--export-dynamic
-LOCAL_CFLAGS:= -DLOG_TAG=\"SurfaceFlinger\"
-LOCAL_CPPFLAGS:= -std=c++11
+LOCAL_CLANG := true
 
-LOCAL_SRC_FILES:= \
-	main_surfaceflinger.cpp
+LOCAL_LDFLAGS := -Wl,--version-script,art/sigchainlib/version-script.txt -Wl,--export-dynamic
+LOCAL_CFLAGS := -DLOG_TAG=\"SurfaceFlinger\"
+LOCAL_CPPFLAGS := -std=c++11
+
+LOCAL_SRC_FILES := \
+    main_surfaceflinger.cpp
 
 LOCAL_SHARED_LIBRARIES := \
-	libsurfaceflinger \
-	libcutils \
-	liblog \
-	libbinder \
-	libutils \
-	libdl
+    libsurfaceflinger \
+    libcutils \
+    liblog \
+    libbinder \
+    libutils \
+    libdl
 
 LOCAL_WHOLE_STATIC_LIBRARIES := libsigchain
 
-LOCAL_MODULE:= surfaceflinger
+LOCAL_MODULE := surfaceflinger
 
 ifdef TARGET_32_BIT_SURFACEFLINGER
 LOCAL_32_BIT_ONLY := true
 endif
 
+LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
+
 include $(BUILD_EXECUTABLE)
 
 ###############################################################
 # uses jni which may not be available in PDK
 ifneq ($(wildcard libnativehelper/include),)
 include $(CLEAR_VARS)
-LOCAL_CFLAGS:= -DLOG_TAG=\"SurfaceFlinger\"
 
-LOCAL_SRC_FILES:= \
+LOCAL_CLANG := true
+
+LOCAL_CFLAGS := -DLOG_TAG=\"SurfaceFlinger\"
+LOCAL_CPPFLAGS := -std=c++11
+
+LOCAL_SRC_FILES := \
     DdmConnection.cpp
 
 LOCAL_SHARED_LIBRARIES := \
-	libcutils \
-	liblog \
-	libdl
+    libcutils \
+    liblog \
+    libdl
 
-LOCAL_MODULE:= libsurfaceflinger_ddmconnection
+LOCAL_MODULE := libsurfaceflinger_ddmconnection
+
+LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
 
 include $(BUILD_SHARED_LIBRARY)
 endif # libnativehelper
diff --git a/services/surfaceflinger/DdmConnection.cpp b/services/surfaceflinger/DdmConnection.cpp
index 2477921..a000a84 100644
--- a/services/surfaceflinger/DdmConnection.cpp
+++ b/services/surfaceflinger/DdmConnection.cpp
@@ -59,12 +59,14 @@
     }
 
     jint (*JNI_CreateJavaVM)(JavaVM** p_vm, JNIEnv** p_env, void* vm_args);
-    JNI_CreateJavaVM = (typeof JNI_CreateJavaVM)dlsym(libart_dso, "JNI_CreateJavaVM");
+    JNI_CreateJavaVM = reinterpret_cast<decltype(JNI_CreateJavaVM)>(
+            dlsym(libart_dso, "JNI_CreateJavaVM"));
     ALOGE_IF(!JNI_CreateJavaVM, "DdmConnection: %s", dlerror());
 
     jint (*registerNatives)(JNIEnv* env, jclass clazz);
-    registerNatives = (typeof registerNatives)dlsym(libandroid_runtime_dso,
-        "Java_com_android_internal_util_WithFramework_registerNatives");
+    registerNatives = reinterpret_cast<decltype(registerNatives)>(
+            dlsym(libandroid_runtime_dso,
+                  "Java_com_android_internal_util_WithFramework_registerNatives"));
     ALOGE_IF(!registerNatives, "DdmConnection: %s", dlerror());
 
     if (!JNI_CreateJavaVM || !registerNatives) {
diff --git a/services/surfaceflinger/DisplayDevice.cpp b/services/surfaceflinger/DisplayDevice.cpp
index 564f974..13d44f3 100644
--- a/services/surfaceflinger/DisplayDevice.cpp
+++ b/services/surfaceflinger/DisplayDevice.cpp
@@ -44,6 +44,18 @@
 using namespace android;
 // ----------------------------------------------------------------------------
 
+#ifdef EGL_ANDROID_swap_rectangle
+static constexpr bool kEGLAndroidSwapRectangle = true;
+#else
+static constexpr bool kEGLAndroidSwapRectangle = false;
+#endif
+
+#if !defined(EGL_EGLEXT_PROTOTYPES) || !defined(EGL_ANDROID_swap_rectangle)
+// Dummy implementation in case it is missing.
+inline void eglSetSwapRectangleANDROID (EGLDisplay, EGLSurface, EGLint, EGLint, EGLint, EGLint) {
+}
+#endif
+
 /*
  * Initialize the display to the specified values.
  *
@@ -84,7 +96,6 @@
      */
 
     EGLSurface surface;
-    EGLint w, h;
     EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
     if (config == EGL_NO_CONFIG) {
         config = RenderEngine::chooseEglConfig(display, format);
@@ -188,19 +199,14 @@
 {
     mFlinger->getRenderEngine().checkErrors();
 
-    EGLDisplay dpy = mDisplay;
-    EGLSurface surface = mSurface;
-
-#ifdef EGL_ANDROID_swap_rectangle
-    if (mFlags & SWAP_RECTANGLE) {
-        const Region newDirty(dirty.intersect(bounds()));
-        const Rect b(newDirty.getBounds());
-        eglSetSwapRectangleANDROID(dpy, surface,
-                b.left, b.top, b.width(), b.height());
+    if (kEGLAndroidSwapRectangle) {
+        if (mFlags & SWAP_RECTANGLE) {
+            const Region newDirty(dirty.intersect(bounds()));
+            const Rect b(newDirty.getBounds());
+            eglSetSwapRectangleANDROID(mDisplay, mSurface,
+                    b.left, b.top, b.width(), b.height());
+        }
     }
-#else
-    (void) dirty; // Eliminate unused parameter warning
-#endif
 
     mPageFlipCount++;
 }
@@ -511,6 +517,6 @@
         tr[0][2], tr[1][2], tr[2][2]);
 
     String8 surfaceDump;
-    mDisplaySurface->dump(surfaceDump);
+    mDisplaySurface->dumpAsString(surfaceDump);
     result.append(surfaceDump);
 }
diff --git a/services/surfaceflinger/DisplayHardware/DisplaySurface.h b/services/surfaceflinger/DisplayHardware/DisplaySurface.h
index e60c4fb..2f743c1 100644
--- a/services/surfaceflinger/DisplayHardware/DisplaySurface.h
+++ b/services/surfaceflinger/DisplayHardware/DisplaySurface.h
@@ -70,7 +70,7 @@
     // frame's buffer.
     virtual void onFrameCommitted() = 0;
 
-    virtual void dump(String8& result) const = 0;
+    virtual void dumpAsString(String8& result) const = 0;
 
     virtual void resizeBuffers(const uint32_t w, const uint32_t h) = 0;
 
diff --git a/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp b/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp
index 086ccf8..f9d76d1 100644
--- a/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp
+++ b/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp
@@ -68,7 +68,7 @@
     mConsumer->setDefaultMaxBufferCount(NUM_FRAMEBUFFER_SURFACE_BUFFERS);
 }
 
-status_t FramebufferSurface::beginFrame(bool mustRecompose) {
+status_t FramebufferSurface::beginFrame(bool /* mustRecompose */) {
     return NO_ERROR;
 }
 
@@ -160,23 +160,7 @@
     return mHwc.fbCompositionComplete();
 }
 
-// Since DisplaySurface and ConsumerBase both have a method with this
-// signature, results will vary based on the static pointer type the caller is
-// using:
-//   void dump(FrameBufferSurface* fbs, String8& s) {
-//       // calls FramebufferSurface::dump()
-//       fbs->dump(s);
-//
-//       // calls ConsumerBase::dump() since it is non-virtual
-//       static_cast<ConsumerBase*>(fbs)->dump(s);
-//
-//       // calls FramebufferSurface::dump() since it is virtual
-//       static_cast<DisplaySurface*>(fbs)->dump(s);
-//   }
-// To make sure that all of these end up doing the same thing, we just redirect
-// to ConsumerBase::dump() here. It will take the internal lock, and then call
-// virtual dumpLocked(), which is where the real work happens.
-void FramebufferSurface::dump(String8& result) const {
+void FramebufferSurface::dumpAsString(String8& result) const {
     ConsumerBase::dump(result);
 }
 
diff --git a/services/surfaceflinger/DisplayHardware/FramebufferSurface.h b/services/surfaceflinger/DisplayHardware/FramebufferSurface.h
index d0bf22b..6ffc52d 100644
--- a/services/surfaceflinger/DisplayHardware/FramebufferSurface.h
+++ b/services/surfaceflinger/DisplayHardware/FramebufferSurface.h
@@ -44,10 +44,7 @@
     virtual status_t compositionComplete();
     virtual status_t advanceFrame();
     virtual void onFrameCommitted();
-
-    // Implementation of DisplaySurface::dump(). Note that ConsumerBase also
-    // has a non-virtual dump() with the same signature.
-    virtual void dump(String8& result) const;
+    virtual void dumpAsString(String8& result) const;
 
     // Cannot resize a buffers in a FramebufferSurface. Only works with virtual
     // displays.
diff --git a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp
index c3d45ee..ef10fa7 100644
--- a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp
+++ b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp
@@ -254,7 +254,7 @@
     resetPerFrameState();
 }
 
-void VirtualDisplaySurface::dump(String8& /* result */) const {
+void VirtualDisplaySurface::dumpAsString(String8& /* result */) const {
 }
 
 void VirtualDisplaySurface::resizeBuffers(const uint32_t w, const uint32_t h) {
@@ -284,7 +284,7 @@
 }
 
 status_t VirtualDisplaySurface::dequeueBuffer(Source source,
-        uint32_t format, uint32_t usage, int* sslot, sp<Fence>* fence) {
+        PixelFormat format, uint32_t usage, int* sslot, sp<Fence>* fence) {
     LOG_FATAL_IF(mDisplayId < 0, "mDisplayId=%d but should not be < 0.", mDisplayId);
     // Don't let a slow consumer block us
     bool async = (source == SOURCE_SINK);
@@ -329,7 +329,7 @@
 }
 
 status_t VirtualDisplaySurface::dequeueBuffer(int* pslot, sp<Fence>* fence, bool async,
-        uint32_t w, uint32_t h, uint32_t format, uint32_t usage) {
+        uint32_t w, uint32_t h, PixelFormat format, uint32_t usage) {
     if (mDisplayId < 0)
         return mSource[SOURCE_SINK]->dequeueBuffer(pslot, fence, async, w, h, format, usage);
 
@@ -364,7 +364,7 @@
         usage |= GRALLOC_USAGE_HW_COMPOSER;
         const sp<GraphicBuffer>& buf = mProducerBuffers[mOutputProducerSlot];
         if ((usage & ~buf->getUsage()) != 0 ||
-                (format != 0 && format != (uint32_t)buf->getPixelFormat()) ||
+                (format != 0 && format != buf->getPixelFormat()) ||
                 (w != 0 && w != mSinkBufferWidth) ||
                 (h != 0 && h != mSinkBufferHeight)) {
             VDS_LOGV("dequeueBuffer: dequeueing new output buffer: "
@@ -517,7 +517,7 @@
 }
 
 void VirtualDisplaySurface::allocateBuffers(bool /* async */,
-        uint32_t /* width */, uint32_t /* height */, uint32_t /* format */,
+        uint32_t /* width */, uint32_t /* height */, PixelFormat /* format */,
         uint32_t /* usage */) {
     // TODO: Should we actually allocate buffers for a virtual display?
 }
diff --git a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h
index 363dce2..0a3f4a1 100644
--- a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h
+++ b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h
@@ -86,7 +86,7 @@
     virtual status_t compositionComplete();
     virtual status_t advanceFrame();
     virtual void onFrameCommitted();
-    virtual void dump(String8& result) const;
+    virtual void dumpAsString(String8& result) const;
     virtual void resizeBuffers(const uint32_t w, const uint32_t h);
 
 private:
@@ -100,7 +100,7 @@
     virtual status_t requestBuffer(int pslot, sp<GraphicBuffer>* outBuf);
     virtual status_t setBufferCount(int bufferCount);
     virtual status_t dequeueBuffer(int* pslot, sp<Fence>* fence, bool async,
-            uint32_t w, uint32_t h, uint32_t format, uint32_t usage);
+            uint32_t w, uint32_t h, PixelFormat format, uint32_t usage);
     virtual status_t detachBuffer(int slot);
     virtual status_t detachNextBuffer(sp<GraphicBuffer>* outBuffer,
             sp<Fence>* outFence);
@@ -114,13 +114,13 @@
     virtual status_t disconnect(int api);
     virtual status_t setSidebandStream(const sp<NativeHandle>& stream);
     virtual void allocateBuffers(bool async, uint32_t width, uint32_t height,
-            uint32_t format, uint32_t usage);
+            PixelFormat format, uint32_t usage);
 
     //
     // Utility methods
     //
     static Source fbSourceForCompositionType(CompositionType type);
-    status_t dequeueBuffer(Source source, uint32_t format, uint32_t usage,
+    status_t dequeueBuffer(Source source, PixelFormat format, uint32_t usage,
             int* sslot, sp<Fence>* fence);
     void updateQueueBufferOutput(const QueueBufferOutput& qbo);
     void resetPerFrameState();
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index fa07656..91e9a02 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -63,7 +63,6 @@
         mTextureName(-1U),
         mPremultipliedAlpha(true),
         mName("unnamed"),
-        mDebug(false),
         mFormat(PIXEL_FORMAT_NONE),
         mTransactionFlags(0),
         mQueuedFrames(0),
@@ -646,7 +645,6 @@
 
 void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
         const Region& /* clip */, bool useIdentityTransform) const {
-    const uint32_t fbHeight = hw->getHeight();
     const State& s(getDrawingState());
 
     computeGeometry(hw, mMesh, useIdentityTransform);
diff --git a/services/surfaceflinger/Layer.h b/services/surfaceflinger/Layer.h
index f0fe58a..2ef39e8 100644
--- a/services/surfaceflinger/Layer.h
+++ b/services/surfaceflinger/Layer.h
@@ -360,7 +360,6 @@
     uint32_t mTextureName;      // from GLES
     bool mPremultipliedAlpha;
     String8 mName;
-    mutable bool mDebug;
     PixelFormat mFormat;
 
     // these are protected by an external lock
diff --git a/services/surfaceflinger/LayerDim.h b/services/surfaceflinger/LayerDim.h
index 4de0ddc..60edd91 100644
--- a/services/surfaceflinger/LayerDim.h
+++ b/services/surfaceflinger/LayerDim.h
@@ -36,6 +36,7 @@
     virtual const char* getTypeId() const { return "LayerDim"; }
     virtual void onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
             bool useIdentityTransform) const;
+    using Layer::isOpaque;
     virtual bool isOpaque() const         { return false; }
     virtual bool isSecure() const         { return false; }
     virtual bool isFixedSize() const      { return true; }
diff --git a/services/surfaceflinger/MonitoredProducer.cpp b/services/surfaceflinger/MonitoredProducer.cpp
index 8739682..e4e7d42 100644
--- a/services/surfaceflinger/MonitoredProducer.cpp
+++ b/services/surfaceflinger/MonitoredProducer.cpp
@@ -49,7 +49,7 @@
         wp<IBinder> mProducer;
     };
 
-    mFlinger->postMessageAsync(new MessageCleanUpList(mFlinger, asBinder()));
+    mFlinger->postMessageAsync(new MessageCleanUpList(mFlinger, asBinder(this)));
 }
 
 status_t MonitoredProducer::requestBuffer(int slot, sp<GraphicBuffer>* buf) {
@@ -61,7 +61,7 @@
 }
 
 status_t MonitoredProducer::dequeueBuffer(int* slot, sp<Fence>* fence,
-        bool async, uint32_t w, uint32_t h, uint32_t format, uint32_t usage) {
+        bool async, uint32_t w, uint32_t h, PixelFormat format, uint32_t usage) {
     return mProducer->dequeueBuffer(slot, fence, async, w, h, format, usage);
 }
 
@@ -106,12 +106,12 @@
 }
 
 void MonitoredProducer::allocateBuffers(bool async, uint32_t width,
-        uint32_t height, uint32_t format, uint32_t usage) {
+        uint32_t height, PixelFormat format, uint32_t usage) {
     mProducer->allocateBuffers(async, width, height, format, usage);
 }
 
 IBinder* MonitoredProducer::onAsBinder() {
-    return mProducer->asBinder().get();
+    return IInterface::asBinder(mProducer).get();
 }
 
 // ---------------------------------------------------------------------------
diff --git a/services/surfaceflinger/MonitoredProducer.h b/services/surfaceflinger/MonitoredProducer.h
index f6ccc51..aec3e85 100644
--- a/services/surfaceflinger/MonitoredProducer.h
+++ b/services/surfaceflinger/MonitoredProducer.h
@@ -37,7 +37,7 @@
     virtual status_t requestBuffer(int slot, sp<GraphicBuffer>* buf);
     virtual status_t setBufferCount(int bufferCount);
     virtual status_t dequeueBuffer(int* slot, sp<Fence>* fence, bool async,
-            uint32_t w, uint32_t h, uint32_t format, uint32_t usage);
+            uint32_t w, uint32_t h, PixelFormat format, uint32_t usage);
     virtual status_t detachBuffer(int slot);
     virtual status_t detachNextBuffer(sp<GraphicBuffer>* outBuffer,
             sp<Fence>* outFence);
@@ -52,7 +52,7 @@
     virtual status_t disconnect(int api);
     virtual status_t setSidebandStream(const sp<NativeHandle>& stream);
     virtual void allocateBuffers(bool async, uint32_t width, uint32_t height,
-            uint32_t format, uint32_t usage);
+            PixelFormat format, uint32_t usage);
     virtual IBinder* onAsBinder();
 
 private:
diff --git a/services/surfaceflinger/RenderEngine/GLES11RenderEngine.cpp b/services/surfaceflinger/RenderEngine/GLES11RenderEngine.cpp
index c2768f3..2e6af49 100644
--- a/services/surfaceflinger/RenderEngine/GLES11RenderEngine.cpp
+++ b/services/surfaceflinger/RenderEngine/GLES11RenderEngine.cpp
@@ -43,12 +43,6 @@
     glDisable(GL_DITHER);
     glDisable(GL_CULL_FACE);
 
-    struct pack565 {
-        inline uint16_t operator() (int r, int g, int b) const {
-            return (r<<11)|(g<<5)|b;
-        }
-    } pack565;
-
     const uint16_t protTexData[] = { 0 };
     glGenTextures(1, &mProtectedTexName);
     glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
diff --git a/services/surfaceflinger/RenderEngine/GLES20RenderEngine.cpp b/services/surfaceflinger/RenderEngine/GLES20RenderEngine.cpp
index 8ebafbc..8712c9a 100644
--- a/services/surfaceflinger/RenderEngine/GLES20RenderEngine.cpp
+++ b/services/surfaceflinger/RenderEngine/GLES20RenderEngine.cpp
@@ -48,12 +48,6 @@
     glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
     glPixelStorei(GL_PACK_ALIGNMENT, 4);
 
-    struct pack565 {
-        inline uint16_t operator() (int r, int g, int b) const {
-            return (r<<11)|(g<<5)|b;
-        }
-    } pack565;
-
     const uint16_t protTexData[] = { 0 };
     glGenTextures(1, &mProtectedTexName);
     glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
diff --git a/services/surfaceflinger/RenderEngine/RenderEngine.cpp b/services/surfaceflinger/RenderEngine/RenderEngine.cpp
index d5d5da8..767b714 100644
--- a/services/surfaceflinger/RenderEngine/RenderEngine.cpp
+++ b/services/surfaceflinger/RenderEngine/RenderEngine.cpp
@@ -279,7 +279,6 @@
 
 static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs,
         EGLint attribute, EGLint wanted, EGLConfig* outConfig) {
-    EGLConfig config = NULL;
     EGLint numConfigs = -1, n = 0;
     eglGetConfigs(dpy, NULL, 0, &numConfigs);
     EGLConfig* const configs = new EGLConfig[numConfigs];
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index c6a4c7a..8daf0f9 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -388,7 +388,6 @@
     ALOGI(  "SurfaceFlinger's main thread ready to run. "
             "Initializing graphics H/W...");
 
-    status_t err;
     Mutex::Autolock _l(mStateLock);
 
     // initialize EGL for the default display
@@ -497,7 +496,7 @@
 bool SurfaceFlinger::authenticateSurfaceTexture(
         const sp<IGraphicBufferProducer>& bufferProducer) const {
     Mutex::Autolock _l(mStateLock);
-    sp<IBinder> surfaceTextureBinder(bufferProducer->asBinder());
+    sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
     return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
 }
 
@@ -604,7 +603,7 @@
     return NO_ERROR;
 }
 
-status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& display,
+status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
         DisplayStatInfo* stats) {
     if (stats == NULL) {
         return BAD_VALUE;
@@ -653,7 +652,7 @@
         virtual bool handler() {
             Vector<DisplayInfo> configs;
             mFlinger.getDisplayConfigs(mDisplay, &configs);
-            if(mMode < 0 || mMode >= configs.size()) {
+            if(mMode < 0 || static_cast<size_t>(mMode) >= configs.size()) {
                 ALOGE("Attempt to set active config = %d for display with %zu configs",
                         mMode, configs.size());
             }
@@ -1274,10 +1273,8 @@
                     // this display is in both lists. see if something changed.
                     const DisplayDeviceState& state(curr[j]);
                     const wp<IBinder>& display(curr.keyAt(j));
-                    const sp<IBinder> state_binder =
-                        state.surface != NULL ? state.surface->asBinder() : NULL;
-                    const sp<IBinder> draw_binder =
-                        draw[i].surface != NULL ? draw[i].surface->asBinder() : NULL;
+                    const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
+                    const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
                     if (state_binder != draw_binder) {
                         // changing the surface is like destroying and
                         // recreating the DisplayDevice, so we just remove it
@@ -1911,7 +1908,7 @@
     // add this layer to the current state list
     Mutex::Autolock _l(mStateLock);
     mCurrentState.layersSortedByZ.add(lbc);
-    mGraphicBufferProducerList.add(gbc->asBinder());
+    mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
 }
 
 status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
@@ -1984,7 +1981,7 @@
         // NOTE: it would be better to use RTTI as we could directly check
         // that we have a Client*. however, RTTI is disabled in Android.
         if (s.client != NULL) {
-            sp<IBinder> binder = s.client->asBinder();
+            sp<IBinder> binder = IInterface::asBinder(s.client);
             if (binder != NULL) {
                 String16 desc(binder->getInterfaceDescriptor());
                 if (desc == ISurfaceComposerClient::descriptor) {
@@ -2031,7 +2028,7 @@
     if (disp.isValid()) {
         const uint32_t what = s.what;
         if (what & DisplayState::eSurfaceChanged) {
-            if (disp.surface->asBinder() != s.surface->asBinder()) {
+            if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
                 disp.surface = s.surface;
                 flags |= eDisplayTransactionNeeded;
             }
@@ -2922,7 +2919,7 @@
         // Prevent reads below from happening before the read from Message
         atomic_thread_fence(memory_order_acquire);
         if (what == MSG_API_CALL) {
-            result = impl->asBinder()->transact(code, data[0], reply);
+            result = IInterface::asBinder(impl)->transact(code, data[0], reply);
             barrier.open();
         } else if (what == MSG_EXIT) {
             exitRequested = true;
@@ -2972,7 +2969,7 @@
     // if we have secure windows on this display, never allow the screen capture
     // unless the producer interface is local (i.e.: we can take a screenshot for
     // ourselves).
-    if (!producer->asBinder()->localBinder()) {
+    if (!IInterface::asBinder(producer)->localBinder()) {
         Mutex::Autolock _l(mStateLock);
         sp<const DisplayDevice> hw(getDisplayDevice(display));
         if (hw->getSecureLayerVisible()) {
@@ -3036,7 +3033,7 @@
             result = flinger->captureScreenImplLocked(hw, producer,
                     sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
                     useIdentityTransform, rotation);
-            static_cast<GraphicProducerWrapper*>(producer->asBinder().get())->exit(result);
+            static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
             return true;
         }
     };
@@ -3078,9 +3075,10 @@
     RenderEngine& engine(getRenderEngine());
 
     // get screen geometry
-    const uint32_t hw_w = hw->getWidth();
-    const uint32_t hw_h = hw->getHeight();
-    const bool filtering = reqWidth != hw_w || reqWidth != hw_h;
+    const int32_t hw_w = hw->getWidth();
+    const int32_t hw_h = hw->getHeight();
+    const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
+                           static_cast<int32_t>(reqWidth) != hw_h;
 
     // if a default or invalid sourceCrop is passed in, set reasonable values
     if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||