/src/wasm-tools/crates/wasmparser/src/offsets.rs
Line | Count | Source |
1 | | /* Copyright 2026 Mozilla Foundation |
2 | | * |
3 | | * Licensed under the Apache License, Version 2.0 (the "License"); |
4 | | * you may not use this file except in compliance with the License. |
5 | | * You may obtain a copy of the License at |
6 | | * |
7 | | * http://www.apache.org/licenses/LICENSE-2.0 |
8 | | * |
9 | | * Unless required by applicable law or agreed to in writing, software |
10 | | * distributed under the License is distributed on an "AS IS" BASIS, |
11 | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | | * See the License for the specific language governing permissions and |
13 | | * limitations under the License. |
14 | | */ |
15 | | |
16 | | //! Logical offsets into the input wasm file are strictly limited to fit into |
17 | | //! an integer of type [u64]. Data in each chunk is addressed through an offset |
18 | | //! into an `[u8]` slice, which uses `usize`-addressing. |
19 | | //! |
20 | | //! This module contains functionality to bridge the gap. |
21 | | |
22 | | // An (not necessarily exhaustive) list of properties we use of `u64` in relation |
23 | | // to usize: |
24 | | // - u64::MAX as an upper bound and sometimes invalid offset |
25 | | // - 0u64 as the starting offset |
26 | | // - we can add and subtract small offsets to recalculate the original position |
27 | | // in some error paths, where saving the position directly would clutter registers. |
28 | | |
29 | | // An memory offset into some chunk of bytes occurs at some specified logical |
30 | | // offset in the file. We currently use `usize` to represent memory offsets. |
31 | | // TODO: on platforms where usize::BITS > u64::BITS (currently almost no-where), |
32 | | // we could use u64 directly instead of usize to represent memory offsets. |
33 | | |
34 | | use crate::Error; |
35 | | |
36 | | /// Return the largest memory offset that can be added to `offset` without going |
37 | | /// past `max_offset` or overflowing. |
38 | 2.14M | pub fn max_data_len(offset: u64, max_offset: u64) -> usize { |
39 | 2.14M | let mut max_logical = max_offset - offset; |
40 | 2.14M | if u64::BITS > usize::BITS { |
41 | 0 | max_logical = max_logical.min(usize::MAX as u64) |
42 | 2.14M | } |
43 | | // we now know that max_logical fits into a usize |
44 | 2.14M | max_logical as usize |
45 | 2.14M | } |
46 | | |
47 | | #[cold] |
48 | 0 | pub fn panic_too_many_bytes(offset: u64, len: usize, max_len: usize) -> ! { |
49 | 0 | panic!( |
50 | | "Content too large to parse. Got {len}, expected at most {max_len} bytes at offset 0x{offset:x}." |
51 | | ) |
52 | | } |
53 | 0 | pub fn err_too_many_bytes(offset: u64, len: usize, max_len: usize) -> Error { |
54 | 0 | format_err!( |
55 | 0 | offset, |
56 | | "Content too large to parse. Got {len}, expected at most {max_len} bytes." |
57 | | ) |
58 | 0 | } |