From b0775ca51739747be074a4b933d52da933830ed5 Mon Sep 17 00:00:00 2001 From: Stephen Hines Date: Wed, 7 Dec 2016 03:46:10 -0800 Subject: [PATCH] Switch to memcpy for accessing misaligned data. Bug: http://b/31532493 Using misaligned pointers forces us to potentially take the address of members in a packed structure (which is now a warning/error in the latest Clang). Using memcpy() is the proper way to handle this kind of problem, as the compiler can insert the proper instructions (and usually elide the memcpy() entirely). Test: Built correctly with updated compilers. Change-Id: Ia1f6eb62cf19404ff76b71d3c6c7ffffa1403120 --- base/include/android-base/memory.h | 20 +++++++------------- gatekeeperd/SoftGateKeeper.h | 2 +- 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/base/include/android-base/memory.h b/base/include/android-base/memory.h index 3a2f8fad6..997122623 100644 --- a/base/include/android-base/memory.h +++ b/base/include/android-base/memory.h @@ -20,25 +20,19 @@ namespace android { namespace base { -// Use packed structures for access to unaligned data on targets with alignment +// Use memcpy for access to unaligned data on targets with alignment // restrictions. The compiler will generate appropriate code to access these // structures without generating alignment exceptions. template -static inline T get_unaligned(const T* address) { - struct unaligned { - T v; - } __attribute__((packed)); - const unaligned* p = reinterpret_cast(address); - return p->v; +static inline T get_unaligned(const void* address) { + T result; + memcpy(&result, address, sizeof(T)); + return result; } template -static inline void put_unaligned(T* address, T v) { - struct unaligned { - T v; - } __attribute__((packed)); - unaligned* p = reinterpret_cast(address); - p->v = v; +static inline void put_unaligned(void* address, T v) { + memcpy(address, &v, sizeof(T)); } } // namespace base diff --git a/gatekeeperd/SoftGateKeeper.h b/gatekeeperd/SoftGateKeeper.h index 8b15d72e2..cb02a6fc6 100644 --- a/gatekeeperd/SoftGateKeeper.h +++ b/gatekeeperd/SoftGateKeeper.h @@ -152,7 +152,7 @@ public: } bool DoVerify(const password_handle_t *expected_handle, const SizedBuffer &password) { - uint64_t user_id = android::base::get_unaligned(&expected_handle->user_id); + uint64_t user_id = android::base::get_unaligned(&expected_handle->user_id); FastHashMap::const_iterator it = fast_hash_map_.find(user_id); if (it != fast_hash_map_.end() && VerifyFast(it->second, password)) { return true;