summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorStephen Hines2016-12-07 05:46:10 -0600
committerStephen Hines2016-12-07 05:46:55 -0600
commitb0775ca51739747be074a4b933d52da933830ed5 (patch)
tree133068fb814cce23716f5a6c3166835669421cfd /base/include/android-base
parenta79477559213e25c6a1f4bf29fc1f4a2e741f8df (diff)
downloadplatform-system-core-b0775ca51739747be074a4b933d52da933830ed5.tar.gz
platform-system-core-b0775ca51739747be074a4b933d52da933830ed5.tar.xz
platform-system-core-b0775ca51739747be074a4b933d52da933830ed5.zip
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
Diffstat (limited to 'base/include/android-base')
-rw-r--r--base/include/android-base/memory.h20
1 files changed, 7 insertions, 13 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 @@
20namespace android { 20namespace android {
21namespace base { 21namespace base {
22 22
23// Use packed structures for access to unaligned data on targets with alignment 23// Use memcpy for access to unaligned data on targets with alignment
24// restrictions. The compiler will generate appropriate code to access these 24// restrictions. The compiler will generate appropriate code to access these
25// structures without generating alignment exceptions. 25// structures without generating alignment exceptions.
26template <typename T> 26template <typename T>
27static inline T get_unaligned(const T* address) { 27static inline T get_unaligned(const void* address) {
28 struct unaligned { 28 T result;
29 T v; 29 memcpy(&result, address, sizeof(T));
30 } __attribute__((packed)); 30 return result;
31 const unaligned* p = reinterpret_cast<const unaligned*>(address);
32 return p->v;
33} 31}
34 32
35template <typename T> 33template <typename T>
36static inline void put_unaligned(T* address, T v) { 34static inline void put_unaligned(void* address, T v) {
37 struct unaligned { 35 memcpy(address, &v, sizeof(T));
38 T v;
39 } __attribute__((packed));
40 unaligned* p = reinterpret_cast<unaligned*>(address);
41 p->v = v;
42} 36}
43 37
44} // namespace base 38} // namespace base