Skip to main content

brotli_decompressor/
shared_dictionary.rs

1#![allow(non_snake_case)]
2#![allow(non_upper_case_globals)]
3#![allow(non_camel_case_types)]
4
5// Port of the shared-brotli serialized dictionary format
6// (https://datatracker.ietf.org/doc/draft-vandevenne-shared-brotli-format/)
7// from c/common/shared_dictionary.c in the reference implementation.
8//
9// A serialized dictionary may carry an LZ77 prefix dictionary (which becomes
10// a compound dictionary chunk, see state.rs), plus optional custom word lists
11// and transform lists that replace or augment the built-in static dictionary,
12// optionally selected per-literal-context through a 64-entry context map.
13
14use core;
15use alloc;
16use alloc::{Allocator, SliceWrapper, SliceWrapperMut};
17use bit_reader;
18use dictionary::{kBrotliDictionary, kBrotliDictionaryOffsetsByLength, kBrotliDictionarySizeBitsByLength,
19                 kBrotliMaxDictionaryWordLength};
20use state;
21use transform::{kNumTransforms, TransformDictionaryWord, ToUpperCase};
22
23pub const SHARED_BROTLI_MIN_DICTIONARY_WORD_LENGTH: u32 = 4;
24pub const SHARED_BROTLI_MAX_DICTIONARY_WORD_LENGTH: u32 = 31;
25// Longest prefix or suffix a transform can prepend/append to a dictionary
26// word. Custom affixes come from the transform list's prefix/suffix table as
27// "stringlets", each stored as a single length byte followed by that many
28// bytes, so 255 is the hard maximum. The built-in transform list
29// (transform.rs) only ever uses 5-byte prefixes and 8-byte suffixes;
30// serialized shared dictionaries may use the full range.
31pub const SHARED_BROTLI_MAX_TRANSFORM_AFFIX_LENGTH: u32 = 255;
32pub const SHARED_BROTLI_NUM_DICTIONARY_CONTEXTS: usize = 64;
33// Max allowed by spec for custom word list size bits.
34const BROTLI_MAX_SIZE_BITS: u8 = 15;
35
36// Transform types beyond the ones used by the built-in transform list
37// (see transform.rs for 0..=20).
38pub const BROTLI_TRANSFORM_SHIFT_FIRST: u8 = 21;
39pub const BROTLI_TRANSFORM_SHIFT_ALL: u8 = 22;
40pub const BROTLI_NUM_TRANSFORM_TYPES: u8 = 23;
41const BROTLI_TRANSFORM_OMIT_LAST_9: u8 = 9;
42const BROTLI_TRANSFORM_UPPERCASE_FIRST: u8 = 10;
43const BROTLI_TRANSFORM_UPPERCASE_ALL: u8 = 11;
44const BROTLI_TRANSFORM_OMIT_FIRST_1: u8 = 12;
45const BROTLI_TRANSFORM_OMIT_FIRST_9: u8 = 20;
46
47// Parsed word lists and transform lists are packed into a single u32 arena
48// so that they can be stored with the decoder's existing u32 allocator (this
49// crate runs without a global allocator). Word list i occupies the
50// WORD_LIST_STRIDE u32s starting at i * WORD_LIST_STRIDE; transform list j
51// occupies the TRANSFORM_LIST_STRIDE u32s starting at
52// num_word_lists * WORD_LIST_STRIDE + j * TRANSFORM_LIST_STRIDE.
53//
54// Word list layout (indexes within its stride):
55//   0..8    size_bits_by_length for lengths 0..32, one byte per length
56//   8..40   offsets_by_length for lengths 0..32
57//   40      offset of the concatenated word data within the blob
58pub(crate) const WORD_LIST_STRIDE: usize = 41;
59const WL_SIZE_BITS: usize = 0;
60const WL_OFFSETS: usize = 8;
61const WL_DATA_OFFSET: usize = 40;
62// Transform list layout:
63//   0       num_transforms (0..=255)
64//   1       offset of the 3*num_transforms transform triplets in the blob
65//   2       offset of the 2*num_transforms SHIFT parameters, or u32::MAX
66//   3       offset of the prefix/suffix stringlet region in the blob
67//   4       cutOffTransforms[0] (index of ["", IDENTITY, ""]) as i16, or -1
68//   5..133  prefix_suffix_map: 256 u16 offsets, two per u32, little-end first
69pub(crate) const TRANSFORM_LIST_STRIDE: usize = 133;
70const TL_NUM_TRANSFORMS: usize = 0;
71const TL_TRANSFORMS_OFFSET: usize = 1;
72const TL_PARAMS_OFFSET: usize = 2;
73const TL_PREFIX_SUFFIX_OFFSET: usize = 3;
74const TL_CUTOFF_IDENTITY: usize = 4;
75const TL_PREFIX_SUFFIX_MAP: usize = 5;
76
77// Byte layout of one entry in a serialized TRANSFORMS_LIST, and the ONLY place
78// in this crate that knows it. Validation, the identity-cutoff scan and the
79// decode-time lookup all go through transform_triplet_at.
80//
81// SPEC DISCREPANCY -- read before "fixing" this:
82//   draft-vandevenne-shared-brotli-format describes each transform as
83//     1 byte: index of prefix in prefix/suffix data
84//     1 byte: index of suffix in prefix/suffix data
85//     1 byte: operation index
86//   i.e. PREFIX_ID, SUFFIX_ID, TYPE. The reference C implementation instead
87//   reads PREFIX_ID, TYPE, SUFFIX_ID:
88//     #define BROTLI_TRANSFORM_PREFIX_ID(T, I) ((T)->transforms[((I) * 3) + 0])
89//     #define BROTLI_TRANSFORM_TYPE(T, I)      ((T)->transforms[((I) * 3) + 1])
90//     #define BROTLI_TRANSFORM_SUFFIX_ID(T, I) ((T)->transforms[((I) * 3) + 2])
91//   (c/common/transform.h:65-67, used by ParseTransformsList and by the
92//   encoder that writes these dictionaries).
93//
94// This port follows the C implementation, because that is what actually
95// produces and consumes serialized dictionaries in practice. Following the
96// draft instead would reject dictionaries the reference encoder emits, and --
97// worse -- would silently mis-apply any transform whose type byte and suffix
98// id are each in range for the other's field, with no error to show for it.
99// Switching to the draft's order is therefore a one-line edit to the
100// constructor below, and nothing else: callers name the fields, so none of
101// them encodes a byte position.
102const TRANSFORM_TRIPLET_SIZE: usize = 3;
103
104#[derive(Clone, Copy)]
105struct TransformTriplet {
106  prefix_id: u8,
107  transform_type: u8,
108  suffix_id: u8,
109}
110
111// Decodes transform `idx` of the list whose triplets begin at byte `base` of
112// `data`. The three field assignments here are the entire definition of the
113// on-the-wire order.
114fn transform_triplet_at(data: &[u8], base: usize, idx: usize) -> TransformTriplet {
115  let offset = base + idx * TRANSFORM_TRIPLET_SIZE;
116  TransformTriplet {
117    prefix_id: data[offset],
118    transform_type: data[offset + 1],
119    suffix_id: data[offset + 2],
120  }
121}
122
123pub struct BrotliSharedDictionary<AllocU8: alloc::Allocator<u8>,
124                                  AllocU32: alloc::Allocator<u32>> {
125  // If set, the context map selects the dictionary for each word, from the
126  // 64 literal contexts; if not set only dictionary 0 is used.
127  pub context_based: bool,
128  pub num_dictionaries: u8,
129  pub num_word_lists: u8,
130  pub num_transform_lists: u8,
131  pub context_map: [u8; SHARED_BROTLI_NUM_DICTIONARY_CONTEXTS],
132  // Per dictionary: index of its word list, or num_word_lists for the
133  // built-in word list.
134  pub words_index: [u8; SHARED_BROTLI_NUM_DICTIONARY_CONTEXTS],
135  // Per dictionary: index of its transform list, or num_transform_lists for
136  // the built-in transform list.
137  pub transforms_index: [u8; SHARED_BROTLI_NUM_DICTIONARY_CONTEXTS],
138  // The serialized dictionary; word data, stringlets, transform triplets and
139  // parameters are referenced by offset into this buffer.
140  pub blob: state::MaybeOwnedSlice<AllocU8>,
141  // The parsed word list / transform list arena described above.
142  pub meta: AllocU32::AllocatedMemory,
143}
144
145impl<AllocU8: alloc::Allocator<u8>,
146     AllocU32: alloc::Allocator<u32>> Default for BrotliSharedDictionary<AllocU8, AllocU32> {
147  fn default() -> Self {
148    BrotliSharedDictionary::<AllocU8, AllocU32> {
149      context_based: false,
150      num_dictionaries: 1,
151      num_word_lists: 0,
152      num_transform_lists: 0,
153      context_map: [0; SHARED_BROTLI_NUM_DICTIONARY_CONTEXTS],
154      words_index: [0; SHARED_BROTLI_NUM_DICTIONARY_CONTEXTS],
155      transforms_index: [0; SHARED_BROTLI_NUM_DICTIONARY_CONTEXTS],
156      blob: state::MaybeOwnedSlice::default(),
157      meta: AllocU32::AllocatedMemory::default(),
158    }
159  }
160}
161
162impl<AllocU8: alloc::Allocator<u8>,
163     AllocU32: alloc::Allocator<u32>> BrotliSharedDictionary<AllocU8, AllocU32> {
164  // True if a custom word list or transform list replaces the built-in
165  // static dictionary; the decoder then takes the generalized lookup path.
166  pub(crate) fn is_custom(&self) -> bool {
167    self.num_word_lists != 0 || self.num_transform_lists != 0
168  }
169  pub(crate) fn words_of(&self, dict_id: u8) -> DictWords<'_> {
170    let index = self.words_index[dict_id as usize];
171    if index >= self.num_word_lists {
172      DictWords::Builtin
173    } else {
174      let start = index as usize * WORD_LIST_STRIDE;
175      DictWords::Custom(CustomWords {
176        meta: &self.meta.slice()[start..start + WORD_LIST_STRIDE],
177        blob: self.blob.slice(),
178      })
179    }
180  }
181  // Resolves `address` in the flat dictionary address space to the word and
182  // transform that own it, for a word of length `len`.
183  //
184  // The space is partitioned across the dictionaries: each owns a contiguous
185  // run of ((1 << shift) & !1) * num_transforms addresses, which is zero when
186  // its word list cannot encode `len` at all (shift == 0). They are searched
187  // in the order the format prescribes -- `dict_id` first, then the rest by
188  // index -- with `remaining` walking past the runs the address is not in.
189  //
190  // c/dec/decode.c writes this as a first lookup plus a separate rescan loop
191  // that re-derives the same quantities; this is that arithmetic stated once.
192  // The reference's `transform_idx >= num_transforms` test is exactly
193  // `remaining >= count` for the first candidate, and its two post-lookup
194  // guards need no counterpart here: a candidate is selected only when
195  // remaining < count, which for count > 0 forces shift >= 1 and
196  // transform_idx < num_transforms.
197  pub(crate) fn lookup(&self, dict_id: u8, len: i32, address: i32)
198      -> Result<DictionaryLookup<'_>, DictionaryLookupError> {
199    let mut remaining = address;
200    for candidate in core::iter::once(dict_id)
201        .chain((0..self.num_dictionaries).filter(|&d| d != dict_id)) {
202      let words = self.words_of(candidate);
203      let shift = words.size_bits_by_length(len) as u32;
204      let transforms = self.transforms_of(candidate);
205      let count = (((1u32 << shift) & !1u32) as i32) * transforms.num_transforms();
206      if remaining < count {
207        return Ok(DictionaryLookup {
208          words: words,
209          transforms: transforms,
210          word_idx: remaining & bit_reader::BitMask(shift) as i32,
211          transform_idx: remaining >> shift,
212        });
213      }
214      remaining -= count;
215    }
216    Err(if self.words_of(dict_id).size_bits_by_length(len) == 0 {
217      DictionaryLookupError::LengthNotEncodable
218    } else {
219      DictionaryLookupError::AddressOutOfRange
220    })
221  }
222  pub(crate) fn transforms_of(&self, dict_id: u8) -> DictTransforms<'_> {
223    let index = self.transforms_index[dict_id as usize];
224    if index >= self.num_transform_lists {
225      DictTransforms::Builtin
226    } else {
227      let start = self.num_word_lists as usize * WORD_LIST_STRIDE +
228                  index as usize * TRANSFORM_LIST_STRIDE;
229      DictTransforms::Custom(CustomTransforms {
230        meta: &self.meta.slice()[start..start + TRANSFORM_LIST_STRIDE],
231        blob: self.blob.slice(),
232      })
233    }
234  }
235}
236
237#[derive(Clone, Copy)]
238pub(crate) struct CustomWords<'a> {
239  meta: &'a [u32],
240  blob: &'a [u8],
241}
242
243impl<'a> CustomWords<'a> {
244  fn size_bits_by_length(&self, len: i32) -> u8 {
245    (self.meta[WL_SIZE_BITS + (len >> 2) as usize] >> ((len & 3) * 8)) as u8
246  }
247  fn word(&self, len: i32, word_idx: i32) -> &'a [u8] {
248    let offset = self.meta[WL_DATA_OFFSET] as usize +
249                 self.meta[WL_OFFSETS + len as usize] as usize +
250                 (word_idx * len) as usize;
251    &self.blob[offset..offset + len as usize]
252  }
253}
254
255// Which word list and transform list own a dictionary-space address, and the
256// indices within them. Named fields on purpose: nothing outside this file
257// should have to remember an order.
258pub(crate) struct DictionaryLookup<'a> {
259  pub(crate) words: DictWords<'a>,
260  pub(crate) transforms: DictTransforms<'a>,
261  pub(crate) word_idx: i32,
262  pub(crate) transform_idx: i32,
263}
264
265// Why an address resolved to no dictionary at all. The two cases map to the
266// two distinct format errors the reference implementation reports.
267#[derive(Clone, Copy)]
268pub(crate) enum DictionaryLookupError {
269  // The context-selected dictionary's word list cannot encode this length.
270  LengthNotEncodable,
271  // The address runs past the end of every candidate's transforms.
272  AddressOutOfRange,
273}
274
275#[derive(Clone, Copy)]
276pub(crate) enum DictWords<'a> {
277  Builtin,
278  Custom(CustomWords<'a>),
279}
280
281impl<'a> DictWords<'a> {
282  pub(crate) fn size_bits_by_length(&self, len: i32) -> u8 {
283    match *self {
284      DictWords::Builtin => {
285        if len as u32 > kBrotliMaxDictionaryWordLength as u32 {
286          0
287        } else {
288          kBrotliDictionarySizeBitsByLength[len as usize]
289        }
290      }
291      DictWords::Custom(ref words) => words.size_bits_by_length(len),
292    }
293  }
294  pub(crate) fn word(&self, len: i32, word_idx: i32) -> &'a [u8] {
295    match *self {
296      DictWords::Builtin => {
297        let offset = kBrotliDictionaryOffsetsByLength[len as usize] as usize +
298                     (word_idx * len) as usize;
299        &kBrotliDictionary[offset..offset + len as usize]
300      }
301      DictWords::Custom(ref words) => words.word(len, word_idx),
302    }
303  }
304}
305
306#[derive(Clone, Copy)]
307pub(crate) struct CustomTransforms<'a> {
308  meta: &'a [u32],
309  blob: &'a [u8],
310}
311
312impl<'a> CustomTransforms<'a> {
313  fn num_transforms(&self) -> i32 {
314    self.meta[TL_NUM_TRANSFORMS] as i32
315  }
316  fn cutoff_identity(&self) -> i32 {
317    self.meta[TL_CUTOFF_IDENTITY] as i32 as i16 as i32
318  }
319  fn stringlet(&self, id: u8) -> &'a [u8] {
320    let map_entry = self.meta[TL_PREFIX_SUFFIX_MAP + (id >> 1) as usize] >> ((id & 1) * 16);
321    let offset = self.meta[TL_PREFIX_SUFFIX_OFFSET] as usize + (map_entry as u16) as usize;
322    let len = self.blob[offset] as usize;
323    &self.blob[offset + 1..offset + 1 + len]
324  }
325  fn transform_triplet(&self, idx: i32) -> TransformTriplet {
326    transform_triplet_at(self.blob, self.meta[TL_TRANSFORMS_OFFSET] as usize, idx as usize)
327  }
328  fn param(&self, idx: i32) -> u16 {
329    let offset = self.meta[TL_PARAMS_OFFSET] as usize + (idx as usize) * 2;
330    self.blob[offset] as u16 | ((self.blob[offset + 1] as u16) << 8)
331  }
332  fn apply(&self, dst: &mut [u8], mut word: &[u8], mut len: i32, transform_idx: i32) -> i32 {
333    let triplet = self.transform_triplet(transform_idx);
334    let t = triplet.transform_type;
335    let mut idx: usize = 0;
336    for &b in self.stringlet(triplet.prefix_id).iter() {
337      dst[idx] = b;
338      idx += 1;
339    }
340    {
341      if t <= BROTLI_TRANSFORM_OMIT_LAST_9 {
342        len -= t as i32;
343      } else if t >= BROTLI_TRANSFORM_OMIT_FIRST_1 && t <= BROTLI_TRANSFORM_OMIT_FIRST_9 {
344        let skip = (t - (BROTLI_TRANSFORM_OMIT_FIRST_1 - 1)) as i32;
345        if skip > len {
346          // cannot happen for valid words (len >= 4) but keep safe
347          len = 0;
348        } else {
349          word = &word[skip as usize..];
350          len -= skip;
351        }
352      }
353      let mut i: usize = 0;
354      while (i as i32) < len {
355        dst[idx] = word[i];
356        idx += 1;
357        i += 1;
358      }
359      if len > 0 {
360        let transformed = &mut dst[idx - len as usize..];
361        if t == BROTLI_TRANSFORM_UPPERCASE_FIRST {
362          ToUpperCase(transformed);
363        } else if t == BROTLI_TRANSFORM_UPPERCASE_ALL {
364          let mut offset: usize = 0;
365          let mut remaining = len;
366          while remaining > 0 {
367            let step = ToUpperCase(&mut transformed[offset..]);
368            offset += step as usize;
369            remaining -= step;
370          }
371        } else if t == BROTLI_TRANSFORM_SHIFT_FIRST {
372          let param = self.param(transform_idx);
373          Shift(transformed, len, param);
374        } else if t == BROTLI_TRANSFORM_SHIFT_ALL {
375          let param = self.param(transform_idx);
376          let mut offset: usize = 0;
377          let mut remaining = len;
378          while remaining > 0 {
379            let step = Shift(&mut transformed[offset..], remaining, param);
380            offset += step as usize;
381            remaining -= step;
382          }
383        }
384      }
385    }
386    for &b in self.stringlet(triplet.suffix_id).iter() {
387      dst[idx] = b;
388      idx += 1;
389    }
390    idx as i32
391  }
392}
393
394#[derive(Clone, Copy)]
395pub(crate) enum DictTransforms<'a> {
396  Builtin,
397  Custom(CustomTransforms<'a>),
398}
399
400impl<'a> DictTransforms<'a> {
401  pub(crate) fn num_transforms(&self) -> i32 {
402    match *self {
403      DictTransforms::Builtin => kNumTransforms,
404      DictTransforms::Custom(ref transforms) => transforms.num_transforms(),
405    }
406  }
407  // The transform index that is ["", IDENTITY, ""] (plain copy), or -1.
408  pub(crate) fn cutoff_identity(&self) -> i32 {
409    match *self {
410      DictTransforms::Builtin => 0,
411      DictTransforms::Custom(ref transforms) => transforms.cutoff_identity(),
412    }
413  }
414  pub(crate) fn apply(&self, dst: &mut [u8], word: &[u8], len: i32, transform_idx: i32) -> i32 {
415    match *self {
416      DictTransforms::Builtin => TransformDictionaryWord(dst, word, len, transform_idx),
417      DictTransforms::Custom(ref transforms) => transforms.apply(dst, word, len, transform_idx),
418    }
419  }
420}
421
422// UTF-8-aware scalar shift, used by the SHIFT_FIRST and SHIFT_ALL transforms;
423// direct port of Shift() in c/common/transform.c.
424fn Shift(word: &mut [u8], word_len: i32, parameter: u16) -> i32 {
425  // Limited sign extension: scalar < (1 << 24).
426  let mut scalar: u32 = (parameter as u32 & 0x7FFF).wrapping_add(0x1000000 - (parameter as u32 & 0x8000));
427  if word[0] < 0x80 {
428    // 1-byte rune / 0sssssss / 7 bit scalar (ASCII).
429    scalar = scalar.wrapping_add(word[0] as u32);
430    word[0] = (scalar & 0x7F) as u8;
431    1
432  } else if word[0] < 0xC0 {
433    // Continuation / 10AAAAAA.
434    1
435  } else if word[0] < 0xE0 {
436    // 2-byte rune / 110sssss AAssssss / 11 bit scalar.
437    if word_len < 2 {
438      return 1;
439    }
440    scalar = scalar.wrapping_add((word[1] as u32 & 0x3F) | ((word[0] as u32 & 0x1F) << 6));
441    word[0] = (0xC0 | ((scalar >> 6) & 0x1F)) as u8;
442    word[1] = ((word[1] as u32 & 0xC0) | (scalar & 0x3F)) as u8;
443    2
444  } else if word[0] < 0xF0 {
445    // 3-byte rune / 1110ssss AAssssss BBssssss / 16 bit scalar.
446    if word_len < 3 {
447      return word_len;
448    }
449    scalar = scalar.wrapping_add((word[2] as u32 & 0x3F) | ((word[1] as u32 & 0x3F) << 6) |
450                                 ((word[0] as u32 & 0x0F) << 12));
451    word[0] = (0xE0 | ((scalar >> 12) & 0x0F)) as u8;
452    word[1] = ((word[1] as u32 & 0xC0) | ((scalar >> 6) & 0x3F)) as u8;
453    word[2] = ((word[2] as u32 & 0xC0) | (scalar & 0x3F)) as u8;
454    3
455  } else if word[0] < 0xF8 {
456    // 4-byte rune / 11110sss AAssssss BBssssss CCssssss / 21 bit scalar.
457    if word_len < 4 {
458      return word_len;
459    }
460    scalar = scalar.wrapping_add((word[3] as u32 & 0x3F) | ((word[2] as u32 & 0x3F) << 6) |
461                                 ((word[1] as u32 & 0x3F) << 12) |
462                                 ((word[0] as u32 & 0x07) << 18));
463    word[0] = (0xF0 | ((scalar >> 18) & 0x07)) as u8;
464    word[1] = ((word[1] as u32 & 0xC0) | ((scalar >> 12) & 0x3F)) as u8;
465    word[2] = ((word[2] as u32 & 0xC0) | ((scalar >> 6) & 0x3F)) as u8;
466    word[3] = ((word[3] as u32 & 0xC0) | (scalar & 0x3F)) as u8;
467    4
468  } else {
469    1
470  }
471}
472
473// ---------------------------------------------------------------------------
474// Serialized format parsing.
475
476struct Reader<'a> {
477  data: &'a [u8],
478  pos: usize,
479}
480
481impl<'a> Reader<'a> {
482  fn read_u8(&mut self) -> Result<u8, ()> {
483    if self.pos >= self.data.len() {
484      return Err(());
485    }
486    let v = self.data[self.pos];
487    self.pos += 1;
488    Ok(v)
489  }
490  fn read_bool(&mut self) -> Result<bool, ()> {
491    match self.read_u8()? {
492      0 => Ok(false),
493      1 => Ok(true),
494      _ => Err(()),
495    }
496  }
497  fn read_u16(&mut self) -> Result<u16, ()> {
498    if self.pos + 2 > self.data.len() {
499      return Err(());
500    }
501    let v = self.data[self.pos] as u16 | ((self.data[self.pos + 1] as u16) << 8);
502    self.pos += 2;
503    Ok(v)
504  }
505  // Reads a varint into a u32, erroring if it is too large.
506  fn read_varint32(&mut self) -> Result<u32, ()> {
507    let mut result: u32 = 0;
508    let mut num = 0;
509    loop {
510      let byte = self.read_u8()?;
511      if num == 4 && byte > 15 {
512        return Err(());
513      }
514      result |= ((byte & 127) as u32) << (num * 7);
515      if byte < 128 {
516        return Ok(result);
517      }
518      num += 1;
519    }
520  }
521}
522
523// Walks one word list. If `out` is provided, fills its WORD_LIST_STRIDE u32s.
524fn parse_word_list(reader: &mut Reader, mut out: Option<&mut [u32]>) -> Result<(), ()> {
525  if let Some(ref mut meta) = out {
526    for entry in meta.iter_mut() {
527      *entry = 0;
528    }
529  }
530  let num_encoded_lengths = (SHARED_BROTLI_MAX_DICTIONARY_WORD_LENGTH -
531                             SHARED_BROTLI_MIN_DICTIONARY_WORD_LENGTH + 1) as usize;
532  if reader.pos + num_encoded_lengths > reader.data.len() {
533    return Err(());
534  }
535  let mut size_bits = [0u8; (SHARED_BROTLI_MAX_DICTIONARY_WORD_LENGTH + 1) as usize];
536  for i in 0..num_encoded_lengths {
537    let bits = reader.data[reader.pos + i];
538    if bits > BROTLI_MAX_SIZE_BITS {
539      return Err(());
540    }
541    size_bits[SHARED_BROTLI_MIN_DICTIONARY_WORD_LENGTH as usize + i] = bits;
542  }
543  reader.pos += num_encoded_lengths;
544  let mut total: u32 = 0;
545  if let Some(ref mut meta) = out {
546    meta[WL_DATA_OFFSET] = reader.pos as u32;
547  }
548  for (i, &bits) in size_bits.iter().enumerate() {
549    if let Some(ref mut meta) = out {
550      meta[WL_SIZE_BITS + (i >> 2)] |= (bits as u32) << ((i & 3) * 8);
551      meta[WL_OFFSETS + i] = total;
552    }
553    if bits != 0 {
554      total += (i as u32) << bits;
555    }
556  }
557  if reader.pos + total as usize > reader.data.len() {
558    return Err(());
559  }
560  reader.pos += total as usize;
561  Ok(())
562}
563
564// Walks the prefix/suffix stringlet table of one transform list. If `out` is
565// provided, fills TL_PREFIX_SUFFIX_OFFSET and the prefix_suffix_map entries.
566// Returns the number of stringlets.
567fn parse_prefix_suffix_table(reader: &mut Reader, mut out: Option<&mut [u32]>) -> Result<usize, ()> {
568  let data_length = reader.read_u16()? as usize;
569  // Must at least have space for the null terminator.
570  if data_length < 1 {
571    return Err(());
572  }
573  if reader.pos + data_length >= reader.data.len() {
574    return Err(());
575  }
576  if let Some(ref mut meta) = out {
577    meta[TL_PREFIX_SUFFIX_OFFSET] = reader.pos as u32;
578  }
579  let mut offset: usize = 0;
580  let mut stringlet_count: usize = 0;
581  loop {
582    let stringlet_len = reader.data[reader.pos + offset] as usize;
583    if let Some(ref mut meta) = out {
584      meta[TL_PREFIX_SUFFIX_MAP + (stringlet_count >> 1)] |=
585        (offset as u32) << ((stringlet_count & 1) * 16);
586    }
587    stringlet_count += 1;
588    offset += 1;
589    if stringlet_len == 0 {
590      if offset == data_length {
591        break;
592      } else {
593        return Err(());
594      }
595    }
596    if stringlet_count > 255 {
597      return Err(());
598    }
599    offset += stringlet_len;
600    if offset >= data_length {
601      return Err(());
602    }
603  }
604  reader.pos += data_length;
605  Ok(stringlet_count)
606}
607
608// Walks one transform list. If `out` is provided, fills its
609// TRANSFORM_LIST_STRIDE u32s including the identity cutoff.
610fn parse_transforms_list(reader: &mut Reader, mut out: Option<&mut [u32]>) -> Result<(), ()> {
611  if let Some(ref mut meta) = out {
612    for entry in meta.iter_mut() {
613      *entry = 0;
614    }
615  }
616  if reader.pos >= reader.data.len() {
617    return Err(());
618  }
619  let stringlet_count = parse_prefix_suffix_table(reader, out.as_deref_mut())?;
620  let num_transforms = reader.read_u8()? as usize;
621  let transforms_offset = reader.pos;
622  if reader.pos + num_transforms * TRANSFORM_TRIPLET_SIZE > reader.data.len() {
623    return Err(());
624  }
625  reader.pos += num_transforms * TRANSFORM_TRIPLET_SIZE;
626  let mut has_params = false;
627  for i in 0..num_transforms {
628    let triplet = transform_triplet_at(reader.data, transforms_offset, i);
629    let transform_type = triplet.transform_type;
630    if triplet.prefix_id as usize >= stringlet_count ||
631       triplet.suffix_id as usize >= stringlet_count {
632      return Err(());
633    }
634    if transform_type >= BROTLI_NUM_TRANSFORM_TYPES {
635      return Err(());
636    }
637    if transform_type == BROTLI_TRANSFORM_SHIFT_FIRST ||
638       transform_type == BROTLI_TRANSFORM_SHIFT_ALL {
639      has_params = true;
640    }
641  }
642  let params_offset = reader.pos;
643  if has_params {
644    if reader.pos + num_transforms * 2 > reader.data.len() {
645      return Err(());
646    }
647    reader.pos += num_transforms * 2;
648    for i in 0..num_transforms {
649      let transform_type =
650        transform_triplet_at(reader.data, transforms_offset, i).transform_type;
651      if transform_type != BROTLI_TRANSFORM_SHIFT_FIRST &&
652         transform_type != BROTLI_TRANSFORM_SHIFT_ALL {
653        if reader.data[params_offset + i * 2] != 0 ||
654           reader.data[params_offset + i * 2 + 1] != 0 {
655          return Err(());
656        }
657      }
658    }
659  }
660  if let Some(meta) = out {
661    meta[TL_NUM_TRANSFORMS] = num_transforms as u32;
662    meta[TL_TRANSFORMS_OFFSET] = transforms_offset as u32;
663    meta[TL_PARAMS_OFFSET] = if has_params { params_offset as u32 } else { u32::max_value() };
664    // Compute the identity cutoff transform: the first ["", IDENTITY, ""].
665    let mut cutoff: i16 = -1;
666    {
667      let view = CustomTransforms { meta: &*meta, blob: reader.data };
668      for i in 0..num_transforms {
669        let triplet = view.transform_triplet(i as i32);
670        if triplet.transform_type == 0 &&
671           view.stringlet(triplet.prefix_id).is_empty() &&
672           view.stringlet(triplet.suffix_id).is_empty() {
673          cutoff = i as i16;
674          break;
675        }
676      }
677    }
678    meta[TL_CUTOFF_IDENTITY] = cutoff as u16 as u32;
679  }
680  Ok(())
681}
682
683pub(crate) struct ParsedSerializedDictionary {
684  // Offset and length of the embedded LZ77 prefix dictionary, if any.
685  pub(crate) prefix: Option<(usize, usize)>,
686  pub(crate) num_word_lists: u8,
687  pub(crate) num_transform_lists: u8,
688}
689
690// First pass: validates the container far enough to learn the word list and
691// transform list counts (and thus the arena size), like DryParseDictionary.
692pub(crate) fn dry_parse_serialized_dictionary(data: &[u8]) -> Result<ParsedSerializedDictionary, ()> {
693  // Check magic header bytes.
694  if data.len() < 2 || data[0] != 0x91 || data[1] != 0 {
695    return Err(());
696  }
697  let mut reader = Reader { data: data, pos: 2 };
698  let chunk_size = reader.read_varint32()?;
699  let mut prefix: Option<(usize, usize)> = None;
700  if chunk_size != 0 {
701    // This limitation is not specified but the 32-bit Brotli decoder for now.
702    if chunk_size > 1073741823 {
703      return Err(());
704    }
705    if reader.pos + chunk_size as usize > data.len() {
706      return Err(());
707    }
708    prefix = Some((reader.pos, chunk_size as usize));
709    reader.pos += chunk_size as usize;
710  }
711  let num_word_lists = reader.read_u8()?;
712  if num_word_lists as usize > SHARED_BROTLI_NUM_DICTIONARY_CONTEXTS {
713    return Err(());
714  }
715  for _ in 0..num_word_lists {
716    parse_word_list(&mut reader, None)?;
717  }
718  let num_transform_lists = reader.read_u8()?;
719  if num_transform_lists as usize > SHARED_BROTLI_NUM_DICTIONARY_CONTEXTS {
720    return Err(());
721  }
722  for _ in 0..num_transform_lists {
723    parse_transforms_list(&mut reader, None)?;
724  }
725  Ok(ParsedSerializedDictionary {
726    prefix: prefix,
727    num_word_lists: num_word_lists,
728    num_transform_lists: num_transform_lists,
729  })
730}
731
732// Second pass: fills `dict` (everything except the blob, which the caller
733// moves in afterwards) using a pre-allocated arena of
734// num_word_lists * WORD_LIST_STRIDE + num_transform_lists * TRANSFORM_LIST_STRIDE
735// zero-initialized u32s. Must be called with the summary returned by
736// dry_parse_serialized_dictionary for the same data.
737pub(crate) fn parse_serialized_dictionary_into<AllocU8: alloc::Allocator<u8>,
738                                               AllocU32: alloc::Allocator<u32>>(
739    data: &[u8],
740    summary: &ParsedSerializedDictionary,
741    dict: &mut BrotliSharedDictionary<AllocU8, AllocU32>)
742    -> Result<(), ()> {
743  if data.len() < 2 || data[0] != 0x91 || data[1] != 0 {
744    return Err(());
745  }
746  if summary.num_word_lists as usize > SHARED_BROTLI_NUM_DICTIONARY_CONTEXTS ||
747     summary.num_transform_lists as usize > SHARED_BROTLI_NUM_DICTIONARY_CONTEXTS {
748    return Err(());
749  }
750  let arena_size = (summary.num_word_lists as usize)
751      .checked_mul(WORD_LIST_STRIDE)
752      .and_then(|word_size| {
753        (summary.num_transform_lists as usize)
754            .checked_mul(TRANSFORM_LIST_STRIDE)
755            .and_then(|transform_size| word_size.checked_add(transform_size))
756      })
757      .ok_or(())?;
758  if dict.meta.slice().len() != arena_size {
759    return Err(());
760  }
761
762  let mut reader = Reader { data: data, pos: 2 };
763  let chunk_size = reader.read_varint32()?;
764  if chunk_size > 1073741823 {
765    return Err(());
766  }
767  let prefix = if chunk_size == 0 {
768    None
769  } else {
770    Some((reader.pos, chunk_size as usize))
771  };
772  reader.pos = reader.pos.checked_add(chunk_size as usize).ok_or(())?;
773  if reader.pos > data.len() || prefix != summary.prefix {
774    return Err(());
775  }
776  let num_word_lists = reader.read_u8()?;
777  if num_word_lists != summary.num_word_lists {
778    return Err(());
779  }
780  dict.num_word_lists = num_word_lists;
781  for i in 0..num_word_lists as usize {
782    let start = i * WORD_LIST_STRIDE;
783    parse_word_list(&mut reader,
784                    Some(&mut dict.meta.slice_mut()[start..start + WORD_LIST_STRIDE]))?;
785  }
786  let num_transform_lists = reader.read_u8()?;
787  if num_transform_lists != summary.num_transform_lists {
788    return Err(());
789  }
790  dict.num_transform_lists = num_transform_lists;
791  let tl_base = num_word_lists as usize * WORD_LIST_STRIDE;
792  for i in 0..num_transform_lists as usize {
793    let start = tl_base + i * TRANSFORM_LIST_STRIDE;
794    parse_transforms_list(&mut reader,
795                          Some(&mut dict.meta.slice_mut()[start..start + TRANSFORM_LIST_STRIDE]))?;
796  }
797  if num_word_lists != 0 || num_transform_lists != 0 {
798    let num_dictionaries = reader.read_u8()?;
799    if num_dictionaries == 0 ||
800       num_dictionaries as usize > SHARED_BROTLI_NUM_DICTIONARY_CONTEXTS {
801      return Err(());
802    }
803    dict.num_dictionaries = num_dictionaries;
804    for i in 0..num_dictionaries as usize {
805      let words_index = reader.read_u8()?;
806      if words_index > num_word_lists {
807        return Err(());
808      }
809      let transforms_index = reader.read_u8()?;
810      if transforms_index > num_transform_lists {
811        return Err(());
812      }
813      dict.words_index[i] = words_index;
814      dict.transforms_index[i] = transforms_index;
815    }
816    dict.context_based = reader.read_bool()?;
817    if dict.context_based {
818      for i in 0..SHARED_BROTLI_NUM_DICTIONARY_CONTEXTS {
819        let context_value = reader.read_u8()?;
820        if context_value >= num_dictionaries {
821          return Err(());
822        }
823        dict.context_map[i] = context_value;
824      }
825    }
826  } else {
827    dict.context_based = false;
828    dict.num_dictionaries = 1;
829    // words_index[0] == num_word_lists == 0 selects the built-in dictionary,
830    // and likewise for transforms; that is what Default already encodes.
831  }
832  Ok(())
833}
834
835#[cfg(all(test, feature="std"))]
836mod tests {
837  use super::*;
838  use alloc_stdlib::StandardAlloc;
839  use std::vec::Vec;
840
841  // Builds a transform list with stringlets ["up", "ing", ""] and transforms
842  // [["", IDENTITY, ""], ["", UPPERCASE_ALL, ""], ["up", IDENTITY, "ing"],
843  //  ["", SHIFT_FIRST, ""] param 3, ["", SHIFT_ALL, ""] param 3,
844  //  ["", OMIT_LAST_2, ""], ["", OMIT_FIRST_2, ""]].
845  fn transform_list_bytes() -> Vec<u8> {
846    let stringlets = b"\x02up\x03ing\x00";
847    let mut out = Vec::<u8>::new();
848    out.push(stringlets.len() as u8);
849    out.push(0);
850    out.extend_from_slice(stringlets);
851    // [prefix_id, transform_type, suffix_id] -- see transform_triplet_at for
852    // why this is the C implementation's order and not the draft's.
853    let transforms: &[[u8; 3]] = &[[2, 0, 2], [2, 11, 2], [0, 0, 1],
854                                   [2, BROTLI_TRANSFORM_SHIFT_FIRST, 2],
855                                   [2, BROTLI_TRANSFORM_SHIFT_ALL, 2],
856                                   [2, 2, 2], [2, 13, 2]];
857    out.push(transforms.len() as u8);
858    for t in transforms.iter() {
859      out.extend_from_slice(t);
860    }
861    let params: &[u16] = &[0, 0, 0, 3, 3, 0, 0];
862    for p in params.iter() {
863      out.push(*p as u8);
864      out.push((*p >> 8) as u8);
865    }
866    out
867  }
868
869  fn serialized_with_custom_lists() -> Vec<u8> {
870    let mut blob = Vec::<u8>::new();
871    blob.extend_from_slice(&[0x91, 0x00]);
872    blob.push(0); // no LZ77 prefix
873    blob.push(1); // NUM_WORD_LISTS
874    let mut size_bits = [0u8; 28]; // lengths 4..=31
875    size_bits[0] = 1; // two words of length 4
876    blob.extend_from_slice(&size_bits);
877    blob.extend_from_slice(b"frobquxx");
878    blob.push(1); // NUM_TRANSFORM_LISTS
879    blob.extend_from_slice(&transform_list_bytes());
880    blob.push(1); // NUM_DICTIONARIES
881    blob.push(0); // words index
882    blob.push(0); // transforms index
883    blob.push(0); // CONTEXT_ENABLED = false
884    blob
885  }
886
887  fn parse(blob: &[u8]) -> Result<BrotliSharedDictionary<StandardAlloc, StandardAlloc>, ()> {
888    let summary = dry_parse_serialized_dictionary(blob)?;
889    let mut dict = BrotliSharedDictionary::<StandardAlloc, StandardAlloc>::default();
890    let arena = summary.num_word_lists as usize * WORD_LIST_STRIDE +
891                summary.num_transform_lists as usize * TRANSFORM_LIST_STRIDE;
892    let mut alloc = StandardAlloc::default();
893    dict.meta = <StandardAlloc as Allocator<u32>>::alloc_cell(&mut alloc, arena);
894    parse_serialized_dictionary_into(blob, &summary, &mut dict)?;
895    let mut blob_mem = <StandardAlloc as Allocator<u8>>::alloc_cell(&mut alloc, blob.len());
896    blob_mem.slice_mut().clone_from_slice(blob);
897    dict.blob = state::MaybeOwnedSlice::Owned(blob_mem);
898    Ok(dict)
899  }
900
901  #[test]
902  fn test_parse_and_lookup_custom_words() {
903    let dict = parse(&serialized_with_custom_lists()[..]).unwrap();
904    assert!(dict.is_custom());
905    assert_eq!(dict.num_dictionaries, 1);
906    let words = dict.words_of(0);
907    assert_eq!(words.size_bits_by_length(4), 1);
908    assert_eq!(words.size_bits_by_length(8), 0);
909    assert_eq!(words.word(4, 0), b"frob");
910    assert_eq!(words.word(4, 1), b"quxx");
911    let transforms = dict.transforms_of(0);
912    assert_eq!(transforms.num_transforms(), 7);
913    assert_eq!(transforms.cutoff_identity(), 0);
914  }
915
916  #[test]
917  fn test_custom_transforms_apply() {
918    let dict = parse(&serialized_with_custom_lists()[..]).unwrap();
919    let transforms = dict.transforms_of(0);
920    let mut dst = [0u8; 64];
921    // identity
922    assert_eq!(transforms.apply(&mut dst, b"frob", 4, 0), 4);
923    assert_eq!(&dst[..4], b"frob");
924    // uppercase all
925    assert_eq!(transforms.apply(&mut dst, b"frob", 4, 1), 4);
926    assert_eq!(&dst[..4], b"FROB");
927    // prefix "up", suffix "ing"
928    assert_eq!(transforms.apply(&mut dst, b"frob", 4, 2), 9);
929    assert_eq!(&dst[..9], b"upfrobing");
930    // shift first by 3: 'f' -> 'i'
931    assert_eq!(transforms.apply(&mut dst, b"frob", 4, 3), 4);
932    assert_eq!(&dst[..4], b"irob");
933    // shift all by 3
934    assert_eq!(transforms.apply(&mut dst, b"frob", 4, 4), 4);
935    assert_eq!(&dst[..4], b"iure");
936    // omit last 2
937    assert_eq!(transforms.apply(&mut dst, b"frob", 4, 5), 2);
938    assert_eq!(&dst[..2], b"fr");
939    // omit first 2
940    assert_eq!(transforms.apply(&mut dst, b"frob", 4, 6), 2);
941    assert_eq!(&dst[..2], b"ob");
942  }
943
944  #[test]
945  fn test_shift_all_multibyte_utf8() {
946    let dict = parse(&serialized_with_custom_lists()[..]).unwrap();
947    let transforms = dict.transforms_of(0);
948    // U+00E9 (0xC3 0xA9) shifted by +3 is U+00EC (0xC3 0xAC).
949    let mut dst = [0u8; 64];
950    let len = transforms.apply(&mut dst, &[0xC3, 0xA9, b'a', b'b'], 4, 4);
951    assert_eq!(len, 4);
952    assert_eq!(&dst[..4], &[0xC3, 0xAC, b'd', b'e']);
953  }
954
955  #[test]
956  fn test_parse_rejects_malformed() {
957    // bad magic
958    assert!(dry_parse_serialized_dictionary(&[0x90, 0x00, 0x00, 0x00, 0x00]).is_err());
959    // truncated
960    assert!(dry_parse_serialized_dictionary(&[0x91]).is_err());
961    // prefix chunk larger than the data
962    assert!(dry_parse_serialized_dictionary(&[0x91, 0x00, 0x10, 0x00, 0x00]).is_err());
963    // size_bits over the limit
964    let mut blob = serialized_with_custom_lists();
965    blob[4] = 16; // size_bits for length 4
966    assert!(dry_parse_serialized_dictionary(&blob[..]).is_err());
967    // transform type out of range
968    let mut blob = serialized_with_custom_lists();
969    let pos = blob.iter().position(|&b| b == BROTLI_TRANSFORM_SHIFT_ALL).unwrap();
970    blob[pos] = BROTLI_NUM_TRANSFORM_TYPES;
971    assert!(dry_parse_serialized_dictionary(&blob[..]).is_err());
972    // nonzero param for a non-shift transform
973    let mut blob = serialized_with_custom_lists();
974    let len = blob.len();
975    blob[len - 17] = 1; // first param byte (identity transform)
976    assert!(dry_parse_serialized_dictionary(&blob[..]).is_err());
977    // dictionary index out of range (validated by the full parse)
978    let mut blob = serialized_with_custom_lists();
979    let len = blob.len();
980    blob[len - 3] = 2; // words index; only one word list, so 2 > 1 is invalid
981    assert!(parse(&blob[..]).is_err());
982  }
983
984  #[test]
985  fn test_second_pass_rejects_mismatched_summary_before_arena_access() {
986    let blob = serialized_with_custom_lists();
987    // Deliberately claim there are no lists and provide the corresponding
988    // zero-length arena. The count must be rejected before list 0 is indexed.
989    let summary = ParsedSerializedDictionary {
990      prefix: None,
991      num_word_lists: 0,
992      num_transform_lists: 0,
993    };
994    let mut dict = BrotliSharedDictionary::<StandardAlloc, StandardAlloc>::default();
995    assert!(parse_serialized_dictionary_into(&blob, &summary, &mut dict).is_err());
996
997    // A matching summary with a short arena is likewise a normal parse error,
998    // not an indexing panic.
999    let summary = dry_parse_serialized_dictionary(&blob).unwrap();
1000    let arena_size = summary.num_word_lists as usize * WORD_LIST_STRIDE +
1001                     summary.num_transform_lists as usize * TRANSFORM_LIST_STRIDE;
1002    let mut alloc = StandardAlloc::default();
1003    dict.meta = <StandardAlloc as Allocator<u32>>::alloc_cell(
1004        &mut alloc, arena_size - 1);
1005    assert!(parse_serialized_dictionary_into(&blob, &summary, &mut dict).is_err());
1006  }
1007
1008  #[test]
1009  fn test_parse_prefix_only_is_not_custom() {
1010    let mut blob = Vec::<u8>::new();
1011    blob.extend_from_slice(&[0x91, 0x00]);
1012    blob.push(4);
1013    blob.extend_from_slice(b"wxyz");
1014    blob.push(0);
1015    blob.push(0);
1016    let summary = dry_parse_serialized_dictionary(&blob[..]).unwrap();
1017    assert_eq!(summary.prefix, Some((3, 4)));
1018    assert_eq!(summary.num_word_lists, 0);
1019    assert_eq!(summary.num_transform_lists, 0);
1020  }
1021}