Fix unaligned read and write

See crbug.com/532120

BUG=chromium:532120

Run on chromeos checkout:
    FEATURES='test' USE='asan clang' \
        CXXFLAGS='-fsanitize=address -fsanitize=alignment' \
        emerge-x86-generic libweave

Change-Id: I817317e8670c46698fd7dbbd05d44798c541ce0b
Reviewed-on: https://weave-review.googlesource.com/1080
Reviewed-by: Alex Vakulenko <avakulenko@google.com>
Reviewed-by: Gene Gutnik <gene@google.com>
diff --git a/libweave/third_party/modp_b64/README.chromium b/libweave/third_party/modp_b64/README.chromium
index 35b9e54..40b93d2 100644
--- a/libweave/third_party/modp_b64/README.chromium
+++ b/libweave/third_party/modp_b64/README.chromium
@@ -13,3 +13,5 @@
 
 The modp_b64.cc and modp_b64.h files were modified to make them safe on
 64-bit systems.
+The modp_b64.cc was modified to avoid misaligned read/write on
+little-endian hardware.
diff --git a/libweave/third_party/modp_b64/modp_b64.cc b/libweave/third_party/modp_b64/modp_b64.cc
index e5f6cf1..fdb8a40 100644
--- a/libweave/third_party/modp_b64/modp_b64.cc
+++ b/libweave/third_party/modp_b64/modp_b64.cc
@@ -211,28 +211,18 @@
 
     uint8_t* p = (uint8_t*)dest;
     uint32_t x = 0;
-    uint32_t* destInt = (uint32_t*) p;
-    uint32_t* srcInt = (uint32_t*) src;
-    uint32_t y = *srcInt++;
-    for (i = 0; i < chunks; ++i) {
-        x = d0[y & 0xff] |
-            d1[(y >> 8) & 0xff] |
-            d2[(y >> 16) & 0xff] |
-            d3[(y >> 24) & 0xff];
-
+    const uint8_t* y = (uint8_t*)src;
+    for (i = 0; i < chunks; ++i, y += 4) {
+        x = d0[y[0]] | d1[y[1]] | d2[y[2]] | d3[y[3]];
         if (x >= BADCHAR) return MODP_B64_ERROR;
-        *destInt = x ;
-        p += 3;
-        destInt = (uint32_t*)p;
-        y = *srcInt++;}
-
+        *p++ =  ((uint8_t*)(&x))[0];
+        *p++ =  ((uint8_t*)(&x))[1];
+        *p++ =  ((uint8_t*)(&x))[2];
+    }
 
     switch (leftover) {
     case 0:
-        x = d0[y & 0xff] |
-            d1[(y >> 8) & 0xff] |
-            d2[(y >> 16) & 0xff] |
-            d3[(y >> 24) & 0xff];
+        x = d0[y[0]] | d1[y[1]] | d2[y[2]] | d3[y[3]];
 
         if (x >= BADCHAR) return MODP_B64_ERROR;
         *p++ =  ((uint8_t*)(&x))[0];
@@ -241,17 +231,15 @@
         return (chunks+1)*3;
         break;
     case 1:  /* with padding this is an impossible case */
-        x = d0[y & 0xff];
+        x = d0[y[0]];
         *p = *((uint8_t*)(&x)); // i.e. first char/byte in int
         break;
     case 2: // * case 2, 1  output byte */
-        x = d0[y & 0xff] | d1[y >> 8 & 0xff];
+        x = d0[y[0]] | d1[y[1]];
         *p = *((uint8_t*)(&x)); // i.e. first char
         break;
     default: /* case 3, 2 output bytes */
-        x = d0[y & 0xff] |
-            d1[y >> 8 & 0xff ] |
-            d2[y >> 16 & 0xff];  /* 0x3c */
+        x = d0[y[0]] | d1[y[1]] | d2[y[2]];  /* 0x3c */
         *p++ =  ((uint8_t*)(&x))[0];
         *p =  ((uint8_t*)(&x))[1];
         break;