ANDROID: Fix heap overflow in sgdisk

If a maliciously formatted USB or SD Card device was inserted into an
Android device, the sgdisk tool could crash. This crash occurs because
sgdisk does not validate that the number of GPT partition entries
specified on disk matches the internal maximum permitted by the GPT spec.

Fix this by sanity checking the on disk parameter before using it.

After the fix, sgdisk detects the corrupt GPT during the formatting
procedure, but it is harmlessly zapped and replaced with a new one.

Test: before fix, saw sgdisk crash while the device was booting up
Test: after fix, no more sgdisk crashes
Test: went through "portable storage" and "adopted storage" wizard flows
      using the cuttlefish virtual device and a malicious partition
      table flashed to the device

Bug: 152874864
Change-Id: Iec64bc2ef5c31ad985126f9cf3b755eec7de3abe
(cherry picked from commit 313410dbea4f777d1388735960d4ea16e8c3b1ff)
diff --git a/gpt.cc b/gpt.cc
index 9ad769a..303bdf7 100644
--- a/gpt.cc
+++ b/gpt.cc
@@ -952,7 +952,10 @@
    uint32_t sizeOfParts, newCRC;
    int retval;
 
-   if (disk.OpenForRead()) {
+   if (header.sizeOfPartitionEntries != sizeof(GPTPart)) {
+      cerr << "Error! GPT header contains invalid partition entry size!\n";
+      retval = 0;
+   } else if (disk.OpenForRead()) {
       if (sector == 0) {
          retval = disk.Seek(header.partitionEntriesLBA);
       } else {