diff options
author | Stephen Hines | 2016-12-07 05:46:10 -0600 |
---|---|---|
committer | Stephen Hines | 2016-12-07 05:46:55 -0600 |
commit | b0775ca51739747be074a4b933d52da933830ed5 (patch) | |
tree | 133068fb814cce23716f5a6c3166835669421cfd /base/include/android-base | |
parent | a79477559213e25c6a1f4bf29fc1f4a2e741f8df (diff) | |
download | platform-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.h | 20 |
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 @@ | |||
20 | namespace android { | 20 | namespace android { |
21 | namespace base { | 21 | namespace 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. |
26 | template <typename T> | 26 | template <typename T> |
27 | static inline T get_unaligned(const T* address) { | 27 | static 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 | ||
35 | template <typename T> | 33 | template <typename T> |
36 | static inline void put_unaligned(T* address, T v) { | 34 | static 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 |