Merge "Use bspatch from external/bsdiff."
diff --git a/adb_install.cpp b/adb_install.cpp
index fab72f8..79b8df9 100644
--- a/adb_install.cpp
+++ b/adb_install.cpp
@@ -78,7 +78,7 @@
     pid_t child;
     if ((child = fork()) == 0) {
         execl("/sbin/recovery", "recovery", "--adbd", NULL);
-        _exit(-1);
+        _exit(EXIT_FAILURE);
     }
 
     // FUSE_SIDELOAD_HOST_PATHNAME will start to exist once the host
diff --git a/install.cpp b/install.cpp
index 959a742..ce89e0d 100644
--- a/install.cpp
+++ b/install.cpp
@@ -382,8 +382,12 @@
     umask(022);
     close(pipefd[0]);
     execv(chr_args[0], const_cast<char**>(chr_args));
-    PLOG(ERROR) << "Can't run " << chr_args[0];
-    _exit(-1);
+    // Bug: 34769056
+    // We shouldn't use LOG/PLOG in the forked process, since they may cause
+    // the child process to hang. This deadlock results from an improperly
+    // copied mutex in the ui functions.
+    fprintf(stdout, "E:Can't run %s (%s)\n", chr_args[0], strerror(errno));
+    _exit(EXIT_FAILURE);
   }
   close(pipefd[1]);
 
diff --git a/minui/graphics.cpp b/minui/graphics.cpp
index 34ea81c..3bdc33f 100644
--- a/minui/graphics.cpp
+++ b/minui/graphics.cpp
@@ -16,27 +16,20 @@
 
 #include "graphics.h"
 
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <unistd.h>
 
-#include <fcntl.h>
-#include <stdio.h>
-
-#include <sys/ioctl.h>
-#include <sys/mman.h>
-#include <sys/types.h>
-
-#include <linux/fb.h>
-#include <linux/kd.h>
-
-#include <time.h>
+#include <memory>
 
 #include "font_10x18.h"
+#include "graphics_adf.h"
+#include "graphics_drm.h"
+#include "graphics_fbdev.h"
 #include "minui/minui.h"
 
 static GRFont* gr_font = NULL;
-static minui_backend* gr_backend = NULL;
+static MinuiBackend* gr_backend = nullptr;
 
 static int overscan_percent = OVERSCAN_PERCENT;
 static int overscan_offset_x = 0;
@@ -319,109 +312,53 @@
     gr_font->char_height = font.char_height;
 }
 
-#if 0
-// Exercises many of the gr_*() functions; useful for testing.
-static void gr_test() {
-    GRSurface** images;
-    int frames;
-    int result = res_create_multi_surface("icon_installing", &frames, &images);
-    if (result < 0) {
-        printf("create surface %d\n", result);
-        gr_exit();
-        return;
-    }
-
-    time_t start = time(NULL);
-    int x;
-    for (x = 0; x <= 1200; ++x) {
-        if (x < 400) {
-            gr_color(0, 0, 0, 255);
-        } else {
-            gr_color(0, (x-400)%128, 0, 255);
-        }
-        gr_clear();
-
-        gr_color(255, 0, 0, 255);
-        GRSurface* frame = images[x%frames];
-        gr_blit(frame, 0, 0, frame->width, frame->height, x, 0);
-
-        gr_color(255, 0, 0, 128);
-        gr_fill(400, 150, 600, 350);
-
-        gr_color(255, 255, 255, 255);
-        gr_text(500, 225, "hello, world!", 0);
-        gr_color(255, 255, 0, 128);
-        gr_text(300+x, 275, "pack my box with five dozen liquor jugs", 1);
-
-        gr_color(0, 0, 255, 128);
-        gr_fill(gr_draw->width - 200 - x, 300, gr_draw->width - x, 500);
-
-        gr_draw = gr_backend->flip(gr_backend);
-    }
-    printf("getting end time\n");
-    time_t end = time(NULL);
-    printf("got end time\n");
-    printf("start %ld end %ld\n", (long)start, (long)end);
-    if (end > start) {
-        printf("%.2f fps\n", ((double)x) / (end-start));
-    }
-}
-#endif
-
 void gr_flip() {
-    gr_draw = gr_backend->flip(gr_backend);
+  gr_draw = gr_backend->Flip();
 }
 
-int gr_init(void)
-{
-    gr_init_font();
+int gr_init() {
+  gr_init_font();
 
-    gr_backend = open_adf();
-    if (gr_backend) {
-        gr_draw = gr_backend->init(gr_backend);
-        if (!gr_draw) {
-            gr_backend->exit(gr_backend);
-        }
-    }
+  auto backend = std::unique_ptr<MinuiBackend>{ std::make_unique<MinuiBackendAdf>() };
+  gr_draw = backend->Init();
 
-    if (!gr_draw) {
-        gr_backend = open_drm();
-        gr_draw = gr_backend->init(gr_backend);
-    }
+  if (!gr_draw) {
+    backend = std::make_unique<MinuiBackendDrm>();
+    gr_draw = backend->Init();
+  }
 
-    if (!gr_draw) {
-        gr_backend = open_fbdev();
-        gr_draw = gr_backend->init(gr_backend);
-        if (gr_draw == NULL) {
-            return -1;
-        }
-    }
+  if (!gr_draw) {
+    backend = std::make_unique<MinuiBackendFbdev>();
+    gr_draw = backend->Init();
+  }
 
-    overscan_offset_x = gr_draw->width * overscan_percent / 100;
-    overscan_offset_y = gr_draw->height * overscan_percent / 100;
+  if (!gr_draw) {
+    return -1;
+  }
 
-    gr_flip();
-    gr_flip();
+  gr_backend = backend.release();
 
-    return 0;
+  overscan_offset_x = gr_draw->width * overscan_percent / 100;
+  overscan_offset_y = gr_draw->height * overscan_percent / 100;
+
+  gr_flip();
+  gr_flip();
+
+  return 0;
 }
 
-void gr_exit(void)
-{
-    gr_backend->exit(gr_backend);
+void gr_exit() {
+  delete gr_backend;
 }
 
-int gr_fb_width(void)
-{
-    return gr_draw->width - 2*overscan_offset_x;
+int gr_fb_width() {
+  return gr_draw->width - 2 * overscan_offset_x;
 }
 
-int gr_fb_height(void)
-{
-    return gr_draw->height - 2*overscan_offset_y;
+int gr_fb_height() {
+  return gr_draw->height - 2 * overscan_offset_y;
 }
 
-void gr_fb_blank(bool blank)
-{
-    gr_backend->blank(gr_backend, blank);
+void gr_fb_blank(bool blank) {
+  gr_backend->Blank(blank);
 }
diff --git a/minui/graphics.h b/minui/graphics.h
index 1eaafc7..3c45a40 100644
--- a/minui/graphics.h
+++ b/minui/graphics.h
@@ -19,25 +19,20 @@
 
 #include "minui/minui.h"
 
-// TODO: lose the function pointers.
-struct minui_backend {
-    // Initializes the backend and returns a GRSurface* to draw into.
-    GRSurface* (*init)(minui_backend*);
+class MinuiBackend {
+ public:
+  // Initializes the backend and returns a GRSurface* to draw into.
+  virtual GRSurface* Init() = 0;
 
-    // Causes the current drawing surface (returned by the most recent
-    // call to flip() or init()) to be displayed, and returns a new
-    // drawing surface.
-    GRSurface* (*flip)(minui_backend*);
+  // Causes the current drawing surface (returned by the most recent call to Flip() or Init()) to
+  // be displayed, and returns a new drawing surface.
+  virtual GRSurface* Flip() = 0;
 
-    // Blank (or unblank) the screen.
-    void (*blank)(minui_backend*, bool);
+  // Blank (or unblank) the screen.
+  virtual void Blank(bool) = 0;
 
-    // Device cleanup when drawing is done.
-    void (*exit)(minui_backend*);
+  // Device cleanup when drawing is done.
+  virtual ~MinuiBackend() {};
 };
 
-minui_backend* open_fbdev();
-minui_backend* open_adf();
-minui_backend* open_drm();
-
-#endif
+#endif  // _GRAPHICS_H_
diff --git a/minui/graphics_adf.cpp b/minui/graphics_adf.cpp
index 9e262b0..1b15a04 100644
--- a/minui/graphics_adf.cpp
+++ b/minui/graphics_adf.cpp
@@ -14,260 +14,184 @@
  * limitations under the License.
  */
 
+#include "graphics_adf.h"
+
 #include <errno.h>
 #include <fcntl.h>
-#include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <sys/cdefs.h>
 #include <sys/mman.h>
+#include <unistd.h>
 
 #include <adf/adf.h>
 #include <sync/sync.h>
 
-#include "graphics.h"
+#include "minui/minui.h"
 
-struct adf_surface_pdata {
-    GRSurface base;
-    int fence_fd;
-    int fd;
-    __u32 offset;
-    __u32 pitch;
-};
+MinuiBackendAdf::MinuiBackendAdf() : intf_fd(-1), dev(), n_surfaces(0), surfaces() {}
 
-struct adf_pdata {
-    minui_backend base;
-    int intf_fd;
-    adf_id_t eng_id;
-    __u32 format;
+int MinuiBackendAdf::SurfaceInit(const drm_mode_modeinfo* mode, GRSurfaceAdf* surf) {
+  *surf = {};
+  surf->fence_fd = -1;
+  surf->fd = adf_interface_simple_buffer_alloc(intf_fd, mode->hdisplay, mode->vdisplay, format,
+                                               &surf->offset, &surf->pitch);
+  if (surf->fd < 0) {
+    return surf->fd;
+  }
 
-    adf_device dev;
+  surf->width = mode->hdisplay;
+  surf->height = mode->vdisplay;
+  surf->row_bytes = surf->pitch;
+  surf->pixel_bytes = (format == DRM_FORMAT_RGB565) ? 2 : 4;
 
-    unsigned int current_surface;
-    unsigned int n_surfaces;
-    adf_surface_pdata surfaces[2];
-};
+  surf->data = static_cast<uint8_t*>(
+      mmap(nullptr, surf->pitch * surf->height, PROT_WRITE, MAP_SHARED, surf->fd, surf->offset));
+  if (surf->data == MAP_FAILED) {
+    int saved_errno = errno;
+    close(surf->fd);
+    return -saved_errno;
+  }
 
-static GRSurface* adf_flip(minui_backend *backend);
-static void adf_blank(minui_backend *backend, bool blank);
-
-static int adf_surface_init(adf_pdata *pdata, drm_mode_modeinfo *mode, adf_surface_pdata *surf) {
-    memset(surf, 0, sizeof(*surf));
-
-    surf->fence_fd = -1;
-    surf->fd = adf_interface_simple_buffer_alloc(pdata->intf_fd, mode->hdisplay,
-            mode->vdisplay, pdata->format, &surf->offset, &surf->pitch);
-    if (surf->fd < 0)
-        return surf->fd;
-
-    surf->base.width = mode->hdisplay;
-    surf->base.height = mode->vdisplay;
-    surf->base.row_bytes = surf->pitch;
-    surf->base.pixel_bytes = (pdata->format == DRM_FORMAT_RGB565) ? 2 : 4;
-
-    surf->base.data = static_cast<uint8_t*>(mmap(NULL,
-                                                 surf->pitch * surf->base.height, PROT_WRITE,
-                                                 MAP_SHARED, surf->fd, surf->offset));
-    if (surf->base.data == MAP_FAILED) {
-        close(surf->fd);
-        return -errno;
-    }
-
-    return 0;
+  return 0;
 }
 
-static int adf_interface_init(adf_pdata *pdata)
-{
-    adf_interface_data intf_data;
-    int ret = 0;
-    int err;
+int MinuiBackendAdf::InterfaceInit() {
+  adf_interface_data intf_data;
+  int err = adf_get_interface_data(intf_fd, &intf_data);
+  if (err < 0) return err;
 
-    err = adf_get_interface_data(pdata->intf_fd, &intf_data);
-    if (err < 0)
-        return err;
+  int ret = 0;
+  err = SurfaceInit(&intf_data.current_mode, &surfaces[0]);
+  if (err < 0) {
+    fprintf(stderr, "allocating surface 0 failed: %s\n", strerror(-err));
+    ret = err;
+    goto done;
+  }
 
-    err = adf_surface_init(pdata, &intf_data.current_mode, &pdata->surfaces[0]);
-    if (err < 0) {
-        fprintf(stderr, "allocating surface 0 failed: %s\n", strerror(-err));
-        ret = err;
-        goto done;
-    }
-
-    err = adf_surface_init(pdata, &intf_data.current_mode,
-            &pdata->surfaces[1]);
-    if (err < 0) {
-        fprintf(stderr, "allocating surface 1 failed: %s\n", strerror(-err));
-        memset(&pdata->surfaces[1], 0, sizeof(pdata->surfaces[1]));
-        pdata->n_surfaces = 1;
-    } else {
-        pdata->n_surfaces = 2;
-    }
+  err = SurfaceInit(&intf_data.current_mode, &surfaces[1]);
+  if (err < 0) {
+    fprintf(stderr, "allocating surface 1 failed: %s\n", strerror(-err));
+    surfaces[1] = {};
+    n_surfaces = 1;
+  } else {
+    n_surfaces = 2;
+  }
 
 done:
-    adf_free_interface_data(&intf_data);
-    return ret;
+  adf_free_interface_data(&intf_data);
+  return ret;
 }
 
-static int adf_device_init(adf_pdata *pdata, adf_device *dev)
-{
-    adf_id_t intf_id;
-    int intf_fd;
-    int err;
+int MinuiBackendAdf::DeviceInit(adf_device* dev) {
+  adf_id_t intf_id;
+  int err = adf_find_simple_post_configuration(dev, &format, 1, &intf_id, &eng_id);
+  if (err < 0) return err;
 
-    err = adf_find_simple_post_configuration(dev, &pdata->format, 1, &intf_id,
-            &pdata->eng_id);
-    if (err < 0)
-        return err;
+  err = adf_device_attach(dev, eng_id, intf_id);
+  if (err < 0 && err != -EALREADY) return err;
 
-    err = adf_device_attach(dev, pdata->eng_id, intf_id);
-    if (err < 0 && err != -EALREADY)
-        return err;
+  intf_fd = adf_interface_open(dev, intf_id, O_RDWR);
+  if (intf_fd < 0) return intf_fd;
 
-    pdata->intf_fd = adf_interface_open(dev, intf_id, O_RDWR);
-    if (pdata->intf_fd < 0)
-        return pdata->intf_fd;
+  err = InterfaceInit();
+  if (err < 0) {
+    close(intf_fd);
+    intf_fd = -1;
+  }
 
-    err = adf_interface_init(pdata);
-    if (err < 0) {
-        close(pdata->intf_fd);
-        pdata->intf_fd = -1;
-    }
-
-    return err;
+  return err;
 }
 
-static GRSurface* adf_init(minui_backend *backend)
-{
-    adf_pdata *pdata = (adf_pdata *)backend;
-    adf_id_t *dev_ids = NULL;
-    ssize_t n_dev_ids, i;
-    GRSurface* ret;
-
+GRSurface* MinuiBackendAdf::Init() {
 #if defined(RECOVERY_ABGR)
-    pdata->format = DRM_FORMAT_ABGR8888;
+  format = DRM_FORMAT_ABGR8888;
 #elif defined(RECOVERY_BGRA)
-    pdata->format = DRM_FORMAT_BGRA8888;
+  format = DRM_FORMAT_BGRA8888;
 #elif defined(RECOVERY_RGBX)
-    pdata->format = DRM_FORMAT_RGBX8888;
+  format = DRM_FORMAT_RGBX8888;
 #else
-    pdata->format = DRM_FORMAT_RGB565;
+  format = DRM_FORMAT_RGB565;
 #endif
 
-    n_dev_ids = adf_devices(&dev_ids);
-    if (n_dev_ids == 0) {
-        return NULL;
-    } else if (n_dev_ids < 0) {
-        fprintf(stderr, "enumerating adf devices failed: %s\n",
-                strerror(-n_dev_ids));
-        return NULL;
+  adf_id_t* dev_ids = nullptr;
+  ssize_t n_dev_ids = adf_devices(&dev_ids);
+  if (n_dev_ids == 0) {
+    return nullptr;
+  } else if (n_dev_ids < 0) {
+    fprintf(stderr, "enumerating adf devices failed: %s\n", strerror(-n_dev_ids));
+    return nullptr;
+  }
+
+  intf_fd = -1;
+
+  for (ssize_t i = 0; i < n_dev_ids && intf_fd < 0; i++) {
+    int err = adf_device_open(dev_ids[i], O_RDWR, &dev);
+    if (err < 0) {
+      fprintf(stderr, "opening adf device %u failed: %s\n", dev_ids[i], strerror(-err));
+      continue;
     }
 
-    pdata->intf_fd = -1;
+    err = DeviceInit(&dev);
+    if (err < 0) {
+      fprintf(stderr, "initializing adf device %u failed: %s\n", dev_ids[i], strerror(-err));
+      adf_device_close(&dev);
+    }
+  }
 
-    for (i = 0; i < n_dev_ids && pdata->intf_fd < 0; i++) {
+  free(dev_ids);
 
-        int err = adf_device_open(dev_ids[i], O_RDWR, &pdata->dev);
-        if (err < 0) {
-            fprintf(stderr, "opening adf device %u failed: %s\n", dev_ids[i],
-                    strerror(-err));
-            continue;
-        }
+  if (intf_fd < 0) return nullptr;
 
-        err = adf_device_init(pdata, &pdata->dev);
-        if (err < 0) {
-            fprintf(stderr, "initializing adf device %u failed: %s\n",
-                    dev_ids[i], strerror(-err));
-            adf_device_close(&pdata->dev);
-        }
+  GRSurface* ret = Flip();
+
+  Blank(true);
+  Blank(false);
+
+  return ret;
+}
+
+void MinuiBackendAdf::Sync(GRSurfaceAdf* surf) {
+  static constexpr unsigned int warningTimeout = 3000;
+
+  if (surf == nullptr) return;
+
+  if (surf->fence_fd >= 0) {
+    int err = sync_wait(surf->fence_fd, warningTimeout);
+    if (err < 0) {
+      perror("adf sync fence wait error\n");
     }
 
-    free(dev_ids);
-
-    if (pdata->intf_fd < 0)
-        return NULL;
-
-    ret = adf_flip(backend);
-
-    adf_blank(backend, true);
-    adf_blank(backend, false);
-
-    return ret;
-}
-
-static void adf_sync(adf_surface_pdata *surf)
-{
-    unsigned int warningTimeout = 3000;
-
-    if (surf == NULL)
-        return;
-
-    if (surf->fence_fd >= 0){
-        int err = sync_wait(surf->fence_fd, warningTimeout);
-        if (err < 0)
-            perror("adf sync fence wait error\n");
-
-        close(surf->fence_fd);
-        surf->fence_fd = -1;
-    }
-}
-
-static GRSurface* adf_flip(minui_backend *backend)
-{
-    adf_pdata *pdata = (adf_pdata *)backend;
-    adf_surface_pdata *surf = &pdata->surfaces[pdata->current_surface];
-
-    int fence_fd = adf_interface_simple_post(pdata->intf_fd, pdata->eng_id,
-            surf->base.width, surf->base.height, pdata->format, surf->fd,
-            surf->offset, surf->pitch, -1);
-    if (fence_fd >= 0)
-        surf->fence_fd = fence_fd;
-
-    pdata->current_surface = (pdata->current_surface + 1) % pdata->n_surfaces;
-    adf_sync(&pdata->surfaces[pdata->current_surface]);
-    return &pdata->surfaces[pdata->current_surface].base;
-}
-
-static void adf_blank(minui_backend *backend, bool blank)
-{
-    adf_pdata *pdata = (adf_pdata *)backend;
-    adf_interface_blank(pdata->intf_fd,
-            blank ? DRM_MODE_DPMS_OFF : DRM_MODE_DPMS_ON);
-}
-
-static void adf_surface_destroy(adf_surface_pdata *surf)
-{
-    munmap(surf->base.data, surf->pitch * surf->base.height);
     close(surf->fence_fd);
-    close(surf->fd);
+    surf->fence_fd = -1;
+  }
 }
 
-static void adf_exit(minui_backend *backend)
-{
-    adf_pdata *pdata = (adf_pdata *)backend;
-    unsigned int i;
+GRSurface* MinuiBackendAdf::Flip() {
+  GRSurfaceAdf* surf = &surfaces[current_surface];
 
-    adf_device_close(&pdata->dev);
-    for (i = 0; i < pdata->n_surfaces; i++)
-        adf_surface_destroy(&pdata->surfaces[i]);
-    if (pdata->intf_fd >= 0)
-        close(pdata->intf_fd);
-    free(pdata);
+  int fence_fd = adf_interface_simple_post(intf_fd, eng_id, surf->width, surf->height, format,
+                                           surf->fd, surf->offset, surf->pitch, -1);
+  if (fence_fd >= 0) surf->fence_fd = fence_fd;
+
+  current_surface = (current_surface + 1) % n_surfaces;
+  Sync(&surfaces[current_surface]);
+  return &surfaces[current_surface];
 }
 
-minui_backend *open_adf()
-{
-    adf_pdata* pdata = static_cast<adf_pdata*>(calloc(1, sizeof(*pdata)));
-    if (!pdata) {
-        perror("allocating adf backend failed");
-        return NULL;
-    }
+void MinuiBackendAdf::Blank(bool blank) {
+  adf_interface_blank(intf_fd, blank ? DRM_MODE_DPMS_OFF : DRM_MODE_DPMS_ON);
+}
 
-    pdata->base.init = adf_init;
-    pdata->base.flip = adf_flip;
-    pdata->base.blank = adf_blank;
-    pdata->base.exit = adf_exit;
-    return &pdata->base;
+void MinuiBackendAdf::SurfaceDestroy(GRSurfaceAdf* surf) {
+  munmap(surf->data, surf->pitch * surf->height);
+  close(surf->fence_fd);
+  close(surf->fd);
+}
+
+MinuiBackendAdf::~MinuiBackendAdf() {
+  adf_device_close(&dev);
+  for (unsigned int i = 0; i < n_surfaces; i++) {
+    SurfaceDestroy(&surfaces[i]);
+  }
+  if (intf_fd >= 0) close(intf_fd);
 }
diff --git a/minui/graphics_adf.h b/minui/graphics_adf.h
new file mode 100644
index 0000000..2f019ed
--- /dev/null
+++ b/minui/graphics_adf.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _GRAPHICS_ADF_H_
+#define _GRAPHICS_ADF_H_
+
+#include <adf/adf.h>
+
+#include "graphics.h"
+
+class GRSurfaceAdf : public GRSurface {
+ private:
+  int fence_fd;
+  int fd;
+  __u32 offset;
+  __u32 pitch;
+
+  friend class MinuiBackendAdf;
+};
+
+class MinuiBackendAdf : public MinuiBackend {
+ public:
+  GRSurface* Init() override;
+  GRSurface* Flip() override;
+  void Blank(bool) override;
+  ~MinuiBackendAdf() override;
+  MinuiBackendAdf();
+
+ private:
+  int SurfaceInit(const drm_mode_modeinfo* mode, GRSurfaceAdf* surf);
+  int InterfaceInit();
+  int DeviceInit(adf_device* dev);
+  void SurfaceDestroy(GRSurfaceAdf* surf);
+  void Sync(GRSurfaceAdf* surf);
+
+  int intf_fd;
+  adf_id_t eng_id;
+  __u32 format;
+  adf_device dev;
+  unsigned int current_surface;
+  unsigned int n_surfaces;
+  GRSurfaceAdf surfaces[2];
+};
+
+#endif  // _GRAPHICS_ADF_H_
diff --git a/minui/graphics_drm.cpp b/minui/graphics_drm.cpp
index 199f4d8..e7d4b38 100644
--- a/minui/graphics_drm.cpp
+++ b/minui/graphics_drm.cpp
@@ -14,462 +14,382 @@
  * limitations under the License.
  */
 
-#include <drm_fourcc.h>
+#include "graphics_drm.h"
+
 #include <fcntl.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <string.h>
-#include <sys/cdefs.h>
-#include <sys/ioctl.h>
 #include <sys/mman.h>
 #include <sys/types.h>
 #include <unistd.h>
+
+#include <drm_fourcc.h>
 #include <xf86drm.h>
 #include <xf86drmMode.h>
 
 #include "minui/minui.h"
-#include "graphics.h"
 
 #define ARRAY_SIZE(A) (sizeof(A)/sizeof(*(A)))
 
-struct drm_surface {
-    GRSurface base;
-    uint32_t fb_id;
-    uint32_t handle;
-};
+MinuiBackendDrm::MinuiBackendDrm()
+    : GRSurfaceDrms(), main_monitor_crtc(nullptr), main_monitor_connector(nullptr), drm_fd(-1) {}
 
-static drm_surface *drm_surfaces[2];
-static int current_buffer;
-
-static drmModeCrtc *main_monitor_crtc;
-static drmModeConnector *main_monitor_connector;
-
-static int drm_fd = -1;
-
-static void drm_disable_crtc(int drm_fd, drmModeCrtc *crtc) {
-    if (crtc) {
-        drmModeSetCrtc(drm_fd, crtc->crtc_id,
-                       0, // fb_id
-                       0, 0,  // x,y
-                       NULL,  // connectors
-                       0,     // connector_count
-                       NULL); // mode
-    }
+void MinuiBackendDrm::DrmDisableCrtc(int drm_fd, drmModeCrtc* crtc) {
+  if (crtc) {
+    drmModeSetCrtc(drm_fd, crtc->crtc_id,
+                   0,         // fb_id
+                   0, 0,      // x,y
+                   nullptr,   // connectors
+                   0,         // connector_count
+                   nullptr);  // mode
+  }
 }
 
-static void drm_enable_crtc(int drm_fd, drmModeCrtc *crtc,
-                            struct drm_surface *surface) {
-    int32_t ret;
+void MinuiBackendDrm::DrmEnableCrtc(int drm_fd, drmModeCrtc* crtc, GRSurfaceDrm* surface) {
+  int32_t ret = drmModeSetCrtc(drm_fd, crtc->crtc_id, surface->fb_id, 0, 0,  // x,y
+                               &main_monitor_connector->connector_id,
+                               1,  // connector_count
+                               &main_monitor_crtc->mode);
 
-    ret = drmModeSetCrtc(drm_fd, crtc->crtc_id,
-                         surface->fb_id,
-                         0, 0,  // x,y
-                         &main_monitor_connector->connector_id,
-                         1,  // connector_count
-                         &main_monitor_crtc->mode);
-
-    if (ret)
-        printf("drmModeSetCrtc failed ret=%d\n", ret);
+  if (ret) {
+    printf("drmModeSetCrtc failed ret=%d\n", ret);
+  }
 }
 
-static void drm_blank(minui_backend* backend __unused, bool blank) {
-    if (blank)
-        drm_disable_crtc(drm_fd, main_monitor_crtc);
-    else
-        drm_enable_crtc(drm_fd, main_monitor_crtc,
-                        drm_surfaces[current_buffer]);
+void MinuiBackendDrm::Blank(bool blank) {
+  if (blank) {
+    DrmDisableCrtc(drm_fd, main_monitor_crtc);
+  } else {
+    DrmEnableCrtc(drm_fd, main_monitor_crtc, GRSurfaceDrms[current_buffer]);
+  }
 }
 
-static void drm_destroy_surface(struct drm_surface *surface) {
-    struct drm_gem_close gem_close;
-    int ret;
+void MinuiBackendDrm::DrmDestroySurface(GRSurfaceDrm* surface) {
+  if (!surface) return;
 
-    if(!surface)
-        return;
+  if (surface->data) {
+    munmap(surface->data, surface->row_bytes * surface->height);
+  }
 
-    if (surface->base.data)
-        munmap(surface->base.data,
-               surface->base.row_bytes * surface->base.height);
-
-    if (surface->fb_id) {
-        ret = drmModeRmFB(drm_fd, surface->fb_id);
-        if (ret)
-            printf("drmModeRmFB failed ret=%d\n", ret);
+  if (surface->fb_id) {
+    int ret = drmModeRmFB(drm_fd, surface->fb_id);
+    if (ret) {
+      printf("drmModeRmFB failed ret=%d\n", ret);
     }
+  }
 
-    if (surface->handle) {
-        memset(&gem_close, 0, sizeof(gem_close));
-        gem_close.handle = surface->handle;
+  if (surface->handle) {
+    drm_gem_close gem_close = {};
+    gem_close.handle = surface->handle;
 
-        ret = drmIoctl(drm_fd, DRM_IOCTL_GEM_CLOSE, &gem_close);
-        if (ret)
-            printf("DRM_IOCTL_GEM_CLOSE failed ret=%d\n", ret);
+    int ret = drmIoctl(drm_fd, DRM_IOCTL_GEM_CLOSE, &gem_close);
+    if (ret) {
+      printf("DRM_IOCTL_GEM_CLOSE failed ret=%d\n", ret);
     }
+  }
 
-    free(surface);
+  delete surface;
 }
 
 static int drm_format_to_bpp(uint32_t format) {
-    switch(format) {
-        case DRM_FORMAT_ABGR8888:
-        case DRM_FORMAT_BGRA8888:
-        case DRM_FORMAT_RGBX8888:
-        case DRM_FORMAT_BGRX8888:
-        case DRM_FORMAT_XBGR8888:
-        case DRM_FORMAT_XRGB8888:
-            return 32;
-        case DRM_FORMAT_RGB565:
-            return 16;
-        default:
-            printf("Unknown format %d\n", format);
-            return 32;
-    }
+  switch (format) {
+    case DRM_FORMAT_ABGR8888:
+    case DRM_FORMAT_BGRA8888:
+    case DRM_FORMAT_RGBX8888:
+    case DRM_FORMAT_BGRX8888:
+    case DRM_FORMAT_XBGR8888:
+    case DRM_FORMAT_XRGB8888:
+      return 32;
+    case DRM_FORMAT_RGB565:
+      return 16;
+    default:
+      printf("Unknown format %d\n", format);
+      return 32;
+  }
 }
 
-static drm_surface *drm_create_surface(int width, int height) {
-    struct drm_surface *surface;
-    struct drm_mode_create_dumb create_dumb;
-    uint32_t format;
-    int ret;
+GRSurfaceDrm* MinuiBackendDrm::DrmCreateSurface(int width, int height) {
+  GRSurfaceDrm* surface = new GRSurfaceDrm;
+  *surface = {};
 
-    surface = (struct drm_surface*)calloc(1, sizeof(*surface));
-    if (!surface) {
-        printf("Can't allocate memory\n");
-        return NULL;
-    }
-
+  uint32_t format;
 #if defined(RECOVERY_ABGR)
-    format = DRM_FORMAT_RGBA8888;
+  format = DRM_FORMAT_RGBA8888;
 #elif defined(RECOVERY_BGRA)
-    format = DRM_FORMAT_ARGB8888;
+  format = DRM_FORMAT_ARGB8888;
 #elif defined(RECOVERY_RGBX)
-    format = DRM_FORMAT_XBGR8888;
+  format = DRM_FORMAT_XBGR8888;
 #else
-    format = DRM_FORMAT_RGB565;
+  format = DRM_FORMAT_RGB565;
 #endif
 
-    memset(&create_dumb, 0, sizeof(create_dumb));
-    create_dumb.height = height;
-    create_dumb.width = width;
-    create_dumb.bpp = drm_format_to_bpp(format);
-    create_dumb.flags = 0;
+  drm_mode_create_dumb create_dumb = {};
+  create_dumb.height = height;
+  create_dumb.width = width;
+  create_dumb.bpp = drm_format_to_bpp(format);
+  create_dumb.flags = 0;
 
-    ret = drmIoctl(drm_fd, DRM_IOCTL_MODE_CREATE_DUMB, &create_dumb);
-    if (ret) {
-        printf("DRM_IOCTL_MODE_CREATE_DUMB failed ret=%d\n",ret);
-        drm_destroy_surface(surface);
-        return NULL;
-    }
-    surface->handle = create_dumb.handle;
+  int ret = drmIoctl(drm_fd, DRM_IOCTL_MODE_CREATE_DUMB, &create_dumb);
+  if (ret) {
+    printf("DRM_IOCTL_MODE_CREATE_DUMB failed ret=%d\n", ret);
+    DrmDestroySurface(surface);
+    return nullptr;
+  }
+  surface->handle = create_dumb.handle;
 
-    uint32_t handles[4], pitches[4], offsets[4];
+  uint32_t handles[4], pitches[4], offsets[4];
 
-    handles[0] = surface->handle;
-    pitches[0] = create_dumb.pitch;
-    offsets[0] = 0;
+  handles[0] = surface->handle;
+  pitches[0] = create_dumb.pitch;
+  offsets[0] = 0;
 
-    ret = drmModeAddFB2(drm_fd, width, height,
-            format, handles, pitches, offsets,
-            &(surface->fb_id), 0);
-    if (ret) {
-        printf("drmModeAddFB2 failed ret=%d\n", ret);
-        drm_destroy_surface(surface);
-        return NULL;
-    }
+  ret =
+      drmModeAddFB2(drm_fd, width, height, format, handles, pitches, offsets, &(surface->fb_id), 0);
+  if (ret) {
+    printf("drmModeAddFB2 failed ret=%d\n", ret);
+    DrmDestroySurface(surface);
+    return nullptr;
+  }
 
-    struct drm_mode_map_dumb map_dumb;
-    memset(&map_dumb, 0, sizeof(map_dumb));
-    map_dumb.handle = create_dumb.handle;
-    ret = drmIoctl(drm_fd, DRM_IOCTL_MODE_MAP_DUMB, &map_dumb);
-    if (ret) {
-        printf("DRM_IOCTL_MODE_MAP_DUMB failed ret=%d\n",ret);
-        drm_destroy_surface(surface);
-        return NULL;;
-    }
+  drm_mode_map_dumb map_dumb = {};
+  map_dumb.handle = create_dumb.handle;
+  ret = drmIoctl(drm_fd, DRM_IOCTL_MODE_MAP_DUMB, &map_dumb);
+  if (ret) {
+    printf("DRM_IOCTL_MODE_MAP_DUMB failed ret=%d\n", ret);
+    DrmDestroySurface(surface);
+    return nullptr;
+  }
 
-    surface->base.height = height;
-    surface->base.width = width;
-    surface->base.row_bytes = create_dumb.pitch;
-    surface->base.pixel_bytes = create_dumb.bpp / 8;
-    surface->base.data = (unsigned char*)
-                         mmap(NULL,
-                              surface->base.height * surface->base.row_bytes,
-                              PROT_READ | PROT_WRITE, MAP_SHARED,
-                              drm_fd, map_dumb.offset);
-    if (surface->base.data == MAP_FAILED) {
-        perror("mmap() failed");
-        drm_destroy_surface(surface);
-        return NULL;
-    }
+  surface->height = height;
+  surface->width = width;
+  surface->row_bytes = create_dumb.pitch;
+  surface->pixel_bytes = create_dumb.bpp / 8;
+  surface->data = static_cast<unsigned char*>(mmap(nullptr, surface->height * surface->row_bytes,
+                                                   PROT_READ | PROT_WRITE, MAP_SHARED, drm_fd,
+                                                   map_dumb.offset));
+  if (surface->data == MAP_FAILED) {
+    perror("mmap() failed");
+    DrmDestroySurface(surface);
+    return nullptr;
+  }
 
-    return surface;
+  return surface;
 }
 
-static drmModeCrtc *find_crtc_for_connector(int fd,
-                            drmModeRes *resources,
-                            drmModeConnector *connector) {
-    int i, j;
-    drmModeEncoder *encoder;
-    int32_t crtc;
+static drmModeCrtc* find_crtc_for_connector(int fd, drmModeRes* resources,
+                                            drmModeConnector* connector) {
+  // Find the encoder. If we already have one, just use it.
+  drmModeEncoder* encoder;
+  if (connector->encoder_id) {
+    encoder = drmModeGetEncoder(fd, connector->encoder_id);
+  } else {
+    encoder = nullptr;
+  }
 
-    /*
-     * Find the encoder. If we already have one, just use it.
-     */
-    if (connector->encoder_id)
-        encoder = drmModeGetEncoder(fd, connector->encoder_id);
-    else
-        encoder = NULL;
+  int32_t crtc;
+  if (encoder && encoder->crtc_id) {
+    crtc = encoder->crtc_id;
+    drmModeFreeEncoder(encoder);
+    return drmModeGetCrtc(fd, crtc);
+  }
 
-    if (encoder && encoder->crtc_id) {
-        crtc = encoder->crtc_id;
+  // Didn't find anything, try to find a crtc and encoder combo.
+  crtc = -1;
+  for (int i = 0; i < connector->count_encoders; i++) {
+    encoder = drmModeGetEncoder(fd, connector->encoders[i]);
+
+    if (encoder) {
+      for (int j = 0; j < resources->count_crtcs; j++) {
+        if (!(encoder->possible_crtcs & (1 << j))) continue;
+        crtc = resources->crtcs[j];
+        break;
+      }
+      if (crtc >= 0) {
         drmModeFreeEncoder(encoder);
         return drmModeGetCrtc(fd, crtc);
+      }
     }
+  }
 
-    /*
-     * Didn't find anything, try to find a crtc and encoder combo.
-     */
-    crtc = -1;
-    for (i = 0; i < connector->count_encoders; i++) {
-        encoder = drmModeGetEncoder(fd, connector->encoders[i]);
-
-        if (encoder) {
-            for (j = 0; j < resources->count_crtcs; j++) {
-                if (!(encoder->possible_crtcs & (1 << j)))
-                    continue;
-                crtc = resources->crtcs[j];
-                break;
-            }
-            if (crtc >= 0) {
-                drmModeFreeEncoder(encoder);
-                return drmModeGetCrtc(fd, crtc);
-            }
-        }
-    }
-
-    return NULL;
+  return nullptr;
 }
 
-static drmModeConnector *find_used_connector_by_type(int fd,
-                                 drmModeRes *resources,
-                                 unsigned type) {
-    int i;
-    for (i = 0; i < resources->count_connectors; i++) {
-        drmModeConnector *connector;
-
-        connector = drmModeGetConnector(fd, resources->connectors[i]);
-        if (connector) {
-            if ((connector->connector_type == type) &&
-                    (connector->connection == DRM_MODE_CONNECTED) &&
-                    (connector->count_modes > 0))
-                return connector;
-
-            drmModeFreeConnector(connector);
-        }
+static drmModeConnector* find_used_connector_by_type(int fd, drmModeRes* resources, unsigned type) {
+  for (int i = 0; i < resources->count_connectors; i++) {
+    drmModeConnector* connector = drmModeGetConnector(fd, resources->connectors[i]);
+    if (connector) {
+      if ((connector->connector_type == type) && (connector->connection == DRM_MODE_CONNECTED) &&
+          (connector->count_modes > 0)) {
+        return connector;
+      }
+      drmModeFreeConnector(connector);
     }
-    return NULL;
+  }
+  return nullptr;
 }
 
-static drmModeConnector *find_first_connected_connector(int fd,
-                             drmModeRes *resources) {
-    int i;
-    for (i = 0; i < resources->count_connectors; i++) {
-        drmModeConnector *connector;
+static drmModeConnector* find_first_connected_connector(int fd, drmModeRes* resources) {
+  for (int i = 0; i < resources->count_connectors; i++) {
+    drmModeConnector* connector;
 
-        connector = drmModeGetConnector(fd, resources->connectors[i]);
-        if (connector) {
-            if ((connector->count_modes > 0) &&
-                    (connector->connection == DRM_MODE_CONNECTED))
-                return connector;
+    connector = drmModeGetConnector(fd, resources->connectors[i]);
+    if (connector) {
+      if ((connector->count_modes > 0) && (connector->connection == DRM_MODE_CONNECTED))
+        return connector;
 
-            drmModeFreeConnector(connector);
-        }
+      drmModeFreeConnector(connector);
     }
-    return NULL;
+  }
+  return nullptr;
 }
 
-static drmModeConnector *find_main_monitor(int fd, drmModeRes *resources,
-        uint32_t *mode_index) {
-    unsigned i = 0;
-    int modes;
-    /* Look for LVDS/eDP/DSI connectors. Those are the main screens. */
-    unsigned kConnectorPriority[] = {
-        DRM_MODE_CONNECTOR_LVDS,
-        DRM_MODE_CONNECTOR_eDP,
-        DRM_MODE_CONNECTOR_DSI,
-    };
+drmModeConnector* MinuiBackendDrm::FindMainMonitor(int fd, drmModeRes* resources,
+                                                   uint32_t* mode_index) {
+  /* Look for LVDS/eDP/DSI connectors. Those are the main screens. */
+  static constexpr unsigned kConnectorPriority[] = {
+    DRM_MODE_CONNECTOR_LVDS,
+    DRM_MODE_CONNECTOR_eDP,
+    DRM_MODE_CONNECTOR_DSI,
+  };
 
-    drmModeConnector *main_monitor_connector = NULL;
-    do {
-        main_monitor_connector = find_used_connector_by_type(fd,
-                                         resources,
-                                         kConnectorPriority[i]);
-        i++;
-    } while (!main_monitor_connector && i < ARRAY_SIZE(kConnectorPriority));
+  drmModeConnector* main_monitor_connector = nullptr;
+  unsigned i = 0;
+  do {
+    main_monitor_connector = find_used_connector_by_type(fd, resources, kConnectorPriority[i]);
+    i++;
+  } while (!main_monitor_connector && i < ARRAY_SIZE(kConnectorPriority));
 
-    /* If we didn't find a connector, grab the first one that is connected. */
-    if (!main_monitor_connector)
-        main_monitor_connector =
-                find_first_connected_connector(fd, resources);
+  /* If we didn't find a connector, grab the first one that is connected. */
+  if (!main_monitor_connector) {
+    main_monitor_connector = find_first_connected_connector(fd, resources);
+  }
 
-    /* If we still didn't find a connector, give up and return. */
-    if (!main_monitor_connector)
-        return NULL;
+  /* If we still didn't find a connector, give up and return. */
+  if (!main_monitor_connector) return nullptr;
 
-    *mode_index = 0;
-    for (modes = 0; modes < main_monitor_connector->count_modes; modes++) {
-        if (main_monitor_connector->modes[modes].type &
-                DRM_MODE_TYPE_PREFERRED) {
-            *mode_index = modes;
-            break;
-        }
+  *mode_index = 0;
+  for (int modes = 0; modes < main_monitor_connector->count_modes; modes++) {
+    if (main_monitor_connector->modes[modes].type & DRM_MODE_TYPE_PREFERRED) {
+      *mode_index = modes;
+      break;
     }
+  }
 
-    return main_monitor_connector;
+  return main_monitor_connector;
 }
 
-static void disable_non_main_crtcs(int fd,
-                    drmModeRes *resources,
-                    drmModeCrtc* main_crtc) {
-    int i;
-    drmModeCrtc* crtc;
-
-    for (i = 0; i < resources->count_connectors; i++) {
-        drmModeConnector *connector;
-
-        connector = drmModeGetConnector(fd, resources->connectors[i]);
-        crtc = find_crtc_for_connector(fd, resources, connector);
-        if (crtc->crtc_id != main_crtc->crtc_id)
-            drm_disable_crtc(fd, crtc);
-        drmModeFreeCrtc(crtc);
+void MinuiBackendDrm::DisableNonMainCrtcs(int fd, drmModeRes* resources, drmModeCrtc* main_crtc) {
+  for (int i = 0; i < resources->count_connectors; i++) {
+    drmModeConnector* connector = drmModeGetConnector(fd, resources->connectors[i]);
+    drmModeCrtc* crtc = find_crtc_for_connector(fd, resources, connector);
+    if (crtc->crtc_id != main_crtc->crtc_id) {
+      DrmDisableCrtc(fd, crtc);
     }
+    drmModeFreeCrtc(crtc);
+  }
 }
 
-static GRSurface* drm_init(minui_backend* backend __unused) {
-    drmModeRes *res = NULL;
-    uint32_t selected_mode;
-    char *dev_name;
-    int width, height;
-    int ret, i;
+GRSurface* MinuiBackendDrm::Init() {
+  drmModeRes* res = nullptr;
 
-    /* Consider DRM devices in order. */
-    for (i = 0; i < DRM_MAX_MINOR; i++) {
-        uint64_t cap = 0;
+  /* Consider DRM devices in order. */
+  for (int i = 0; i < DRM_MAX_MINOR; i++) {
+    char* dev_name;
+    int ret = asprintf(&dev_name, DRM_DEV_NAME, DRM_DIR_NAME, i);
+    if (ret < 0) continue;
 
-        ret = asprintf(&dev_name, DRM_DEV_NAME, DRM_DIR_NAME, i);
-        if (ret < 0)
-            continue;
+    drm_fd = open(dev_name, O_RDWR, 0);
+    free(dev_name);
+    if (drm_fd < 0) continue;
 
-        drm_fd = open(dev_name, O_RDWR, 0);
-        free(dev_name);
-        if (drm_fd < 0)
-            continue;
-
-        /* We need dumb buffers. */
-        ret = drmGetCap(drm_fd, DRM_CAP_DUMB_BUFFER, &cap);
-        if (ret || cap == 0) {
-            close(drm_fd);
-            continue;
-        }
-
-        res = drmModeGetResources(drm_fd);
-        if (!res) {
-            close(drm_fd);
-            continue;
-        }
-
-        /* Use this device if it has at least one connected monitor. */
-        if (res->count_crtcs > 0 && res->count_connectors > 0)
-            if (find_first_connected_connector(drm_fd, res))
-                break;
-
-        drmModeFreeResources(res);
-        close(drm_fd);
-        res = NULL;
+    uint64_t cap = 0;
+    /* We need dumb buffers. */
+    ret = drmGetCap(drm_fd, DRM_CAP_DUMB_BUFFER, &cap);
+    if (ret || cap == 0) {
+      close(drm_fd);
+      continue;
     }
 
-    if (drm_fd < 0 || res == NULL) {
-        perror("cannot find/open a drm device");
-        return NULL;
+    res = drmModeGetResources(drm_fd);
+    if (!res) {
+      close(drm_fd);
+      continue;
     }
 
-    main_monitor_connector = find_main_monitor(drm_fd,
-            res, &selected_mode);
-
-    if (!main_monitor_connector) {
-        printf("main_monitor_connector not found\n");
-        drmModeFreeResources(res);
-        close(drm_fd);
-        return NULL;
+    /* Use this device if it has at least one connected monitor. */
+    if (res->count_crtcs > 0 && res->count_connectors > 0) {
+      if (find_first_connected_connector(drm_fd, res)) break;
     }
 
-    main_monitor_crtc = find_crtc_for_connector(drm_fd, res,
-                                                main_monitor_connector);
-
-    if (!main_monitor_crtc) {
-        printf("main_monitor_crtc not found\n");
-        drmModeFreeResources(res);
-        close(drm_fd);
-        return NULL;
-    }
-
-    disable_non_main_crtcs(drm_fd,
-                           res, main_monitor_crtc);
-
-    main_monitor_crtc->mode = main_monitor_connector->modes[selected_mode];
-
-    width = main_monitor_crtc->mode.hdisplay;
-    height = main_monitor_crtc->mode.vdisplay;
-
     drmModeFreeResources(res);
-
-    drm_surfaces[0] = drm_create_surface(width, height);
-    drm_surfaces[1] = drm_create_surface(width, height);
-    if (!drm_surfaces[0] || !drm_surfaces[1]) {
-        drm_destroy_surface(drm_surfaces[0]);
-        drm_destroy_surface(drm_surfaces[1]);
-        drmModeFreeResources(res);
-        close(drm_fd);
-        return NULL;
-    }
-
-    current_buffer = 0;
-
-    drm_enable_crtc(drm_fd, main_monitor_crtc, drm_surfaces[1]);
-
-    return &(drm_surfaces[0]->base);
-}
-
-static GRSurface* drm_flip(minui_backend* backend __unused) {
-    int ret;
-
-    ret = drmModePageFlip(drm_fd, main_monitor_crtc->crtc_id,
-                          drm_surfaces[current_buffer]->fb_id, 0, NULL);
-    if (ret < 0) {
-        printf("drmModePageFlip failed ret=%d\n", ret);
-        return NULL;
-    }
-    current_buffer = 1 - current_buffer;
-    return &(drm_surfaces[current_buffer]->base);
-}
-
-static void drm_exit(minui_backend* backend __unused) {
-    drm_disable_crtc(drm_fd, main_monitor_crtc);
-    drm_destroy_surface(drm_surfaces[0]);
-    drm_destroy_surface(drm_surfaces[1]);
-    drmModeFreeCrtc(main_monitor_crtc);
-    drmModeFreeConnector(main_monitor_connector);
     close(drm_fd);
-    drm_fd = -1;
+    res = nullptr;
+  }
+
+  if (drm_fd < 0 || res == nullptr) {
+    perror("cannot find/open a drm device");
+    return nullptr;
+  }
+
+  uint32_t selected_mode;
+  main_monitor_connector = FindMainMonitor(drm_fd, res, &selected_mode);
+
+  if (!main_monitor_connector) {
+    printf("main_monitor_connector not found\n");
+    drmModeFreeResources(res);
+    close(drm_fd);
+    return nullptr;
+  }
+
+  main_monitor_crtc = find_crtc_for_connector(drm_fd, res, main_monitor_connector);
+
+  if (!main_monitor_crtc) {
+    printf("main_monitor_crtc not found\n");
+    drmModeFreeResources(res);
+    close(drm_fd);
+    return nullptr;
+  }
+
+  DisableNonMainCrtcs(drm_fd, res, main_monitor_crtc);
+
+  main_monitor_crtc->mode = main_monitor_connector->modes[selected_mode];
+
+  int width = main_monitor_crtc->mode.hdisplay;
+  int height = main_monitor_crtc->mode.vdisplay;
+
+  drmModeFreeResources(res);
+
+  GRSurfaceDrms[0] = DrmCreateSurface(width, height);
+  GRSurfaceDrms[1] = DrmCreateSurface(width, height);
+  if (!GRSurfaceDrms[0] || !GRSurfaceDrms[1]) {
+    // GRSurfaceDrms and drm_fd should be freed in d'tor.
+    return nullptr;
+  }
+
+  current_buffer = 0;
+
+  DrmEnableCrtc(drm_fd, main_monitor_crtc, GRSurfaceDrms[1]);
+
+  return GRSurfaceDrms[0];
 }
 
-static minui_backend drm_backend = {
-    .init = drm_init,
-    .flip = drm_flip,
-    .blank = drm_blank,
-    .exit = drm_exit,
-};
+GRSurface* MinuiBackendDrm::Flip() {
+  int ret = drmModePageFlip(drm_fd, main_monitor_crtc->crtc_id,
+                            GRSurfaceDrms[current_buffer]->fb_id, 0, nullptr);
+  if (ret < 0) {
+    printf("drmModePageFlip failed ret=%d\n", ret);
+    return nullptr;
+  }
+  current_buffer = 1 - current_buffer;
+  return GRSurfaceDrms[current_buffer];
+}
 
-minui_backend* open_drm() {
-    return &drm_backend;
+MinuiBackendDrm::~MinuiBackendDrm() {
+  DrmDisableCrtc(drm_fd, main_monitor_crtc);
+  DrmDestroySurface(GRSurfaceDrms[0]);
+  DrmDestroySurface(GRSurfaceDrms[1]);
+  drmModeFreeCrtc(main_monitor_crtc);
+  drmModeFreeConnector(main_monitor_connector);
+  close(drm_fd);
+  drm_fd = -1;
 }
diff --git a/minui/graphics_drm.h b/minui/graphics_drm.h
new file mode 100644
index 0000000..de96212
--- /dev/null
+++ b/minui/graphics_drm.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _GRAPHICS_DRM_H_
+#define _GRAPHICS_DRM_H_
+
+#include <stdint.h>
+
+#include <xf86drmMode.h>
+
+#include "graphics.h"
+#include "minui/minui.h"
+
+class GRSurfaceDrm : public GRSurface {
+ private:
+  uint32_t fb_id;
+  uint32_t handle;
+
+  friend class MinuiBackendDrm;
+};
+
+class MinuiBackendDrm : public MinuiBackend {
+ public:
+  GRSurface* Init() override;
+  GRSurface* Flip() override;
+  void Blank(bool) override;
+  ~MinuiBackendDrm() override;
+  MinuiBackendDrm();
+
+ private:
+  void DrmDisableCrtc(int drm_fd, drmModeCrtc* crtc);
+  void DrmEnableCrtc(int drm_fd, drmModeCrtc* crtc, GRSurfaceDrm* surface);
+  GRSurfaceDrm* DrmCreateSurface(int width, int height);
+  void DrmDestroySurface(GRSurfaceDrm* surface);
+  void DisableNonMainCrtcs(int fd, drmModeRes* resources, drmModeCrtc* main_crtc);
+  drmModeConnector* FindMainMonitor(int fd, drmModeRes* resources, uint32_t* mode_index);
+
+  GRSurfaceDrm* GRSurfaceDrms[2];
+  int current_buffer;
+  drmModeCrtc* main_monitor_crtc;
+  drmModeConnector* main_monitor_connector;
+  int drm_fd;
+};
+
+#endif  // _GRAPHICS_DRM_H_
diff --git a/minui/graphics_fbdev.cpp b/minui/graphics_fbdev.cpp
index 2d70249..746f42a 100644
--- a/minui/graphics_fbdev.cpp
+++ b/minui/graphics_fbdev.cpp
@@ -14,187 +14,154 @@
  * limitations under the License.
  */
 
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
+#include "graphics_fbdev.h"
 
 #include <fcntl.h>
+#include <linux/fb.h>
 #include <stdio.h>
-
-#include <sys/cdefs.h>
+#include <stdlib.h>
+#include <string.h>
 #include <sys/ioctl.h>
 #include <sys/mman.h>
 #include <sys/types.h>
-
-#include <linux/fb.h>
-#include <linux/kd.h>
+#include <unistd.h>
 
 #include "minui/minui.h"
-#include "graphics.h"
 
-static GRSurface* fbdev_init(minui_backend*);
-static GRSurface* fbdev_flip(minui_backend*);
-static void fbdev_blank(minui_backend*, bool);
-static void fbdev_exit(minui_backend*);
+MinuiBackendFbdev::MinuiBackendFbdev() : gr_draw(nullptr), fb_fd(-1) {}
 
-static GRSurface gr_framebuffer[2];
-static bool double_buffered;
-static GRSurface* gr_draw = NULL;
-static int displayed_buffer;
-
-static fb_var_screeninfo vi;
-static int fb_fd = -1;
-
-static minui_backend my_backend = {
-    .init = fbdev_init,
-    .flip = fbdev_flip,
-    .blank = fbdev_blank,
-    .exit = fbdev_exit,
-};
-
-minui_backend* open_fbdev() {
-    return &my_backend;
+void MinuiBackendFbdev::Blank(bool blank) {
+  int ret = ioctl(fb_fd, FBIOBLANK, blank ? FB_BLANK_POWERDOWN : FB_BLANK_UNBLANK);
+  if (ret < 0) perror("ioctl(): blank");
 }
 
-static void fbdev_blank(minui_backend* backend __unused, bool blank)
-{
-    int ret;
+void MinuiBackendFbdev::SetDisplayedFramebuffer(unsigned n) {
+  if (n > 1 || !double_buffered) return;
 
-    ret = ioctl(fb_fd, FBIOBLANK, blank ? FB_BLANK_POWERDOWN : FB_BLANK_UNBLANK);
-    if (ret < 0)
-        perror("ioctl(): blank");
+  vi.yres_virtual = gr_framebuffer[0].height * 2;
+  vi.yoffset = n * gr_framebuffer[0].height;
+  vi.bits_per_pixel = gr_framebuffer[0].pixel_bytes * 8;
+  if (ioctl(fb_fd, FBIOPUT_VSCREENINFO, &vi) < 0) {
+    perror("active fb swap failed");
+  }
+  displayed_buffer = n;
 }
 
-static void set_displayed_framebuffer(unsigned n)
-{
-    if (n > 1 || !double_buffered) return;
+GRSurface* MinuiBackendFbdev::Init() {
+  int fd = open("/dev/graphics/fb0", O_RDWR);
+  if (fd == -1) {
+    perror("cannot open fb0");
+    return nullptr;
+  }
 
-    vi.yres_virtual = gr_framebuffer[0].height * 2;
-    vi.yoffset = n * gr_framebuffer[0].height;
-    vi.bits_per_pixel = gr_framebuffer[0].pixel_bytes * 8;
-    if (ioctl(fb_fd, FBIOPUT_VSCREENINFO, &vi) < 0) {
-        perror("active fb swap failed");
+  fb_fix_screeninfo fi;
+  if (ioctl(fd, FBIOGET_FSCREENINFO, &fi) < 0) {
+    perror("failed to get fb0 info");
+    close(fd);
+    return nullptr;
+  }
+
+  if (ioctl(fd, FBIOGET_VSCREENINFO, &vi) < 0) {
+    perror("failed to get fb0 info");
+    close(fd);
+    return nullptr;
+  }
+
+  // We print this out for informational purposes only, but
+  // throughout we assume that the framebuffer device uses an RGBX
+  // pixel format.  This is the case for every development device I
+  // have access to.  For some of those devices (eg, hammerhead aka
+  // Nexus 5), FBIOGET_VSCREENINFO *reports* that it wants a
+  // different format (XBGR) but actually produces the correct
+  // results on the display when you write RGBX.
+  //
+  // If you have a device that actually *needs* another pixel format
+  // (ie, BGRX, or 565), patches welcome...
+
+  printf(
+      "fb0 reports (possibly inaccurate):\n"
+      "  vi.bits_per_pixel = %d\n"
+      "  vi.red.offset   = %3d   .length = %3d\n"
+      "  vi.green.offset = %3d   .length = %3d\n"
+      "  vi.blue.offset  = %3d   .length = %3d\n",
+      vi.bits_per_pixel, vi.red.offset, vi.red.length, vi.green.offset, vi.green.length,
+      vi.blue.offset, vi.blue.length);
+
+  void* bits = mmap(0, fi.smem_len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
+  if (bits == MAP_FAILED) {
+    perror("failed to mmap framebuffer");
+    close(fd);
+    return nullptr;
+  }
+
+  memset(bits, 0, fi.smem_len);
+
+  gr_framebuffer[0].width = vi.xres;
+  gr_framebuffer[0].height = vi.yres;
+  gr_framebuffer[0].row_bytes = fi.line_length;
+  gr_framebuffer[0].pixel_bytes = vi.bits_per_pixel / 8;
+  gr_framebuffer[0].data = static_cast<uint8_t*>(bits);
+  memset(gr_framebuffer[0].data, 0, gr_framebuffer[0].height * gr_framebuffer[0].row_bytes);
+
+  /* check if we can use double buffering */
+  if (vi.yres * fi.line_length * 2 <= fi.smem_len) {
+    double_buffered = true;
+
+    memcpy(gr_framebuffer + 1, gr_framebuffer, sizeof(GRSurface));
+    gr_framebuffer[1].data =
+        gr_framebuffer[0].data + gr_framebuffer[0].height * gr_framebuffer[0].row_bytes;
+
+    gr_draw = gr_framebuffer + 1;
+
+  } else {
+    double_buffered = false;
+
+    // Without double-buffering, we allocate RAM for a buffer to
+    // draw in, and then "flipping" the buffer consists of a
+    // memcpy from the buffer we allocated to the framebuffer.
+
+    gr_draw = static_cast<GRSurface*>(malloc(sizeof(GRSurface)));
+    memcpy(gr_draw, gr_framebuffer, sizeof(GRSurface));
+    gr_draw->data = static_cast<unsigned char*>(malloc(gr_draw->height * gr_draw->row_bytes));
+    if (!gr_draw->data) {
+      perror("failed to allocate in-memory surface");
+      return nullptr;
     }
-    displayed_buffer = n;
+  }
+
+  memset(gr_draw->data, 0, gr_draw->height * gr_draw->row_bytes);
+  fb_fd = fd;
+  SetDisplayedFramebuffer(0);
+
+  printf("framebuffer: %d (%d x %d)\n", fb_fd, gr_draw->width, gr_draw->height);
+
+  Blank(true);
+  Blank(false);
+
+  return gr_draw;
 }
 
-static GRSurface* fbdev_init(minui_backend* backend) {
-    int fd = open("/dev/graphics/fb0", O_RDWR);
-    if (fd == -1) {
-        perror("cannot open fb0");
-        return NULL;
-    }
-
-    fb_fix_screeninfo fi;
-    if (ioctl(fd, FBIOGET_FSCREENINFO, &fi) < 0) {
-        perror("failed to get fb0 info");
-        close(fd);
-        return NULL;
-    }
-
-    if (ioctl(fd, FBIOGET_VSCREENINFO, &vi) < 0) {
-        perror("failed to get fb0 info");
-        close(fd);
-        return NULL;
-    }
-
-    // We print this out for informational purposes only, but
-    // throughout we assume that the framebuffer device uses an RGBX
-    // pixel format.  This is the case for every development device I
-    // have access to.  For some of those devices (eg, hammerhead aka
-    // Nexus 5), FBIOGET_VSCREENINFO *reports* that it wants a
-    // different format (XBGR) but actually produces the correct
-    // results on the display when you write RGBX.
-    //
-    // If you have a device that actually *needs* another pixel format
-    // (ie, BGRX, or 565), patches welcome...
-
-    printf("fb0 reports (possibly inaccurate):\n"
-           "  vi.bits_per_pixel = %d\n"
-           "  vi.red.offset   = %3d   .length = %3d\n"
-           "  vi.green.offset = %3d   .length = %3d\n"
-           "  vi.blue.offset  = %3d   .length = %3d\n",
-           vi.bits_per_pixel,
-           vi.red.offset, vi.red.length,
-           vi.green.offset, vi.green.length,
-           vi.blue.offset, vi.blue.length);
-
-    void* bits = mmap(0, fi.smem_len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
-    if (bits == MAP_FAILED) {
-        perror("failed to mmap framebuffer");
-        close(fd);
-        return NULL;
-    }
-
-    memset(bits, 0, fi.smem_len);
-
-    gr_framebuffer[0].width = vi.xres;
-    gr_framebuffer[0].height = vi.yres;
-    gr_framebuffer[0].row_bytes = fi.line_length;
-    gr_framebuffer[0].pixel_bytes = vi.bits_per_pixel / 8;
-    gr_framebuffer[0].data = static_cast<uint8_t*>(bits);
-    memset(gr_framebuffer[0].data, 0, gr_framebuffer[0].height * gr_framebuffer[0].row_bytes);
-
-    /* check if we can use double buffering */
-    if (vi.yres * fi.line_length * 2 <= fi.smem_len) {
-        double_buffered = true;
-
-        memcpy(gr_framebuffer+1, gr_framebuffer, sizeof(GRSurface));
-        gr_framebuffer[1].data = gr_framebuffer[0].data +
-            gr_framebuffer[0].height * gr_framebuffer[0].row_bytes;
-
-        gr_draw = gr_framebuffer+1;
-
-    } else {
-        double_buffered = false;
-
-        // Without double-buffering, we allocate RAM for a buffer to
-        // draw in, and then "flipping" the buffer consists of a
-        // memcpy from the buffer we allocated to the framebuffer.
-
-        gr_draw = (GRSurface*) malloc(sizeof(GRSurface));
-        memcpy(gr_draw, gr_framebuffer, sizeof(GRSurface));
-        gr_draw->data = (unsigned char*) malloc(gr_draw->height * gr_draw->row_bytes);
-        if (!gr_draw->data) {
-            perror("failed to allocate in-memory surface");
-            return NULL;
-        }
-    }
-
-    memset(gr_draw->data, 0, gr_draw->height * gr_draw->row_bytes);
-    fb_fd = fd;
-    set_displayed_framebuffer(0);
-
-    printf("framebuffer: %d (%d x %d)\n", fb_fd, gr_draw->width, gr_draw->height);
-
-    fbdev_blank(backend, true);
-    fbdev_blank(backend, false);
-
-    return gr_draw;
+GRSurface* MinuiBackendFbdev::Flip() {
+  if (double_buffered) {
+    // Change gr_draw to point to the buffer currently displayed,
+    // then flip the driver so we're displaying the other buffer
+    // instead.
+    gr_draw = gr_framebuffer + displayed_buffer;
+    SetDisplayedFramebuffer(1 - displayed_buffer);
+  } else {
+    // Copy from the in-memory surface to the framebuffer.
+    memcpy(gr_framebuffer[0].data, gr_draw->data, gr_draw->height * gr_draw->row_bytes);
+  }
+  return gr_draw;
 }
 
-static GRSurface* fbdev_flip(minui_backend* backend __unused) {
-    if (double_buffered) {
-        // Change gr_draw to point to the buffer currently displayed,
-        // then flip the driver so we're displaying the other buffer
-        // instead.
-        gr_draw = gr_framebuffer + displayed_buffer;
-        set_displayed_framebuffer(1-displayed_buffer);
-    } else {
-        // Copy from the in-memory surface to the framebuffer.
-        memcpy(gr_framebuffer[0].data, gr_draw->data,
-               gr_draw->height * gr_draw->row_bytes);
-    }
-    return gr_draw;
-}
+MinuiBackendFbdev::~MinuiBackendFbdev() {
+  close(fb_fd);
+  fb_fd = -1;
 
-static void fbdev_exit(minui_backend* backend __unused) {
-    close(fb_fd);
-    fb_fd = -1;
-
-    if (!double_buffered && gr_draw) {
-        free(gr_draw->data);
-        free(gr_draw);
-    }
-    gr_draw = NULL;
+  if (!double_buffered && gr_draw) {
+    free(gr_draw->data);
+    free(gr_draw);
+  }
+  gr_draw = nullptr;
 }
diff --git a/minui/graphics_fbdev.h b/minui/graphics_fbdev.h
new file mode 100644
index 0000000..107e195
--- /dev/null
+++ b/minui/graphics_fbdev.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _GRAPHICS_FBDEV_H_
+#define _GRAPHICS_FBDEV_H_
+
+#include <linux/fb.h>
+
+#include "graphics.h"
+#include "minui/minui.h"
+
+class MinuiBackendFbdev : public MinuiBackend {
+ public:
+  GRSurface* Init() override;
+  GRSurface* Flip() override;
+  void Blank(bool) override;
+  ~MinuiBackendFbdev() override;
+  MinuiBackendFbdev();
+
+ private:
+  void SetDisplayedFramebuffer(unsigned n);
+
+  GRSurface gr_framebuffer[2];
+  bool double_buffered;
+  GRSurface* gr_draw;
+  int displayed_buffer;
+  fb_var_screeninfo vi;
+  int fb_fd;
+};
+
+#endif  // _GRAPHICS_FBDEV_H_
diff --git a/recovery.cpp b/recovery.cpp
index 25d3546..9dfe5d1 100644
--- a/recovery.cpp
+++ b/recovery.cpp
@@ -34,7 +34,9 @@
 #include <time.h>
 #include <unistd.h>
 
+#include <algorithm>
 #include <chrono>
+#include <memory>
 #include <string>
 #include <vector>
 
@@ -243,7 +245,7 @@
         if (log_fp == nullptr) {
             PLOG(ERROR) << "fopen \"" << filename << "\" failed";
             close(pipefd[0]);
-            _exit(1);
+            _exit(EXIT_FAILURE);
         }
 
         FILE* pipe_fp = fdopen(pipefd[0], "r");
@@ -251,7 +253,7 @@
             PLOG(ERROR) << "fdopen failed";
             check_and_fclose(log_fp, filename);
             close(pipefd[0]);
-            _exit(1);
+            _exit(EXIT_FAILURE);
         }
 
         char* line = nullptr;
@@ -273,7 +275,7 @@
         free(line);
         check_and_fclose(log_fp, filename);
         close(pipefd[0]);
-        _exit(1);
+        _exit(EXIT_FAILURE);
     } else {
         // Redirect stdout/stderr to the logger process.
         // Close the unused read end.
@@ -656,108 +658,69 @@
     return chosen_item;
 }
 
-static int compare_string(const void* a, const void* b) {
-    return strcmp(*(const char**)a, *(const char**)b);
-}
+// Returns the selected filename, or an empty string.
+static std::string browse_directory(const std::string& path, Device* device) {
+  ensure_path_mounted(path.c_str());
 
-// Returns a malloc'd path, or NULL.
-static char* browse_directory(const char* path, Device* device) {
-    ensure_path_mounted(path);
+  std::unique_ptr<DIR, decltype(&closedir)> d(opendir(path.c_str()), closedir);
+  if (!d) {
+    PLOG(ERROR) << "error opening " << path;
+    return "";
+  }
 
-    DIR* d = opendir(path);
-    if (d == NULL) {
-        PLOG(ERROR) << "error opening " << path;
-        return NULL;
+  std::vector<std::string> dirs;
+  std::vector<std::string> zips = { "../" };  // "../" is always the first entry.
+
+  dirent* de;
+  while ((de = readdir(d.get())) != nullptr) {
+    std::string name(de->d_name);
+
+    if (de->d_type == DT_DIR) {
+      // Skip "." and ".." entries.
+      if (name == "." || name == "..") continue;
+      dirs.push_back(name + "/");
+    } else if (de->d_type == DT_REG && android::base::EndsWithIgnoreCase(name, ".zip")) {
+      zips.push_back(name);
+    }
+  }
+
+  std::sort(dirs.begin(), dirs.end());
+  std::sort(zips.begin(), zips.end());
+
+  // Append dirs to the zips list.
+  zips.insert(zips.end(), dirs.begin(), dirs.end());
+
+  const char* entries[zips.size() + 1];
+  entries[zips.size()] = nullptr;
+  for (size_t i = 0; i < zips.size(); i++) {
+    entries[i] = zips[i].c_str();
+  }
+
+  const char* headers[] = { "Choose a package to install:", path.c_str(), nullptr };
+
+  int chosen_item = 0;
+  while (true) {
+    chosen_item = get_menu_selection(headers, entries, 1, chosen_item, device);
+
+    const std::string& item = zips[chosen_item];
+    if (chosen_item == 0) {
+      // Go up but continue browsing (if the caller is browse_directory).
+      return "";
     }
 
-    int d_size = 0;
-    int d_alloc = 10;
-    char** dirs = (char**)malloc(d_alloc * sizeof(char*));
-    int z_size = 1;
-    int z_alloc = 10;
-    char** zips = (char**)malloc(z_alloc * sizeof(char*));
-    zips[0] = strdup("../");
-
-    struct dirent* de;
-    while ((de = readdir(d)) != NULL) {
-        int name_len = strlen(de->d_name);
-
-        if (de->d_type == DT_DIR) {
-            // skip "." and ".." entries
-            if (name_len == 1 && de->d_name[0] == '.') continue;
-            if (name_len == 2 && de->d_name[0] == '.' &&
-                de->d_name[1] == '.') continue;
-
-            if (d_size >= d_alloc) {
-                d_alloc *= 2;
-                dirs = (char**)realloc(dirs, d_alloc * sizeof(char*));
-            }
-            dirs[d_size] = (char*)malloc(name_len + 2);
-            strcpy(dirs[d_size], de->d_name);
-            dirs[d_size][name_len] = '/';
-            dirs[d_size][name_len+1] = '\0';
-            ++d_size;
-        } else if (de->d_type == DT_REG &&
-                   name_len >= 4 &&
-                   strncasecmp(de->d_name + (name_len-4), ".zip", 4) == 0) {
-            if (z_size >= z_alloc) {
-                z_alloc *= 2;
-                zips = (char**)realloc(zips, z_alloc * sizeof(char*));
-            }
-            zips[z_size++] = strdup(de->d_name);
-        }
+    std::string new_path = path + "/" + item;
+    if (new_path.back() == '/') {
+      // Recurse down into a subdirectory.
+      new_path.pop_back();
+      std::string result = browse_directory(new_path, device);
+      if (!result.empty()) return result;
+    } else {
+      // Selected a zip file: return the path to the caller.
+      return new_path;
     }
-    closedir(d);
+  }
 
-    qsort(dirs, d_size, sizeof(char*), compare_string);
-    qsort(zips, z_size, sizeof(char*), compare_string);
-
-    // append dirs to the zips list
-    if (d_size + z_size + 1 > z_alloc) {
-        z_alloc = d_size + z_size + 1;
-        zips = (char**)realloc(zips, z_alloc * sizeof(char*));
-    }
-    memcpy(zips + z_size, dirs, d_size * sizeof(char*));
-    free(dirs);
-    z_size += d_size;
-    zips[z_size] = NULL;
-
-    const char* headers[] = { "Choose a package to install:", path, NULL };
-
-    char* result;
-    int chosen_item = 0;
-    while (true) {
-        chosen_item = get_menu_selection(headers, zips, 1, chosen_item, device);
-
-        char* item = zips[chosen_item];
-        int item_len = strlen(item);
-        if (chosen_item == 0) {          // item 0 is always "../"
-            // go up but continue browsing (if the caller is update_directory)
-            result = NULL;
-            break;
-        }
-
-        char new_path[PATH_MAX];
-        strlcpy(new_path, path, PATH_MAX);
-        strlcat(new_path, "/", PATH_MAX);
-        strlcat(new_path, item, PATH_MAX);
-
-        if (item[item_len-1] == '/') {
-            // recurse down into a subdirectory
-            new_path[strlen(new_path)-1] = '\0';  // truncate the trailing '/'
-            result = browse_directory(new_path, device);
-            if (result) break;
-        } else {
-            // selected a zip file: return the malloc'd path to the caller.
-            result = strdup(new_path);
-            break;
-        }
-    }
-
-    for (int i = 0; i < z_size; ++i) free(zips[i]);
-    free(zips);
-
-    return result;
+  // Unreachable.
 }
 
 static bool yes_no(Device* device, const char* question1, const char* question2) {
@@ -1065,14 +1028,14 @@
         return INSTALL_ERROR;
     }
 
-    char* path = browse_directory(SDCARD_ROOT, device);
-    if (path == NULL) {
+    std::string path = browse_directory(SDCARD_ROOT, device);
+    if (path.empty()) {
         ui->Print("\n-- No package file selected.\n");
         ensure_path_unmounted(SDCARD_ROOT);
         return INSTALL_ERROR;
     }
 
-    ui->Print("\n-- Install %s ...\n", path);
+    ui->Print("\n-- Install %s ...\n", path.c_str());
     set_sdcard_update_bootloader_message();
 
     // We used to use fuse in a thread as opposed to a process. Since accessing
@@ -1080,7 +1043,7 @@
     // to deadlock when a page fault occurs. (Bug: 26313124)
     pid_t child;
     if ((child = fork()) == 0) {
-        bool status = start_sdcard_fuse(path);
+        bool status = start_sdcard_fuse(path.c_str());
 
         _exit(status ? EXIT_SUCCESS : EXIT_FAILURE);
     }
diff --git a/roots.cpp b/roots.cpp
index 376fcbd..4a0a494 100644
--- a/roots.cpp
+++ b/roots.cpp
@@ -163,7 +163,7 @@
     pid_t child;
     if ((child = vfork()) == 0) {
         execv(path, argv);
-        _exit(-1);
+        _exit(EXIT_FAILURE);
     }
     waitpid(child, &status, 0);
     if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
diff --git a/update_verifier/update_verifier.cpp b/update_verifier/update_verifier.cpp
index 1c9be2d..a4799cc 100644
--- a/update_verifier/update_verifier.cpp
+++ b/update_verifier/update_verifier.cpp
@@ -30,6 +30,7 @@
  * verifier reaches the end after the verification.
  */
 
+#include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <stdio.h>
@@ -52,14 +53,71 @@
 using android::hardware::boot::V1_0::CommandResult;
 
 constexpr auto CARE_MAP_FILE = "/data/ota_package/care_map.txt";
+constexpr auto DM_PATH_PREFIX = "/sys/block/";
+constexpr auto DM_PATH_SUFFIX = "/dm/name";
+constexpr auto DEV_PATH = "/dev/block/";
 constexpr int BLOCKSIZE = 4096;
 
-static bool read_blocks(const std::string& blk_device_prefix, const std::string& range_str) {
-  std::string slot_suffix = android::base::GetProperty("ro.boot.slot_suffix", "");
-  std::string blk_device = blk_device_prefix + slot_suffix;
-  android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(blk_device.c_str(), O_RDONLY)));
+// Find directories in format of "/sys/block/dm-X".
+static int dm_name_filter(const dirent* de) {
+  if (android::base::StartsWith(de->d_name, "dm-")) {
+    return 1;
+  }
+  return 0;
+}
+
+static bool read_blocks(const std::string& blk_device, const std::string& range_str) {
+  // Parse the partition in the end of the block_device string.
+  // Here is one example: "/dev/block/bootdevice/by-name/system"
+  std::string partition;
+  if (android::base::EndsWith(blk_device, "system")) {
+    partition = "system";
+  } else if (android::base::EndsWith(blk_device, "vendor")) {
+    partition = "vendor";
+  } else {
+    LOG(ERROR) << "Failed to parse partition string in " << blk_device;
+    return false;
+  }
+
+  // Iterate the content of "/sys/block/dm-X/dm/name". If it matches "system"
+  // (or "vendor"), then dm-X is a dm-wrapped system/vendor partition.
+  // Afterwards, update_verifier will read every block on the care_map_file of
+  // "/dev/block/dm-X" to ensure the partition's integrity.
+  dirent** namelist;
+  int n = scandir(DM_PATH_PREFIX, &namelist, dm_name_filter, alphasort);
+  if (n == -1) {
+    PLOG(ERROR) << "Failed to scan dir " << DM_PATH_PREFIX;
+    return false;
+  }
+  if (n == 0) {
+    LOG(ERROR) << "dm block device not found for " << partition;
+    return false;
+  }
+
+  std::string dm_block_device;
+  while (n--) {
+    std::string path = DM_PATH_PREFIX + std::string(namelist[n]->d_name) + DM_PATH_SUFFIX;
+    std::string content;
+    if (!android::base::ReadFileToString(path, &content)) {
+      PLOG(WARNING) << "Failed to read " << path;
+    } else if (android::base::Trim(content) == partition) {
+      dm_block_device = DEV_PATH + std::string(namelist[n]->d_name);
+      while (n--) {
+        free(namelist[n]);
+      }
+      break;
+    }
+    free(namelist[n]);
+  }
+  free(namelist);
+
+  if (dm_block_device.empty()) {
+    LOG(ERROR) << "Failed to find dm block device for " << partition;
+    return false;
+  }
+  android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(dm_block_device.c_str(), O_RDONLY)));
   if (fd.get() == -1) {
-    PLOG(ERROR) << "Error reading partition " << blk_device;
+    PLOG(ERROR) << "Error reading " << dm_block_device << " for partition " << partition;
     return false;
   }
 
@@ -100,7 +158,7 @@
     blk_count += (range_end - range_start);
   }
 
-  LOG(INFO) << "Finished reading " << blk_count << " blocks on " << blk_device;
+  LOG(INFO) << "Finished reading " << blk_count << " blocks on " << dm_block_device;
   return true;
 }
 
diff --git a/updater/blockimg.cpp b/updater/blockimg.cpp
index 6755d78..03ce413 100644
--- a/updater/blockimg.cpp
+++ b/updater/blockimg.cpp
@@ -120,7 +120,7 @@
 
 err:
   LOG(ERROR) << "failed to parse range '" << range_text << "'";
-  exit(1);
+  exit(EXIT_FAILURE);
 }
 
 static bool range_overlaps(const RangeSet& r1, const RangeSet& r2) {
diff --git a/updater/install.cpp b/updater/install.cpp
index 7a8e92f..c7ecdb5 100644
--- a/updater/install.cpp
+++ b/updater/install.cpp
@@ -247,7 +247,7 @@
   pid_t child;
   if ((child = vfork()) == 0) {
     execv(path, argv);
-    _exit(-1);
+    _exit(EXIT_FAILURE);
   }
 
   int status;
@@ -1072,7 +1072,7 @@
   if (child == 0) {
     execv(args2[0], args2);
     PLOG(ERROR) << "run_program: execv failed";
-    _exit(1);
+    _exit(EXIT_FAILURE);
   }
 
   int status;