1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef V8_BASE_MEMORY_H_
6 #define V8_BASE_MEMORY_H_
7
8 #include "src/base/macros.h"
9
10 namespace v8 {
11 namespace base {
12
13 using Address = uintptr_t;
14 using byte = uint8_t;
15
16 // Memory provides an interface to 'raw' memory. It encapsulates the casts
17 // that typically are needed when incompatible pointer types are used.
18 // Note that this class currently relies on undefined behaviour. There is a
19 // proposal (http://wg21.link/p0593r2) to make it defined behaviour though.
20 template <class T>
Memory(Address addr)21 inline T& Memory(Address addr) {
22 DCHECK(IsAligned(addr, alignof(T)));
23 return *reinterpret_cast<T*>(addr);
24 }
25 template <class T>
Memory(byte * addr)26 inline T& Memory(byte* addr) {
27 return Memory<T>(reinterpret_cast<Address>(addr));
28 }
29
30 template <typename V>
ReadUnalignedValue(Address p)31 static inline V ReadUnalignedValue(Address p) {
32 ASSERT_TRIVIALLY_COPYABLE(V);
33 V r;
34 memcpy(&r, reinterpret_cast<void*>(p), sizeof(V));
35 return r;
36 }
37
38 template <typename V>
WriteUnalignedValue(Address p,V value)39 static inline void WriteUnalignedValue(Address p, V value) {
40 ASSERT_TRIVIALLY_COPYABLE(V);
41 memcpy(reinterpret_cast<void*>(p), &value, sizeof(V));
42 }
43
44 template <typename V>
ReadLittleEndianValue(Address p)45 static inline V ReadLittleEndianValue(Address p) {
46 #if defined(V8_TARGET_LITTLE_ENDIAN)
47 return ReadUnalignedValue<V>(p);
48 #elif defined(V8_TARGET_BIG_ENDIAN)
49 V ret{};
50 const byte* src = reinterpret_cast<const byte*>(p);
51 byte* dst = reinterpret_cast<byte*>(&ret);
52 for (size_t i = 0; i < sizeof(V); i++) {
53 dst[i] = src[sizeof(V) - i - 1];
54 }
55 return ret;
56 #endif // V8_TARGET_LITTLE_ENDIAN
57 }
58
59 template <typename V>
WriteLittleEndianValue(Address p,V value)60 static inline void WriteLittleEndianValue(Address p, V value) {
61 #if defined(V8_TARGET_LITTLE_ENDIAN)
62 WriteUnalignedValue<V>(p, value);
63 #elif defined(V8_TARGET_BIG_ENDIAN)
64 byte* src = reinterpret_cast<byte*>(&value);
65 byte* dst = reinterpret_cast<byte*>(p);
66 for (size_t i = 0; i < sizeof(V); i++) {
67 dst[i] = src[sizeof(V) - i - 1];
68 }
69 #endif // V8_TARGET_LITTLE_ENDIAN
70 }
71
72 template <typename V>
ReadLittleEndianValue(V * p)73 static inline V ReadLittleEndianValue(V* p) {
74 return ReadLittleEndianValue<V>(reinterpret_cast<Address>(p));
75 }
76
77 template <typename V>
WriteLittleEndianValue(V * p,V value)78 static inline void WriteLittleEndianValue(V* p, V value) {
79 static_assert(
80 !std::is_array<V>::value,
81 "Passing an array decays to pointer, causing unexpected results.");
82 WriteLittleEndianValue<V>(reinterpret_cast<Address>(p), value);
83 }
84
85 } // namespace base
86 } // namespace v8
87
88 #endif // V8_BASE_MEMORY_H_
89