jbig2-decoder 0.3.3

Memory-safe JBIG2 decoder under development
Documentation
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Modified Modified READ (MMR) bitmap decoding.
//!
//! This implements the T.6 two-dimensional modes and run tables with the
//! restrictions imposed by T.88 6.2.6: black is one, white is zero, extension
//! modes are forbidden, and an EOFB may be omitted only when the caller has a
//! bounded MMR data block.

// Keep normative prefix bitstrings contiguous so their encoded lengths can be
// audited directly against T.6 tables.
#![allow(clippy::unreadable_literal)]

use crate::bitmap::Bitmap;
use crate::reader::{bit_reader, BitReader};
use crate::{DecodeError, LimitExceeded, LimitKind, Limits, MalformedError, MmrErrorKind};
#[cfg(verus_keep_ghost)]
use vstd::prelude::*;
#[cfg(verus_keep_ghost)]
use vstd::std_specs::convert::FromSpecImpl;

#[cfg(verus_keep_ghost)]
#[rustfmt::skip]
#[path = "../specs/mmr.rs"]
mod mmr_spec;

#[cfg(verus_keep_ghost)]
#[rustfmt::skip]
#[path = "../proofs/shared/mmr.rs"]
mod mmr_shared;

#[cfg(verus_keep_ghost)]
#[rustfmt::skip]
#[path = "../proofs/spec_properties/mmr.rs"]
mod mmr_properties;

#[cfg(verus_keep_ghost)]
#[macro_use]
#[rustfmt::skip]
#[path = "../proofs/production_impl/mmr.rs"]
mod mmr_proofs;

#[cfg_attr(verus_keep_ghost, verus_verify)]
const EOFB: u32 = 0x00_1001;
#[cfg_attr(verus_keep_ghost, verus_verify)]
const MAX_MODE_CODE_BITS: u8 = 7;
#[cfg_attr(verus_keep_ghost, verus_verify)]
const MAX_RUN_CODE_BITS: u8 = 13;

/// Whether the enclosing JBIG2 syntax requires an end-of-facsimile-block code.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(verus_keep_ghost, verus_verify)]
pub(crate) enum EofbPolicy {
    /// T.88 requires EOFB because the encoded byte count is not otherwise known.
    Required,
    /// The input slice is the complete bounded MMR block, so EOFB is optional.
    Optional,
}

#[derive(Debug)]
#[cfg_attr(verus_keep_ghost, verus_verify)]
pub(crate) struct MmrScratch {
    pub(crate) transitions: Vec<u32>,
    pub(crate) row_transitions: Vec<u32>,
    pub(crate) retained_bytes: u64,
    #[cfg(test)]
    pub(crate) reserve_events: u64,
}

#[cfg(verus_keep_ghost)]
verus! {
    impl View for MmrScratch {
        type V = (Seq<u32>, Seq<u32>, u64);

        closed spec fn view(&self) -> Self::V {
            (self.transitions@, self.row_transitions@, self.retained_bytes)
        }
    }

    pub(crate) proof fn scratch_view_definition()
        ensures forall|scratch: &MmrScratch|
            #[trigger] scratch.view() == (
                scratch.transitions@, scratch.row_transitions@, scratch.retained_bytes,
            ),
    {
        reveal(<MmrScratch as View>::view);
    }
}

#[cfg_attr(verus_keep_ghost, verus_verify)]
impl Default for MmrScratch {
    fn default() -> Self {
        #[cfg(verus_keep_ghost)]
        ensures(|out: Self| {
            equal(
                out.view(),
                (Seq::<u32>::empty(), Seq::<u32>::empty(), 0_u64),
            )
        });
        let out = Self {
            transitions: Vec::new(),
            row_transitions: Vec::new(),
            retained_bytes: 0,
            #[cfg(test)]
            reserve_events: 0,
        };
        #[cfg(verus_keep_ghost)]
        proof! {
            reveal(<MmrScratch as View>::view);
        }
        out
    }
}

impl MmrScratch {
    #[cfg_attr(verus_keep_ghost, verus_spec(
        ensures
            final(self).transitions@.len() == 0,
            final(self).row_transitions@.len() == 0,
            final(self).retained_bytes == old(self).retained_bytes,
    ))]
    pub(crate) fn clear(&mut self) {
        self.transitions.clear();
        self.row_transitions.clear();
    }

    #[cfg_attr(verus_keep_ghost, verus_spec(
        ensures
            final(self).transitions@.len() == 0,
            final(self).row_transitions@.len() == 0,
            final(self).retained_bytes == 0,
    ))]
    pub(crate) fn release(&mut self) {
        self.transitions = Vec::new();
        self.row_transitions = Vec::new();
        self.retained_bytes = 0;
        #[cfg(test)]
        {
            self.reserve_events = 0;
        }
    }

    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
        ensures out == self.retained_bytes,
    ))]
    pub(crate) fn retained_bytes(&self) -> u64 {
        self.retained_bytes
    }
}

/// A fail-closed MMR decoding failure.
///
/// Wiring this module into the public decoder should add equivalent cases to
/// `MalformedError` rather than collapsing these distinctions.
#[derive(Debug)]
#[cfg_attr(verus_keep_ghost, verus_verify)]
pub(crate) enum MmrError {
    /// The shared bit reader rejected or exhausted the input.
    Reader(MalformedError),
    /// Bitmap allocation or a configured resource limit failed.
    Bitmap(DecodeError),
    /// Temporary transition storage could not be allocated.
    Allocation { requested_bytes: u64 },
    /// No T.6 two-dimensional mode has the encoded prefix.
    InvalidMode { bit_offset: usize },
    /// T.88 forbids all T.6 extension modes, including uncompressed mode.
    ExtensionMode { bit_offset: usize },
    /// No run code for the selected colour has the encoded prefix.
    InvalidRunCode { bit_offset: usize, black: bool },
    /// A decoded run exceeds the pixels remaining in the row.
    RunExceedsRow,
    /// A pass or vertical transition is outside the current row or moves back.
    InvalidTransition,
    /// A mode made no semantic progress and could otherwise loop forever.
    NonProgress,
    /// The number of modes exceeded a dimension-derived valid-row bound.
    TooManyModes,
    /// Required EOFB was absent or truncated.
    MissingEofb,
    /// The EOFB value was not the T.6 24-bit marker.
    InvalidEofb,
    /// More than byte-alignment padding remained after the bitmap or EOFB.
    TrailingData,
    /// T.6 requires zero-valued padding after a present EOFB.
    NonZeroEofbPadding,
    /// Input-derived arithmetic could not be represented.
    IntegerOverflow,
}

#[cfg_attr(verus_keep_ghost, verus_verify)]
impl From<MalformedError> for MmrError {
    fn from(error: MalformedError) -> Self {
        Self::Reader(error)
    }
}

#[cfg_attr(verus_keep_ghost, verus_verify)]
impl From<MmrError> for DecodeError {
    fn from(error: MmrError) -> Self {
        let kind = match error {
            MmrError::Reader(error) => return Self::Malformed(error),
            MmrError::Bitmap(error) => return error,
            MmrError::Allocation { requested_bytes } => {
                return Self::Allocation { requested_bytes };
            }
            MmrError::IntegerOverflow => return Self::Malformed(MalformedError::IntegerOverflow),
            MmrError::InvalidMode { bit_offset } => MmrErrorKind::InvalidMode { bit_offset },
            MmrError::ExtensionMode { bit_offset } => MmrErrorKind::ExtensionMode { bit_offset },
            MmrError::InvalidRunCode { bit_offset, black } => {
                MmrErrorKind::InvalidRunCode { bit_offset, black }
            }
            MmrError::RunExceedsRow => MmrErrorKind::RunExceedsRow,
            MmrError::InvalidTransition => MmrErrorKind::InvalidTransition,
            MmrError::NonProgress => MmrErrorKind::NonProgress,
            MmrError::TooManyModes => MmrErrorKind::TooManyModes,
            MmrError::MissingEofb => MmrErrorKind::MissingEofb,
            MmrError::InvalidEofb => MmrErrorKind::InvalidEofb,
            MmrError::TrailingData => MmrErrorKind::TrailingData,
            MmrError::NonZeroEofbPadding => MmrErrorKind::NonZeroPadding,
        };
        Self::Malformed(MalformedError::InvalidMmr(kind))
    }
}

#[cfg(verus_keep_ghost)]
verus! {

impl FromSpecImpl<MalformedError> for MmrError {
    open spec fn obeys_from_spec() -> bool { true }

    closed spec fn from_spec(error: MalformedError) -> MmrError {
        MmrError::Reader(error)
    }
}

// Project error policy, discharged by the executing From body through the pinned trait contract.
impl FromSpecImpl<MmrError> for DecodeError {
    open spec fn obeys_from_spec() -> bool {
        true
    }

    open spec fn from_spec(error: MmrError) -> DecodeError {
        mmr_error_result(error)
    }
}

// Keep the project mapping opaque externally; the open trait bridge exposes no private fields.
pub closed spec fn mmr_error_result(error: MmrError) -> DecodeError {
    match error {
            MmrError::Reader(error) => DecodeError::Malformed(error),
            MmrError::Bitmap(error) => error,
            MmrError::Allocation { requested_bytes } => DecodeError::Allocation { requested_bytes },
            MmrError::IntegerOverflow => DecodeError::Malformed(MalformedError::IntegerOverflow),
            MmrError::InvalidMode { bit_offset } => DecodeError::Malformed(
                MalformedError::InvalidMmr(MmrErrorKind::InvalidMode { bit_offset })),
            MmrError::ExtensionMode { bit_offset } => DecodeError::Malformed(
                MalformedError::InvalidMmr(MmrErrorKind::ExtensionMode { bit_offset })),
            MmrError::InvalidRunCode { bit_offset, black } => DecodeError::Malformed(
                MalformedError::InvalidMmr(MmrErrorKind::InvalidRunCode { bit_offset, black })),
            MmrError::RunExceedsRow => DecodeError::Malformed(
                MalformedError::InvalidMmr(MmrErrorKind::RunExceedsRow)),
            MmrError::InvalidTransition => DecodeError::Malformed(
                MalformedError::InvalidMmr(MmrErrorKind::InvalidTransition)),
            MmrError::NonProgress => DecodeError::Malformed(
                MalformedError::InvalidMmr(MmrErrorKind::NonProgress)),
            MmrError::TooManyModes => DecodeError::Malformed(
                MalformedError::InvalidMmr(MmrErrorKind::TooManyModes)),
            MmrError::MissingEofb => DecodeError::Malformed(
                MalformedError::InvalidMmr(MmrErrorKind::MissingEofb)),
            MmrError::InvalidEofb => DecodeError::Malformed(
                MalformedError::InvalidMmr(MmrErrorKind::InvalidEofb)),
            MmrError::TrailingData => DecodeError::Malformed(
                MalformedError::InvalidMmr(MmrErrorKind::TrailingData)),
            MmrError::NonZeroEofbPadding => DecodeError::Malformed(
                MalformedError::InvalidMmr(MmrErrorKind::NonZeroPadding)),
    }
}

}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(verus_keep_ghost, verus_verify)]
enum Mode {
    Pass,
    Horizontal,
    Vertical(i8),
    Extension,
}

#[derive(Debug, Clone, Copy)]
#[cfg_attr(verus_keep_ghost, verus_verify)]
struct ModeCode {
    bits: u16,
    length: u8,
    mode: Mode,
}

impl ModeCode {
    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
        ensures out.bits == bits, out.length == length, out.mode == mode,
    ))]
    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
    const fn new(bits: u16, length: u8, mode: Mode) -> Self {
        Self { bits, length, mode }
    }
}

#[derive(Debug, Clone, Copy)]
#[cfg_attr(verus_keep_ghost, verus_verify)]
struct RunCode {
    bits: u16,
    length: u8,
    value: u16,
    terminal: bool,
}

impl RunCode {
    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
        ensures
            out.bits == bits,
            out.length == length,
            out.value == value,
            out.terminal,
    ))]
    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
    const fn terminal(value: u16, bits: u16, length: u8) -> Self {
        Self {
            bits,
            length,
            value,
            terminal: true,
        }
    }

    #[cfg_attr(verus_keep_ghost, verus_spec(out =>
        ensures
            out.bits == bits,
            out.length == length,
            out.value == value,
            !out.terminal,
    ))]
    #[cfg_attr(verus_keep_ghost, allow(unused, verus_impl_method_marker))]
    const fn makeup(value: u16, bits: u16, length: u8) -> Self {
        Self {
            bits,
            length,
            value,
            terminal: false,
        }
    }
}

/// Decode one complete, byte-bounded JBIG2 MMR bitmap.
///
/// `data` must contain exactly the MMR data block, including any optional or
/// required EOFB and final byte-alignment bits.
#[cfg_attr(verus_keep_ghost, verus_spec(out =>
    ensures match out {
        Ok(bitmap) => crate::spec::bitmap::storage_valid(&bitmap)
            && mmr_spec::bounded_bitmap_decodes(
                data@, width, height, &bitmap, eofb_policy,
            ),
        Err(_) => true,
    },
))]
pub(crate) fn decode_mmr(
    data: &[u8],
    width: u32,
    height: u32,
    limits: &Limits,
    eofb_policy: EofbPolicy,
) -> Result<Bitmap, MmrError> {
    let mut scratch = MmrScratch::default();
    decode_mmr_reused(data, width, height, limits, eofb_policy, &mut scratch)
}

#[cfg_attr(verus_keep_ghost, verus_spec(out =>
    ensures match out {
        Ok(bitmap) => crate::spec::bitmap::storage_valid(&bitmap)
            && mmr_spec::bounded_bitmap_decodes(
                data@, width, height, &bitmap, eofb_policy,
            ),
        Err(_) => true,
    },
))]
pub(crate) fn decode_mmr_reused(
    data: &[u8],
    width: u32,
    height: u32,
    limits: &Limits,
    eofb_policy: EofbPolicy,
    scratch: &mut MmrScratch,
) -> Result<Bitmap, MmrError> {
    let result = decode_bitmap(data, width, height, limits, scratch);
    let (bitmap, mut reader) = match result {
        Ok(value) => value,
        Err(error) => {
            scratch.clear();
            return Err(error);
        }
    };
    #[cfg(verus_keep_ghost)]
    proof_decl! { let ghost decoded_end = reader.bit_position as nat; }
    let finish = finish_block(&mut reader, eofb_policy);
    scratch.clear();
    finish?;
    #[cfg(verus_keep_ghost)]
    proof! {
        assert(mmr_spec::bitmap_decodes(data@, width, height, &bitmap, decoded_end));
        mmr_spec::bounded_bitmap_witness(
            data@, width, height, &bitmap, eofb_policy, decoded_end,
        );
    }
    Ok(bitmap)
}

/// Decode one EOFB-terminated MMR bitmap at the start of `data`.
///
/// Unlike [`decode_mmr`], this accepts bytes after the decoded bitmap. It
/// requires an exact EOFB immediately after the declared rows, requires every
/// bit between EOFB and the next byte boundary to be zero, and returns that
/// byte boundary as `consumed_bytes`. A caller can decode a following bitplane
/// from `&data[consumed_bytes..]`.
#[cfg_attr(verus_keep_ghost, verus_spec(out =>
    ensures match out {
        Ok((bitmap, consumed_bytes)) =>
            crate::spec::bitmap::storage_valid(&bitmap)
            && consumed_bytes <= data@.len()
            && mmr_spec::prefix_bitmap_decodes(
                data@, width, height, &bitmap, consumed_bytes,
            ),
        Err(_) => true,
    },
))]
pub(crate) fn decode_mmr_prefix(
    data: &[u8],
    width: u32,
    height: u32,
    limits: &Limits,
) -> Result<(Bitmap, usize), MmrError> {
    let mut scratch = MmrScratch::default();
    let (bitmap, mut reader) = decode_bitmap(data, width, height, limits, &mut scratch)?;
    #[cfg(verus_keep_ghost)]
    proof_decl! { let ghost decoded_end = reader.bit_position as nat; }
    let finish = finish_required_prefix(&mut reader);
    scratch.clear();
    finish?;
    let consumed_bytes = reader
        .bit_position
        .checked_div(8)
        .ok_or(MmrError::IntegerOverflow)?;
    #[cfg(verus_keep_ghost)]
    proof! {
        assert(mmr_spec::bitmap_decodes(data@, width, height, &bitmap, decoded_end));
        assert(consumed_bytes as nat * 8 == reader.bit_position as nat);
        mmr_spec::prefix_bitmap_witness(
            data@, width, height, &bitmap, decoded_end, consumed_bytes,
        );
    }
    Ok((bitmap, consumed_bytes))
}

mod codes;
mod luts;
mod memory;
mod raster;
mod reference;
mod spans;
mod tables;
mod termination;

#[cfg(test)]
use spans::collect_transitions;
// Private aliases also serve cfg-gated proof and test callers.
#[allow(unused_imports)]
use self::{
    codes::{
        append_code_bit, decode_horizontal_runs, decode_mode, decode_run, decode_run_code,
        find_run_code,
    },
    memory::{
        enforce_input_limit, enforce_work, observed_transition_bytes, prepare_transition_storage,
    },
    raster::decode_bitmap,
    reference::{reference_elements, reference_elements_from},
    spans::{fill_recorded_span, fill_span, finish_transition_row, record_transition_span},
    tables::{
        BLACK_MAKEUP, BLACK_TERMINATING, COMMON_MAKEUP, MODE_CODES, WHITE_MAKEUP, WHITE_TERMINATING,
    },
    termination::{finish_block, finish_required_prefix, remaining_bits},
};

#[cfg(test)]
mod tests;