Skip to main content

gix_pack/data/file/decode/
entry.rs

1use gix_error::Result;
2use smallvec::SmallVec;
3use std::ops::Range;
4
5use gix_error::{OptionExt, ResourceExhaustionKind, ResultExt, bail, corruption, message, validation};
6
7use crate::{
8    cache, data,
9    data::{
10        File, delta,
11        file::decode::{DeltaBaseUnresolved, allocation_error, resize_with_limit},
12    },
13};
14
15/// A return value of a resolve function, which given an [`ObjectId`][gix_hash::ObjectId] determines where an object can be found.
16#[derive(Debug, PartialEq, Eq, Hash, Ord, PartialOrd, Clone)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub enum ResolvedBase {
19    /// Indicate an object is within this pack, at the given entry, and thus can be looked up locally.
20    InPack(data::Entry),
21    /// Indicates the object of `kind` was found outside of the pack, and its data was written into an output
22    /// vector which now has a length of `end`.
23    #[expect(missing_docs)]
24    OutOfPack { kind: gix_object::Kind, end: usize },
25}
26
27#[derive(Debug)]
28struct Delta {
29    data: Range<usize>,
30    base_size: usize,
31    result_size: usize,
32
33    decompressed_size: usize,
34    data_offset: data::Offset,
35}
36
37/// Additional information and statistics about a successfully decoded object produced by [`File::decode_entry()`].
38///
39/// Useful to understand the effectiveness of the pack compression or the cost of decompression.
40#[derive(Debug, PartialEq, Eq, Hash, Ord, PartialOrd, Clone)]
41#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
42pub struct Outcome {
43    /// The kind of resolved object.
44    pub kind: gix_object::Kind,
45    /// The amount of deltas in the chain of objects that had to be resolved beforehand.
46    ///
47    /// This number is affected by the [`Cache`][cache::DecodeEntry] implementation, with cache hits shortening the
48    /// delta chain accordingly
49    pub num_deltas: u32,
50    /// The total decompressed size of all pack entries in the delta chain
51    pub decompressed_size: u64,
52    /// The total compressed size of all pack entries in the delta chain
53    pub compressed_size: usize,
54    /// The total size of the decoded object.
55    pub object_size: u64,
56}
57
58impl Outcome {
59    pub(crate) fn default_from_kind(kind: gix_object::Kind) -> Self {
60        Self {
61            kind,
62            num_deltas: 0,
63            decompressed_size: 0,
64            compressed_size: 0,
65            object_size: 0,
66        }
67    }
68    fn from_object_entry(kind: gix_object::Kind, entry: &data::Entry, compressed_size: usize) -> Self {
69        Self {
70            kind,
71            num_deltas: 0,
72            decompressed_size: entry.decompressed_size,
73            compressed_size,
74            object_size: entry.decompressed_size,
75        }
76    }
77}
78
79/// Decompression of objects
80impl<T> File<T>
81where
82    T: crate::FileData,
83{
84    fn decoded_object_size(&self, size: u64) -> Result<usize> {
85        decoded_object_size(size, self.alloc_limit_bytes)
86    }
87
88    /// Decompress the given `entry` into `out` and return the amount of bytes read from the pack data.
89    /// Note that `inflate` is not reset after usage, but will be reset before using it.
90    ///
91    /// _Note_ that this method does not resolve deltified objects, but merely decompresses their content
92    /// `out` is expected to be large enough to hold `entry.size` bytes.
93    pub fn decompress_entry(
94        &self,
95        entry: &data::Entry,
96        inflate: &mut gix_zlib::Inflate,
97        out: &mut [u8],
98    ) -> Result<usize> {
99        let size = usize::try_from(entry.decompressed_size)
100            .or_raise(|| allocation_error(ResourceExhaustionKind::AllocationFailure))?;
101        if out.len() < size {
102            bail!(validation("Output buffer is too small for the decompressed entry"));
103        }
104        self.decompress_entry_from_data_offset(entry.data_offset, inflate, &mut out[..size])
105    }
106
107    /// Obtain the [`Entry`][crate::data::Entry] at the given `offset` into the pack.
108    ///
109    /// The `offset` is typically obtained from the pack index file.
110    pub fn entry(&self, offset: data::Offset) -> Result<data::Entry> {
111        let pack_offset: usize = offset.try_into().expect("offset representable by machine");
112        if pack_offset > self.data.len() {
113            bail!(corruption(
114                "Pack entry is truncated: an entry offset pointing beyond pack data"
115            ));
116        }
117
118        let object_data = &self.data[pack_offset..];
119        data::Entry::from_bytes(object_data, offset, self.object_hash)
120    }
121
122    /// Decompress the object expected at the given data offset, sans pack header. This information is only
123    /// known after the pack header was parsed.
124    /// Note that this method does not resolve deltified objects, but merely decompresses their content
125    /// `out` is expected to be large enough to hold `entry.size` bytes.
126    /// Returns the amount of packed bytes there read from the pack data file.
127    pub(crate) fn decompress_entry_from_data_offset(
128        &self,
129        data_offset: data::Offset,
130        inflate: &mut gix_zlib::Inflate,
131        out: &mut [u8],
132    ) -> Result<usize> {
133        let (consumed_in, _consumed_out) =
134            self.decompress_complete_entry_from_data_offset(data_offset, inflate, out)?;
135        Ok(consumed_in)
136    }
137
138    /// Like `decompress_entry_from_data_offset`, but returns `(consumed-input, consumed-output)`.
139    ///
140    /// The compressed stream must end exactly after producing `out.len()` bytes. Pack entry
141    /// headers are untrusted, so callers must not accept streams that stop early and
142    /// leave zero-filled slack in the destination buffer, nor streams that require more output
143    /// than the header promised. Both cases would make later delta parsing operate on bytes that
144    /// are not the entry payload described by the pack header.
145    pub(crate) fn decompress_complete_entry_from_data_offset(
146        &self,
147        data_offset: data::Offset,
148        inflate: &mut gix_zlib::Inflate,
149        out: &mut [u8],
150    ) -> Result<(usize, usize)> {
151        let input = self.entry_data(data_offset)?;
152        inflate.reset();
153        let (status, consumed_in, consumed_out) = inflate
154            .once(input, out)
155            .or_raise(|| message("Failed to decompress pack entry"))?;
156        if status != gix_zlib::Status::StreamEnd || consumed_out != out.len() {
157            bail!(corruption(
158                "Pack entry is truncated: pack entry decompressed size does not match entry header",
159            ));
160        }
161        Ok((consumed_in, consumed_out))
162    }
163
164    /// Like [`Self::decompress_commplete_entry_from_data_offset()`], but allows callers to inspect incomplete streams.
165    ///
166    /// This is only for callers that intentionally decompress a prefix into a smaller buffer, such as
167    /// delta header probing. Full pack entry decoding should use [`Self::decompress_commplete_entry_from_data_offset()`].
168    pub(crate) fn decompress_entry_from_data_offset_unchecked(
169        &self,
170        data_offset: data::Offset,
171        inflate: &mut gix_zlib::Inflate,
172        out: &mut [u8],
173    ) -> Result<(gix_zlib::Status, usize, usize)> {
174        let input = self.entry_data(data_offset)?;
175        inflate.reset();
176        inflate
177            .prefix(input, out)
178            .or_raise(|| message("Failed to decompress pack entry"))
179    }
180
181    /// Return the pack data from `data_offset`, where the compressed entry data starts, to the pack end
182    fn entry_data(&self, data_offset: data::Offset) -> Result<&[u8]> {
183        let offset: usize = data_offset.try_into().expect("offset representable by machine");
184        if offset >= self.data.len() {
185            bail!(corruption(
186                "Pack entry is truncated: an entry data offset pointing beyond pack data"
187            ));
188        }
189        Ok(&self.data[offset..])
190    }
191
192    /// Decode an entry, resolving delta's as needed, while growing the `out` vector if there is not enough
193    /// space to hold the result object.
194    ///
195    /// The `entry` determines which object to decode, and is commonly obtained with the help of a pack index file or through pack iteration.
196    /// `inflate` will be used for decompressing entries, and will not be reset after usage, but before first using it.
197    ///
198    /// `resolve` is a function to lookup objects with the given [`ObjectId`][gix_hash::ObjectId], in case the full object id is used to refer to
199    /// a base object, instead of an in-pack offset. Return `Ok(None)` if the base could not be found;
200    /// lookup errors are propagated unchanged instead of being treated as missing bases.
201    ///
202    /// `delta_cache` is a mechanism to avoid looking up base objects multiple times when decompressing multiple objects in a row.
203    /// Use a [Noop-Cache][cache::Never] to disable caching all together at the cost of repeating work.
204    #[expect(clippy::type_complexity)] // Keep the fallible resolver's arguments and result explicit.
205    pub fn decode_entry(
206        &self,
207        entry: data::Entry,
208        out: &mut Vec<u8>,
209        inflate: &mut gix_zlib::Inflate,
210        resolve: &dyn Fn(&gix_hash::oid, &mut Vec<u8>) -> Result<Option<ResolvedBase>>,
211        delta_cache: &mut dyn cache::DecodeEntry,
212    ) -> Result<Outcome> {
213        use crate::data::entry::Header::*;
214        match entry.header {
215            Tree | Blob | Commit | Tag => {
216                let size = self.decoded_object_size(entry.decompressed_size)?;
217                resize_with_limit(out, size, self.alloc_limit_bytes)?;
218                self.decompress_entry(&entry, inflate, out.as_mut_slice())
219                    .map(|consumed_input| {
220                        Outcome::from_object_entry(
221                            entry.header.as_kind().expect("a non-delta entry"),
222                            &entry,
223                            consumed_input,
224                        )
225                    })
226            }
227            OfsDelta { .. } | RefDelta { .. } => self.resolve_deltas(entry, resolve, inflate, out, delta_cache),
228        }
229    }
230
231    /// resolve: technically, this shouldn't ever be required as stored local packs don't refer to objects by id
232    /// that are outside of the pack. Unless, of course, the ref refers to an object within this pack, which means
233    /// it's very, very large as 20bytes are smaller than the corresponding MSB encoded number
234    #[expect(clippy::type_complexity)] // Match the public decoder's resolver signature.
235    fn resolve_deltas(
236        &self,
237        last: data::Entry,
238        resolve: &dyn Fn(&gix_hash::oid, &mut Vec<u8>) -> Result<Option<ResolvedBase>>,
239        inflate: &mut gix_zlib::Inflate,
240        out: &mut Vec<u8>,
241        cache: &mut dyn cache::DecodeEntry,
242    ) -> Result<Outcome> {
243        // all deltas, from the one that produces the desired object (first) to the oldest at the end of the chain
244        let mut chain = SmallVec::<[Delta; 10]>::default();
245        let first_entry = last.clone();
246        let mut cursor = last;
247        let mut cycle = super::DeltaCycle::new(cursor.data_offset);
248        let mut base_buffer_size: Option<usize> = None;
249        let mut object_kind: Option<gix_object::Kind> = None;
250        let mut consumed_input: Option<usize> = None;
251
252        // Find the first full base, either an undeltified object in the pack or a reference to another object.
253        let mut total_delta_data_size: u64 = 0;
254        while cursor.header.is_delta() {
255            if let Some((kind, packed_size)) = cache.get(self.id, cursor.data_offset, out) {
256                base_buffer_size = Some(out.len());
257                object_kind = Some(kind);
258                // If the input entry is a cache hit, keep the packed size as it must be returned.
259                // Otherwise, the packed size will be determined later when decompressing the input delta
260                if total_delta_data_size == 0 {
261                    consumed_input = Some(packed_size);
262                }
263                break;
264            }
265            // This is a pessimistic guess, as worst possible compression should not be bigger than the data itself.
266            // TODO: is this assumption actually true?
267            total_delta_data_size = total_delta_data_size
268                .checked_add(cursor.decompressed_size)
269                .ok_or_raise(|| allocation_error(ResourceExhaustionKind::AllocationFailure))?;
270            let chain_capacity = if chain.len() == chain.capacity() {
271                chain
272                    .len()
273                    .checked_add(1)
274                    .and_then(usize::checked_next_power_of_two)
275                    .ok_or_raise(|| allocation_error(ResourceExhaustionKind::AllocationFailure))?
276            } else if chain.spilled() {
277                chain.capacity()
278            } else {
279                0
280            };
281            let chain_bytes = chain_capacity
282                .checked_mul(std::mem::size_of::<Delta>())
283                .ok_or_raise(|| allocation_error(ResourceExhaustionKind::AllocationFailure))?;
284            let allocation_size = total_delta_data_size.max(chain_bytes as u64);
285            if self
286                .alloc_limit_bytes
287                .is_some_and(|limit| allocation_size > limit as u64)
288            {
289                bail!(allocation_error(ResourceExhaustionKind::AllocationLimit));
290            }
291            let decompressed_size = self.decoded_object_size(cursor.decompressed_size)?;
292            if chain_capacity > chain.capacity() {
293                chain
294                    .try_reserve_exact(chain_capacity - chain.len())
295                    .map_err(|_| allocation_error(ResourceExhaustionKind::AllocationFailure))
296                    .or_error()?;
297            }
298            chain.push(Delta {
299                data: Range {
300                    start: 0,
301                    end: decompressed_size,
302                },
303                base_size: 0,
304                result_size: 0,
305                decompressed_size,
306                data_offset: cursor.data_offset,
307            });
308            use crate::data::entry::Header;
309            cursor = match cursor.header {
310                Header::OfsDelta { base_distance } => {
311                    let offset = cursor
312                        .checked_base_pack_offset(base_distance)
313                        .ok_or_else(|| {
314                            corruption("Pack entry is truncated: an ofs-delta base distance pointing before pack start")
315                        })
316                        .or_error()?;
317                    self.entry(offset)?
318                }
319                Header::RefDelta { base_id } => match resolve(base_id.as_ref(), out)? {
320                    Some(ResolvedBase::InPack(entry)) => entry,
321                    Some(ResolvedBase::OutOfPack { end, kind }) => {
322                        base_buffer_size = Some(end);
323                        object_kind = Some(kind);
324                        break;
325                    }
326                    None => bail!(DeltaBaseUnresolved(base_id)),
327                },
328                _ => unreachable!("cursor.is_delta() only allows deltas here"),
329            };
330            cycle.check(cursor.data_offset)?;
331        }
332
333        // This can happen if the cache held the first entry itself
334        // We will just treat it as an object then, even though it's technically incorrect.
335        if chain.is_empty() {
336            return Ok(Outcome::from_object_entry(
337                object_kind.expect("object kind as set by cache"),
338                &first_entry,
339                consumed_input.expect("consumed bytes as set by cache"),
340            ));
341        }
342
343        // First pass will decompress all delta data and keep it in our output buffer
344        // [<possibly resolved base object>]<delta-1..delta-n>...
345        // so that we can find the biggest result size.
346        let total_delta_data_size = usize::try_from(total_delta_data_size)
347            .or_raise(|| allocation_error(ResourceExhaustionKind::AllocationFailure))?;
348
349        let chain_len = chain.len();
350        let actual_base_size = match base_buffer_size {
351            Some(size) => size,
352            None => self.decoded_object_size(cursor.decompressed_size)?,
353        };
354        let (first_buffer_end, second_buffer_end) = {
355            let delta_start = base_buffer_size.unwrap_or(0);
356
357            let delta_range = Range {
358                start: delta_start,
359                end: delta_start
360                    .checked_add(total_delta_data_size)
361                    .ok_or_raise(|| allocation_error(ResourceExhaustionKind::AllocationFailure))?,
362            };
363            resize_with_limit(out, delta_range.end, self.alloc_limit_bytes)?;
364
365            let mut instructions = &mut out[delta_range.clone()];
366            let mut relative_delta_start = 0;
367            let mut biggest_result_size = 0;
368            let mut expected_base_size = actual_base_size;
369            for (delta_idx, delta) in chain.iter_mut().rev().enumerate() {
370                let (consumed_from_data_offset, consumed_out) = self.decompress_complete_entry_from_data_offset(
371                    delta.data_offset,
372                    inflate,
373                    &mut instructions[..delta.decompressed_size],
374                )?;
375                let is_last_delta_to_be_applied = delta_idx + 1 == chain_len;
376                if is_last_delta_to_be_applied {
377                    consumed_input = Some(consumed_from_data_offset);
378                }
379
380                let current_delta = &instructions[..consumed_out];
381                let (base_size, offset) = delta::decode_header_size(current_delta)?;
382                let mut bytes_consumed_by_header = offset;
383                delta.base_size = self.decoded_object_size(base_size)?;
384                if delta.base_size != expected_base_size {
385                    bail!(corruption(
386                        "Corrupt delta data: delta base size does not match base object size"
387                    ));
388                }
389                biggest_result_size = biggest_result_size.max(base_size);
390
391                let (result_size, offset) = delta::decode_header_size(&current_delta[offset..])?;
392                bytes_consumed_by_header += offset;
393                biggest_result_size = biggest_result_size.max(result_size);
394                delta.result_size = self.decoded_object_size(result_size)?;
395                expected_base_size = delta.result_size;
396
397                // the absolute location into the instructions buffer, so we keep track of the end point of the last
398                delta.data.start = relative_delta_start + bytes_consumed_by_header;
399                delta.data.end = relative_delta_start + consumed_out;
400                relative_delta_start += delta.decompressed_size;
401
402                instructions = &mut instructions[delta.decompressed_size..];
403            }
404
405            // Now we can produce a buffer like this
406            // [<biggest-result-buffer, possibly filled with resolved base object data>]<biggest-result-buffer><delta-1..delta-n>
407            // from [<possibly resolved base object>]<delta-1..delta-n>...
408            if base_buffer_size.is_none() {
409                biggest_result_size = biggest_result_size.max(cursor.decompressed_size);
410            }
411            let biggest_result_size = self.decoded_object_size(biggest_result_size)?;
412            let first_buffer_size = biggest_result_size;
413            let second_buffer_size = first_buffer_size;
414            let out_size = first_buffer_size
415                .checked_add(second_buffer_size)
416                .and_then(|size| size.checked_add(total_delta_data_size))
417                .ok_or_raise(|| allocation_error(ResourceExhaustionKind::AllocationFailure))?;
418            resize_with_limit(out, out_size, self.alloc_limit_bytes)?;
419
420            // Now 'rescue' the deltas, because in the next step we possibly overwrite that portion
421            // of memory with the base object (in the majority of cases)
422            let second_buffer_end = {
423                let end = first_buffer_size
424                    .checked_add(second_buffer_size)
425                    .ok_or_raise(|| allocation_error(ResourceExhaustionKind::AllocationFailure))?;
426                // Move the decompressed delta instructions behind the two work buffers so they remain intact
427                // while we repurpose the front of `out` for base-object materialization and delta application.
428                out.copy_within(delta_range, end);
429                end
430            };
431
432            // If we don't have a out-of-pack object already, fill the base-buffer by decompressing the full object
433            // at which the cursor is left after the iteration
434            if base_buffer_size.is_none() {
435                let base_entry = cursor;
436                debug_assert!(!base_entry.header.is_delta());
437                object_kind = base_entry.header.as_kind();
438                let base_size = self.decoded_object_size(base_entry.decompressed_size)?;
439                let out_base = &mut out[..base_size];
440                self.decompress_entry_from_data_offset(base_entry.data_offset, inflate, out_base)?;
441            }
442
443            (first_buffer_size, second_buffer_end)
444        };
445
446        // From oldest to most recent, apply all deltas, swapping the buffer back and forth
447        // TODO: once we have more tests, we could optimize this memory-intensive work to
448        //       analyse the delta-chains to only copy data once - after all, with 'copy-from-base' deltas,
449        //       all data originates from one base at some point.
450        // `out` is: [source-buffer][target-buffer][max-delta-instructions-buffer]
451        let (buffers, instructions) = out.split_at_mut(second_buffer_end);
452        let (mut source_buf, mut target_buf) = buffers.split_at_mut(first_buffer_end);
453
454        let mut last_result_size = None;
455        for (
456            delta_idx,
457            Delta {
458                data,
459                base_size,
460                result_size,
461                ..
462            },
463        ) in chain.into_iter().rev().enumerate()
464        {
465            let data = &mut instructions[data];
466            if delta_idx + 1 == chain_len {
467                last_result_size = Some(result_size);
468            }
469            delta::apply(&source_buf[..base_size], &mut target_buf[..result_size], data)?;
470            // use the target as source for the next delta
471            std::mem::swap(&mut source_buf, &mut target_buf);
472        }
473
474        let last_result_size = last_result_size.expect("at least one delta chain item");
475        // uneven chains leave the target buffer after the source buffer
476        // FIXME(Performance) If delta-chains are uneven, we know we will have to copy bytes over here
477        //      Instead we could use a different start buffer, to naturally end up with the result in the
478        //      right one.
479        //      However, this is a bit more complicated than just that - you have to deal with the base
480        //      object, which should also be placed in the second buffer right away. You don't have that
481        //      control/knowledge for out-of-pack bases, so this is a special case to deal with, too.
482        //      Maybe these invariants can be represented in the type system though.
483        if chain_len % 2 == 1 {
484            // this seems inverted, but remember: we swapped the buffers on the last iteration
485            target_buf[..last_result_size].copy_from_slice(&source_buf[..last_result_size]);
486        }
487        debug_assert!(out.len() >= last_result_size);
488        out.truncate(last_result_size);
489
490        let object_kind = object_kind.expect("a base object as root of any delta chain that we are here to resolve");
491        let consumed_input = consumed_input.expect("at least one decompressed delta object");
492        cache.put(
493            self.id,
494            first_entry.data_offset,
495            out.as_slice(),
496            object_kind,
497            consumed_input,
498        );
499        Ok(Outcome {
500            kind: object_kind,
501            // technically depending on the cache, the chain size is not correct as it might
502            // have been cut short by a cache hit. The caller must deactivate the cache to get
503            // actual results
504            num_deltas: chain_len as u32,
505            decompressed_size: first_entry.decompressed_size,
506            compressed_size: consumed_input,
507            object_size: last_result_size as u64,
508        })
509    }
510}
511
512/// Convert user-controlled sizes from pack data into allocation sizes while enforcing the configured allocation cap.
513fn decoded_object_size(size: u64, alloc_limit_bytes: Option<usize>) -> Result<usize> {
514    let size = usize::try_from(size).or_raise(|| allocation_error(ResourceExhaustionKind::AllocationFailure))?;
515    if alloc_limit_bytes.is_some_and(|limit| size > limit) {
516        bail!(allocation_error(ResourceExhaustionKind::AllocationLimit));
517    }
518    Ok(size)
519}
520
521#[cfg(test)]
522mod tests {
523    use gix_testtools::size_ok;
524
525    use super::*;
526
527    #[test]
528    fn size_of_decode_entry_outcome() {
529        let actual = std::mem::size_of::<Outcome>();
530        let expected = 32;
531        assert!(
532            size_ok(actual, expected),
533            "this shouldn't change without use noticing as it's returned a lot: {actual} <~ {expected}"
534        );
535    }
536}