Checkpoint: Assure proper buffer alignment
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
diff --git a/Checkpoint.cpp b/Checkpoint.cpp
index ce0d00c..28855e6 100644
--- a/Checkpoint.cpp
+++ b/Checkpoint.cpp
@@ -296,9 +296,9 @@
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 @@
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");