fix(engine): reserve the define-brush tip and selection-mask buffers fallibly (#212) (#5469)

brush.defineFromSelection allocated the sampled tip and the selection mask infallibly over the whole selection, so a large selection could abort the process. Both now go through the engine's fallible allocator and return a normal error that leaves the brush, presets, history and document untouched. A failpoint test asserts all four.

Part of #212.
This commit is contained in:
wwew authored and GitHub committed 2026-10-16 17:23:08 -07:00
1 parent aecac608b4
commit dd69f0797d
2 files changed
+26 -2

No files matched your search

+6 -2
View File
@@ -863,9 +863,13 @@ fn define_from_selection(s: &mut Session, p: &Value) -> Result<Value> {
}
// Paint amount = darkness × alpha × selection (black = full paint, like Photoshop).
let (w, h) = (area.width() as usize, area.height() as usize);
let mut v = vec![0.0f32; w * h];
// The sampled tip is one f32 buffer over the whole selection; a large selection must fail
// gracefully instead of aborting the process on allocation, so reserve it fallibly.
let mut v = crate::allocation::filled(w * h, 0.0, "defining a brush from the selection")?;
let sc = sel.channels();
let sv = sel.read_region(area);
// The selection mask is a second buffer of the same size; it must fail gracefully too
// (review of #5469), so read it through the fallible allocator.
let sv = crate::allocation::read_region(sel, area, "defining a brush from the selection")?;
for y in 0..h {
for x in 0..w {
let c = surf.rgba(area.x0 + x as i32, area.y0 + y as i32);
+20
View File
@@ -442,6 +442,26 @@ fn define_brush_from_selection() {
assert!(rgba(&s, 30, 32)[3] > 0.9);
}
#[test]
fn define_brush_from_selection_survives_allocation_failure() {
// The sampled tip is one f32 buffer over the whole selection, and the selection mask is a
// second of the same size. Both are reserved through the fallible allocator, so an allocation
// failure must be a graceful error (brush, presets, history and document untouched), never a
// panic or an OOM abort.
let mut s = session(40, 40);
s.execute("select.rect", json!({"x": 5, "y": 5, "width": 20, "height": 20})).unwrap();
let brush_before = s.tools.brush.clone();
let presets_before = s.tools.presets.clone();
let history_before = s.active().unwrap().history.past_len();
crate::allocation::fail_next_for_test();
let result = s.execute("brush.defineFromSelection", json!({"name": "Blob"}));
let _ = crate::allocation::capacity::<u8>(0, "reset failpoint");
assert!(result.is_err(), "an allocation failure must be reported, not panic");
assert_eq!(s.tools.brush, brush_before, "the current brush is unchanged");
assert_eq!(s.tools.presets, presets_before, "the preset list is unchanged");
assert_eq!(s.active().unwrap().history.past_len(), history_before, "no history step was recorded");
}
#[test]
fn works_on_cmyk_and_16_bit() {
for (mode, depth) in [("cmyk", 8), ("rgb", 16), ("grayscale", 32)] {