Debian Codegraph @

js/src/wasm/WasmMemory.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 *
4 * Copyright 2021 Mozilla Foundation
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 #ifndef wasm_memory_h
20 #define wasm_memory_h
21
22 #include "mozilla/CheckedInt.h"
23 #include "mozilla/Maybe.h"
24
25 #include <stdint.h>
26
27 #include "js/Value.h"
28 #include "vm/NativeObject.h"
29 #include "wasm/WasmConstants.h"
30 #include "wasm/WasmValType.h"
31
32 namespace js {
33 namespace wasm {
34
35 // Limits are parameterized by an AddressType which is used to index the
36 // underlying resource (either a Memory or a Table). Tables are restricted to
37 // I32, while memories may use I64 when memory64 is enabled.
38
39 enum class AddressType : uint8_t { I32, I64 };
40
41 inline ValType ToValType(AddressType at) {
42 return at == AddressType::I64 ? ValType::I64 : ValType::I32;
43 }
44
45 inline AddressType MinAddressType(AddressType a, AddressType b) {
46 return (a == AddressType::I32 || b == AddressType::I32) ? AddressType::I32
47 : AddressType::I64;
48 }
49
50 extern bool ToAddressType(JSContext* cx, HandleValue value,
51 AddressType* addressType);
52
53 extern const char* ToString(AddressType addressType);
54
55 // Pages is a typed unit representing a multiple of wasm::PageSize. We
56 // generally use pages as the unit of length when representing linear memory
57 // lengths so as to avoid overflow when the specified initial or maximum pages
58 // would overflow the native word size.
59 //
60 // Modules may specify pages up to 2^48 inclusive and so Pages is 64-bit on all
61 // platforms.
62 //
63 // We represent byte lengths using the native word size, as it is assumed that
64 // consumers of this API will only need byte lengths once it is time to
65 // allocate memory, at which point the pages will be checked against the
66 // implementation limits `MaxMemoryPages()` and will then be guaranteed to
67 // fit in a native word.
68 struct Pages {
69 private:
70 // Pages are specified by limit fields, which in general may be up to 2^48,
71 // so we must use uint64_t here.
72 uint64_t value_;
73
74 public:
75 constexpr Pages() : value_(0) {}
76 constexpr explicit Pages(uint64_t value) : value_(value) {}
77
78 // Get the wrapped page value. Only use this if you must, prefer to use or
79 // add new APIs to Page.
80 uint64_t value() const { return value_; }
81
82 // Converts from a byte length to pages, assuming that the length is an
83 // exact multiple of the page size.
84 static Pages fromByteLengthExact(size_t byteLength) {
85 MOZ_ASSERT(byteLength % PageSize == 0);
86 return Pages(byteLength / PageSize);
87 }
88
89 // Return whether the page length may overflow when converted to a byte
90 // length in the native word size.
91 bool hasByteLength() const {
92 mozilla::CheckedInt<size_t> length(value_);
93 length *= PageSize;
94 return length.isValid();
95 }
96
97 // Converts from pages to byte length in the native word size. Users must
98 // check for overflow, or be assured else-how that overflow cannot happen.
99 size_t byteLength() const {
100 mozilla::CheckedInt<size_t> length(value_);
101 length *= PageSize;
102 return length.value();
103 }
104
105 // Increment this pages by delta and return whether the resulting value
106 // did not overflow. If there is no overflow, then this is set to the
107 // resulting value.
108 bool checkedIncrement(Pages delta) {
109 mozilla::CheckedInt<uint64_t> newValue = value_;
110 newValue += delta.value_;
111 if (!newValue.isValid()) {
112 return false;
113 }
114 value_ = newValue.value();
115 return true;
116 }
117
118 // Implement pass-through comparison operators so that Pages can be compared.
119
120 bool operator==(Pages other) const { return value_ == other.value_; }
121 bool operator!=(Pages other) const { return value_ != other.value_; }
122 bool operator<=(Pages other) const { return value_ <= other.value_; }
123 bool operator<(Pages other) const { return value_ < other.value_; }
124 bool operator>=(Pages other) const { return value_ >= other.value_; }
125 bool operator>(Pages other) const { return value_ > other.value_; }
126 };
127
128 // The largest number of pages the application can request.
129 extern Pages MaxMemoryPages(AddressType t);
130
131 // The byte value of MaxMemoryPages(t).
132 static inline size_t MaxMemoryBytes(AddressType t) {
133 return MaxMemoryPages(t).byteLength();
134 }
135
136 // A value at least as large as MaxMemoryBytes(t) representing the largest valid
137 // bounds check limit on the system. (It can be larger than MaxMemoryBytes()
138 // because bounds check limits are rounded up to fit formal requirements on some
139 // platforms. Also see ComputeMappedSize().)
140 extern size_t MaxMemoryBoundsCheckLimit(AddressType t);
141
142 static inline uint64_t MaxMemoryPagesValidation(AddressType addressType) {
143 return addressType == AddressType::I32 ? MaxMemory32PagesValidation
144 : MaxMemory64PagesValidation;
145 }
146
147 static inline uint64_t MaxTableElemsValidation(AddressType addressType) {
148 return addressType == AddressType::I32 ? MaxTable32ElemsValidation
149 : MaxTable64ElemsValidation;
150 }
151
152 // Compute the 'clamped' maximum size of a memory. See
153 // 'WASM Linear Memory structure' in ArrayBufferObject.cpp for background.
154 extern Pages ClampedMaxPages(AddressType t, Pages initialPages,
155 const mozilla::Maybe<Pages>& sourceMaxPages,
156 bool useHugeMemory);
157
158 // For a given WebAssembly/asm.js 'clamped' max pages, return the number of
159 // bytes to map which will necessarily be a multiple of the system page size and
160 // greater than clampedMaxPages in bytes. See "Wasm Linear Memory Structure" in
161 // vm/ArrayBufferObject.cpp.
162 extern size_t ComputeMappedSize(Pages clampedMaxPages);
163
164 extern uint64_t GetMaxOffsetGuardLimit(bool hugeMemory);
165
166 // Return whether the given immediate satisfies the constraints of the platform.
167 extern bool IsValidBoundsCheckImmediate(uint32_t i);
168
169 // Return whether the given immediate is valid on arm.
170 extern bool IsValidARMImmediate(uint32_t i);
171
172 // Return the next higher valid immediate that satisfies the constraints of the
173 // platform.
174 extern uint64_t RoundUpToNextValidBoundsCheckImmediate(uint64_t i);
175
176 // Return the next higher valid immediate for arm.
177 extern uint64_t RoundUpToNextValidARMImmediate(uint64_t i);
178
179 #ifdef WASM_SUPPORTS_HUGE_MEMORY
180 // On WASM_SUPPORTS_HUGE_MEMORY platforms, every asm.js or WebAssembly 32-bit
181 // memory unconditionally allocates a huge region of virtual memory of size
182 // wasm::HugeMappedSize. This allows all memory resizing to work without
183 // reallocation and provides enough guard space for most offsets to be folded
184 // into memory accesses. See "Linear memory addresses and bounds checking" in
185 // wasm/WasmMemory.cpp for more information.
186
187 // Reserve 4GiB to support any i32 index.
188 static const uint64_t HugeIndexRange = uint64_t(UINT32_MAX) + 1;
189 // Reserve 32MiB to support most offset immediates. Any immediate that is over
190 // this will require a bounds check to be emitted. 32MiB was chosen to
191 // generously cover the max offset immediate, 20MiB, found in a corpus of wasm
192 // modules.
193 static const uint64_t HugeOffsetGuardLimit = 1 << 25;
194 // Reserve a wasm page (64KiB) to support slop on unaligned accesses.
195 static const uint64_t HugeUnalignedGuardPage = PageSize;
196
197 // Compute the total memory reservation.
198 static const uint64_t HugeMappedSize =
199 HugeIndexRange + HugeOffsetGuardLimit + HugeUnalignedGuardPage;
200
201 // Try to keep the memory reservation aligned to the wasm page size. This
202 // ensures that it's aligned to the system page size.
203 static_assert(HugeMappedSize % PageSize == 0);
204
205 #endif
206
207 // The size of the guard page for non huge-memories.
208 static const size_t GuardSize = PageSize;
209
210 // The size of the guard page that included NULL pointer. Reserve a smallest
211 // range for typical hardware, to catch near NULL pointer accesses, e.g.
212 // for a structure fields operations.
213 static const size_t NullPtrGuardSize = 4096;
214
215 // Check if a range of wasm memory is within bounds, specified as byte offset
216 // and length (using 32-bit indices). Omits one check by converting from
217 // uint32_t to uint64_t, at which point overflow cannot occur.
218 static inline bool MemoryBoundsCheck(uint32_t offset, uint32_t len,
219 size_t memLen) {
220 uint64_t offsetLimit = uint64_t(offset) + uint64_t(len);
221 return offsetLimit <= memLen;
222 }
223
224 // Check if a range of wasm memory is within bounds, specified as byte offset
225 // and length (using 64-bit indices).
226 static inline bool MemoryBoundsCheck(uint64_t offset, uint64_t len,
227 size_t memLen) {
228 uint64_t offsetLimit = offset + len;
229 bool didOverflow = offsetLimit < offset;
230 bool tooLong = memLen < offsetLimit;
231 return !didOverflow && !tooLong;
232 }
233
234 } // namespace wasm
235 } // namespace js
236
237 #endif // wasm_memory_h