libmemtrack: Fix integer overflow in kgsl function

In the kgsl function which gets memory info for a
pid, there could be possibility of integer overflow
in operations with size, mapsize, accounted_size,
and unaccounted_size due to which result might be
smaller than these values. External inputs size and
mapsize are verified, and overflow check has been added.

CRs-Fixed: 1103020
Change-Id: Ic450e990598777591739635facc08fb7a2e477f9
Signed-off-by: Archana Sriram <apsrir@codeaurora.org>
diff --git a/libmemtrack/kgsl.c b/libmemtrack/kgsl.c
index c3aa86e..877b54e 100644
--- a/libmemtrack/kgsl.c
+++ b/libmemtrack/kgsl.c
@@ -93,19 +93,31 @@
             continue;
         }
 
+        if (size == 0)
+            return -EINVAL;
+
+        if (unaccounted_size + size < size)
+            return -ERANGE;
+
         if (type == MEMTRACK_TYPE_GL && strcmp(line_type, "gpumem") == 0) {
 
             if (flags[6] == 'Y') {
-                accounted_size += mapsize;
-		unaccounted_size += size - mapsize;
-	    } else
-                unaccounted_size += size;
+                if (accounted_size + mapsize < accounted_size)
+                    return -ERANGE;
 
+                accounted_size += mapsize;
+
+                if (mapsize > size)
+                    return -EINVAL;
+
+                unaccounted_size += size - mapsize;
+            } else
+                unaccounted_size += size;
         } else if (type == MEMTRACK_TYPE_GRAPHICS && strcmp(line_type, "ion") == 0) {
             if (strcmp(line_usage, "egl_surface") == 0)
                 unaccounted_size += size;
             else if (egl_surface_count == 0)
-		unaccounted_size += size / (egl_image_count ? egl_image_count : 1);
+                unaccounted_size += size / (egl_image_count ? egl_image_count : 1);
         }
     }