Address some security concerns in the cgpt tool.

1. Check for potential integer overflow in sector_bytes * sector_count.
2. Added O_NOFOLLOW to open() call - Is this enough?
3. Passing buffer length to GuidToStr(), PMBRToStr().
4. Use unsigned int in GetEntry() to determine stride.
5. Address conversion between UTF16 and UTF8.

Note: The UTF conversion is complex and troublesome, and needs careful
consideration to get right. For now, I've just forced the interpretation of
the partition name to 7-bit ASCII. That's sufficient for the needs of Chrome
OS, and I can file a new issue to handle UTF correctly.

BUG=chrome-os-partner:705
TEST=manual

Running "make runtests" invokes the tests/run_cgpt_tests.sh script, which checks the behavior and output of the cgpt tool.

Review URL: http://codereview.chromium.org/3594010

Change-Id: I5fd29796d8c929527e0cfbc6d5ccbcdc77502c6b
diff --git a/cgpt/cmd_add.c b/cgpt/cmd_add.c
index 12ae57c..21085e7 100644
--- a/cgpt/cmd_add.c
+++ b/cgpt/cmd_add.c
@@ -36,7 +36,7 @@
 
 int cmd_add(int argc, char *argv[]) {
   struct drive drive;
-  int partition = 0;
+  uint32_t partition = 0;
   uint64_t begin = 0;
   uint64_t size = 0;
   Guid type_guid;
@@ -57,8 +57,8 @@
 
   int gpt_retval;
   GptEntry *entry;
-  int index;
-  
+  uint32_t index;
+
   int c;
   int errorcnt = 0;
   char *e = 0;
@@ -198,7 +198,7 @@
     return CGPT_FAILED;
   }
 
-  int max_part = GetNumberOfEntries(&drive.gpt);
+  uint32_t max_part = GetNumberOfEntries(&drive.gpt);
   if (partition) {
     if (partition > max_part) {
       Error("invalid partition number: %d\n", partition);
@@ -244,9 +244,8 @@
   if (set_unique)
     memcpy(&entry->unique, &unique_guid, sizeof(Guid));
   if (label) {
-    uint16_t buf[128];
-    UTF8ToUTF16((uint8_t *)label, buf);
-    memcpy(entry->name, buf, sizeof(entry->name));
+    UTF8ToUTF16((uint8_t *)label, entry->name,
+                sizeof(entry->name) / sizeof(entry->name[0]));
   }
   if (set_raw) {
     entry->attrs.fields.gpt_att = raw_value;