1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
#![forbid(unsafe_code)]
//! Make sure you sync this file with `crates/fuzzing-support/src/from_bump_scope/bumping.rs`.

use core::{alloc::Layout, num::NonZeroUsize, ops::Range};

pub(crate) const MIN_CHUNK_ALIGN: usize = 16;

macro_rules! debug_assert_aligned {
    ($addr:expr, $align:expr) => {
        let addr = $addr;
        let align = $align;

        debug_assert!(align.is_power_of_two());
        let is_aligned = addr & (align - 1) == 0;

        debug_assert!(
            is_aligned,
            "expected `{}` ({}) to be aligned to `{}` ({})",
            stringify!($addr),
            addr,
            stringify!($align),
            align,
        );
    };
}

/// Arguments for [`bump_up`] and [`bump_down`].
///
/// The fields `min_align`, `align_is_const`, `size_is_const`, `size_is_multiple_of_align` are expected to be constants.
/// `bump_up` and `bump_down` are optimized for that case.
///
/// Choosing `false` for `align_is_const`, `size_is_const`, `size_is_multiple_of_align` is always valid.
pub(crate) struct BumpProps {
    pub(crate) start: usize,
    pub(crate) end: usize,
    pub(crate) layout: Layout,
    pub(crate) min_align: usize,
    pub(crate) align_is_const: bool,
    pub(crate) size_is_const: bool,
    pub(crate) size_is_multiple_of_align: bool,
}

pub(crate) struct BumpUp {
    pub(crate) new_pos: usize,
    pub(crate) ptr: usize,
}

#[inline(always)]
pub(crate) fn bump_up(
    BumpProps {
        mut start,
        end,
        layout,
        min_align,
        align_is_const,
        size_is_const,
        size_is_multiple_of_align,
    }: BumpProps,
) -> Option<BumpUp> {
    debug_assert_ne!(start, 0);
    debug_assert_ne!(end, 0);

    debug_assert!(min_align.is_power_of_two());
    debug_assert!(min_align <= MIN_CHUNK_ALIGN);

    if size_is_multiple_of_align {
        debug_assert_eq!(layout.size() % layout.align(), 0);
    }

    debug_assert!(start <= end);
    debug_assert_eq!(end % MIN_CHUNK_ALIGN, 0);

    let mut new_pos;

    // doing the `layout.size() < CHUNK_ALIGN_MIN` trick here (as seen in !UP)
    // results in worse codegen, so we don't

    if align_is_const && layout.align() <= MIN_CHUNK_ALIGN {
        // Constant, small alignment fast path!

        if align_is_const && layout.align() <= min_align {
            // alignment is already sufficient
        } else {
            // Aligning an address that is `<= range.end` with an alignment
            // that is `<= CHUNK_ALIGN_MIN` can not exceed `range.end` and
            // can not overflow as `range.end` is always aligned to `CHUNK_ALIGN_MIN`
            start = up_align_unchecked(start, layout.align());
        }

        let remaining = end - start;

        if layout.size() > remaining {
            return None;
        }

        // doesn't exceed `end` because of the check above
        new_pos = start + layout.size();
    } else {
        // Alignment is `> CHUNK_ALIGN_MIN` or unknown.

        // start and align are both nonzero
        // `aligned_down` is the aligned pointer minus `layout.align()`
        let aligned_down = (start - 1) & !(layout.align() - 1);

        // align + size cannot overflow as per `Layout`'s rules
        //
        // this could also be a `checked_add`, but we use `saturating_add` to save us a branch;
        // the `if` below will return None if the addition saturated and returned `usize::MAX`
        new_pos = aligned_down.saturating_add(layout.align() + layout.size());

        // note that `new_pos` being `usize::MAX` is an invalid value for `new_pos` and we MUST return None;
        // due to `end` being always aligned to `CHUNK_ALIGN_MIN`, it can't be `usize::MAX`;
        // thus when `new_pos` is `usize::MAX` this will always return None;
        if new_pos > end {
            return None;
        }

        // doesn't exceed `end` because `aligned_down + align + size` didn't
        start = aligned_down + layout.align();
    };

    if (align_is_const && size_is_multiple_of_align && layout.align() >= min_align)
        || (size_is_const && (layout.size() % min_align == 0))
    {
        // we are already aligned to `MIN_ALIGN`
    } else {
        // up aligning an address `<= range.end` with an alignment `<= CHUNK_ALIGN_MIN` (which `MIN_ALIGN` is)
        // can not exceed `range.end`, and thus also can't overflow
        new_pos = up_align_unchecked(new_pos, min_align);
    }

    debug_assert_aligned!(start, layout.align());
    debug_assert_aligned!(start, min_align);
    debug_assert_aligned!(new_pos, min_align);
    debug_assert_ne!(new_pos, 0);
    debug_assert_ne!(start, 0);

    Some(BumpUp { new_pos, ptr: start })
}

#[inline(always)]
pub(crate) fn bump_down(
    BumpProps {
        start,
        mut end,
        layout,
        min_align,
        align_is_const,
        size_is_const,
        size_is_multiple_of_align,
    }: BumpProps,
) -> Option<usize> {
    debug_assert_ne!(start, 0);
    debug_assert_ne!(end, 0);

    debug_assert!(min_align.is_power_of_two());
    debug_assert!(min_align <= MIN_CHUNK_ALIGN);

    if size_is_multiple_of_align {
        debug_assert_eq!(layout.size() % layout.align(), 0);
    }

    debug_assert!(start <= end);

    // these are expected to be evaluated at compile time
    let needs_align_for_min_align = (!align_is_const || !size_is_multiple_of_align || layout.align() < min_align)
        && (!size_is_const || (layout.size() % min_align != 0));
    let needs_align_for_layout = !align_is_const || !size_is_multiple_of_align || layout.align() > min_align;
    let needs_align = needs_align_for_min_align || needs_align_for_layout;

    if size_is_const && layout.size() <= MIN_CHUNK_ALIGN {
        // When `size <= CHUNK_ALIGN_MIN` subtracting it from `end` can't overflow, as the lowest value for `end` would be `start` which is aligned to `CHUNK_ALIGN_MIN`,
        // thus its address can't be smaller than it.
        end -= layout.size();

        if needs_align {
            // At this point layout's align is const, because we assume `L::SIZE_IS_CONST` implies `L::ALIGN_IS_CONST`.
            // That means `max` is evaluated at compile time, so we don't bother having different cases for either alignment.
            end = down_align(end, layout.align().max(min_align));
        }

        if end < start {
            return None;
        }
    } else if align_is_const && layout.align() <= MIN_CHUNK_ALIGN {
        // Constant, small alignment fast path!
        let remaining = end - start;

        if layout.size() > remaining {
            return None;
        }

        // doesn't overflow because of the check above
        end -= layout.size();

        if needs_align {
            // down aligning an address `>= range.start` with an alignment `<= CHUNK_ALIGN_MIN` (which `layout.align()` is)
            // can not exceed `range.start`, and thus also can't overflow
            end = down_align(end, layout.align().max(min_align));
        }
    } else {
        // Alignment is `> CHUNK_ALIGN_MIN` or unknown.

        // this could also be a `checked_sub`, but we use `saturating_sub` to save us a branch;
        // the `if` below will return None if the addition saturated and returned `0`
        end = end.saturating_sub(layout.size());
        end = down_align(end, layout.align().max(min_align));

        // note that `end` being `0` is an invalid value for `end` and we MUST return None;
        // due to `start` being `NonNull`, it can't be `0`;
        // thus when `end` is `0` this will always return None;
        if end < start {
            return None;
        }
    };

    debug_assert_aligned!(end, layout.align());
    debug_assert_aligned!(end, min_align);
    debug_assert_ne!(end, 0);

    Some(end)
}

#[inline(always)]
pub(crate) fn bump_greedy_up(
    BumpProps {
        mut start,
        end,
        layout,
        min_align,
        align_is_const,
        size_is_const: _,
        size_is_multiple_of_align: _,
    }: BumpProps,
) -> Option<Range<usize>> {
    debug_assert!(layout.size() % layout.align() == 0);
    debug_assert!(start <= end);
    debug_assert!(end % MIN_CHUNK_ALIGN == 0);

    if align_is_const && layout.align() <= min_align {
        // alignment is already sufficient
    } else {
        // `start` needs to be aligned
        if align_is_const && layout.align() <= MIN_CHUNK_ALIGN {
            // SAFETY:
            // Aligning an address that is `<= range.end` with an alignment
            // that is `<= CHUNK_ALIGN_MIN` can not exceed `range.end` and
            // can not overflow
            start = up_align_unchecked(start, layout.align());
        } else {
            start = up_align(start, layout.align())?.get();

            if start > end {
                return None;
            }
        }
    }

    let remaining = end - start;

    if layout.size() > remaining {
        return None;
    }

    // layout does fit, we just trim off the excess to make end aligned
    let end = down_align(end, layout.align());

    debug_assert_aligned!(start, layout.align());
    debug_assert_aligned!(end, layout.align());
    debug_assert_ne!(start, 0);
    debug_assert_ne!(end, 0);

    Some(start..end)
}

#[inline(always)]
pub(crate) fn bump_greedy_down(
    BumpProps {
        start,
        mut end,
        layout,
        min_align,
        align_is_const,
        size_is_const: _,
        size_is_multiple_of_align: _,
    }: BumpProps,
) -> Option<Range<usize>> {
    debug_assert!(layout.size() % layout.align() == 0);
    debug_assert!(start <= end);

    if align_is_const && layout.align() <= min_align {
        // alignment is already sufficient
    } else {
        end = down_align(end, layout.align());

        if align_is_const && layout.align() <= MIN_CHUNK_ALIGN {
            // end is valid
        } else {
            // end could be less than start at this point
            if end < start {
                return None;
            }
        }
    }

    let remaining = end - start;

    if layout.size() > remaining {
        return None;
    }

    // layout does fit, we just trim off the excess to make start aligned
    let start = up_align_unchecked(start, layout.align());

    debug_assert_aligned!(start, layout.align());
    debug_assert_aligned!(end, layout.align());
    debug_assert_ne!(start, 0);
    debug_assert_ne!(end, 0);

    Some(start..end)
}

#[inline(always)]
const fn down_align(addr: usize, align: usize) -> usize {
    debug_assert!(align.is_power_of_two());
    let mask = align - 1;
    addr & !mask
}

/// Does not check for overflow.
#[inline(always)]
const fn up_align_unchecked(addr: usize, align: usize) -> usize {
    debug_assert!(align.is_power_of_two());
    let mask = align - 1;
    (addr + mask) & !mask
}

#[inline(always)]
const fn up_align(addr: usize, align: usize) -> Option<NonZeroUsize> {
    debug_assert!(align.is_power_of_two());
    let mask = align - 1;
    let addr_plus_mask = match addr.checked_add(mask) {
        Some(addr_plus_mask) => addr_plus_mask,
        None => return None,
    };
    NonZeroUsize::new(addr_plus_mask & !mask)
}