OSDN Git Service

Checkpoint: Assure proper buffer alignment
authorGreg Kaiser <gkaiser@google.com>
Tue, 18 Dec 2018 20:22:29 +0000 (12:22 -0800)
committerGreg Kaiser <gkaiser@google.com>
Thu, 20 Dec 2018 18:38:31 +0000 (10:38 -0800)
We have a char buffer on the stack, which we then cast to a
struct, and then proceed to access elements in the struct.
This is not safe across all platforms, as some platforms
may require a certain alignment for members of the struct.
We fix this by assuring an appropriate alignment for our
char buffer.

We also use C++ casting, and rename our buffer to differenciate
it from the other 'buffer' variable in this function.

Test: TreeHugger
Change-Id: I8254cb6b8124e394bd805afd1ccca0faedb27ffa

Checkpoint.cpp

index ce0d00c..28855e6 100644 (file)
@@ -296,9 +296,9 @@ Status cp_restoreCheckpoint(const std::string& blockDevice) {
         PLOG(ERROR) << "Cannot open " << blockDevice;
         return Status::fromExceptionCode(errno, ("Cannot open " + blockDevice).c_str());
     }
-    char buffer[kBlockSize];
-    device.read(buffer, kBlockSize);
-    log_sector& ls = *(log_sector*)buffer;
+    alignas(alignof(log_sector)) char ls_buffer[kBlockSize];
+    device.read(ls_buffer, kBlockSize);
+    log_sector& ls = *reinterpret_cast<log_sector*>(ls_buffer);
     if (ls.magic != kMagic) {
         LOG(ERROR) << "No magic";
         return Status::fromExceptionCode(EINVAL, "No magic");
@@ -307,10 +307,9 @@ Status cp_restoreCheckpoint(const std::string& blockDevice) {
     LOG(INFO) << "Restoring " << ls.sequence << " log sectors";
 
     for (int sequence = ls.sequence; sequence >= 0; sequence--) {
-        char buffer[kBlockSize];
         device.seekg(0);
-        device.read(buffer, kBlockSize);
-        log_sector& ls = *(log_sector*)buffer;
+        device.read(ls_buffer, kBlockSize);
+        ls = *reinterpret_cast<log_sector*>(ls_buffer);
         if (ls.magic != kMagic) {
             LOG(ERROR) << "No magic!";
             return Status::fromExceptionCode(EINVAL, "No magic");