Skip to main content

gix_commitgraph/file/
init.rs

1use gix_error::Result;
2use std::path::{Path, PathBuf};
3
4use gix_error::{ResultExt, bail, corruption, message};
5
6use crate::{
7    File,
8    file::{
9        BASE_GRAPHS_LIST_CHUNK_ID, COMMIT_DATA_CHUNK_ID, COMMIT_DATA_ENTRY_SIZE_SANS_HASH,
10        EXTENDED_EDGES_LIST_CHUNK_ID, FAN_LEN, GENERATION_DATA_CHUNK_ID, GENERATION_OVERFLOW_CHUNK_ID, HEADER_LEN,
11        OID_FAN_CHUNK_ID, OID_LOOKUP_CHUNK_ID, SIGNATURE,
12    },
13};
14
15const MIN_FILE_SIZE: usize = HEADER_LEN
16    + gix_chunk::file::Index::size_for_entries(3 /*OIDF, OIDL, CDAT*/)
17    + FAN_LEN * 4 /* FANOUT TABLE CHUNK OIDF */
18    + gix_hash::Kind::shortest().len_in_bytes();
19
20impl File {
21    /// Try to parse the commit graph file at `path`.
22    pub fn at(path: impl AsRef<Path>) -> Result<File> {
23        Self::try_from(path.as_ref())
24    }
25
26    /// A lower-level constructor which constructs a new instance directly from the mapping in `data`,
27    /// assuming that it originated from `path`.
28    ///
29    /// Note that `path` is only used for verification of the hash its basename contains, but otherwise
30    /// is not of importance.
31    pub fn new(data: memmap2::Mmap, path: PathBuf) -> Result<File> {
32        let data_size = data.len();
33        if data_size < MIN_FILE_SIZE {
34            bail!(corruption("Commit-graph file too small even for an empty graph"));
35        }
36
37        let mut ofs = 0;
38        if &data[ofs..ofs + SIGNATURE.len()] != SIGNATURE {
39            bail!(corruption("Commit-graph file does not start with expected signature"));
40        }
41        ofs += SIGNATURE.len();
42
43        match data[ofs] {
44            1 => (),
45            x => {
46                bail!("Unsupported commit-graph file version: {x}".unsupported());
47            }
48        }
49        ofs += 1;
50
51        let object_hash = gix_hash::Kind::try_from(data[ofs])
52            .map_err(|v| message!("Commit-graph file uses unsupported hash version: {v}").unsupported_error())?;
53        ofs += 1;
54
55        let chunk_count = data[ofs];
56        // Can assert chunk_count >= MIN_CHUNKS here, but later OIDF+OIDL+CDAT presence checks make
57        // it redundant.
58        ofs += 1;
59
60        let base_graph_count = data[ofs];
61        ofs += 1;
62
63        let chunks = gix_chunk::file::Index::from_bytes(&data, ofs, u32::from(chunk_count)).or_raise(|| {
64            message!("Couldn't read commit-graph file with {chunk_count} chunks at offset {ofs}").corrupted()
65        })?;
66
67        let base_graphs_list_offset = chunks
68            .validated_usize_offset_by_id(BASE_GRAPHS_LIST_CHUNK_ID, |chunk_range| -> Result<_> {
69                let chunk_size = chunk_range.len();
70                if chunk_size % object_hash.len_in_bytes() != 0 {
71                    bail!("Commit-graph chunk {BASE_GRAPHS_LIST_CHUNK_ID:?} has invalid size: {msg}".corrupted(),
72                        msg = format!(
73                            "chunk size {} is not a multiple of {}",
74                            chunk_size,
75                            object_hash.len_in_bytes()
76                        ),
77                    );
78                }
79                let chunk_base_graph_count = chunk_size / object_hash.len_in_bytes();
80                if chunk_base_graph_count != usize::from(base_graph_count) {
81                    bail!("Commit-graph {BASE_GRAPHS_LIST_CHUNK_ID:?} chunk contains {chunk_base_graph_count} base graphs, but commit-graph file header claims {base_graph_count} base graphs".corrupted())
82                }
83                Ok(chunk_range.start)
84            })
85            .ok()
86            .transpose()?;
87
88        let (commit_data_offset, commit_data_count): (_, u32) = chunks
89            .validated_usize_offset_by_id(COMMIT_DATA_CHUNK_ID, |chunk_range| -> Result<_> {
90                let chunk_size = chunk_range.len();
91
92                let entry_size = object_hash.len_in_bytes() + COMMIT_DATA_ENTRY_SIZE_SANS_HASH;
93                if chunk_size % entry_size != 0 {
94                    bail!("Commit-graph chunk {COMMIT_DATA_CHUNK_ID:?} has invalid size: chunk size {chunk_size} is not a multiple of {entry_size}".corrupted())
95                }
96                Ok((
97                    chunk_range.start,
98                    commit_count(chunk_size / entry_size)?,
99                ))
100            })
101            .or_raise(|| corruption("Error getting offset for commit data chunk"))??;
102
103        let fan_offset = chunks
104            .validated_usize_offset_by_id(OID_FAN_CHUNK_ID, |chunk_range| -> Result<_> {
105                let chunk_size = chunk_range.len();
106
107                let expected_size = 4 * FAN_LEN;
108                if chunk_size != expected_size {
109                    bail!("Commit-graph chunk {OID_FAN_CHUNK_ID:?} has invalid size: expected chunk length {expected_size}, got {chunk_size}".corrupted())
110                }
111                Ok(chunk_range.start)
112            })
113            .or_raise(|| corruption("Error getting offset for OID fan chunk"))?
114            .or_raise(|| message("Error getting offset for OID fan chunk"))?;
115
116        let (oid_lookup_offset, oid_lookup_count): (_, u32) = chunks
117            .validated_usize_offset_by_id(OID_LOOKUP_CHUNK_ID, |chunk_range| -> Result<_> {
118                let chunk_size = chunk_range.len();
119
120                if chunk_size % object_hash.len_in_bytes() != 0 {
121                    bail!("Commit-graph chunk {OID_LOOKUP_CHUNK_ID:?} has invalid size: chunk size {chunk_size} is not a multiple of {hash_len}".corrupted(), hash_len = object_hash.len_in_bytes())
122                }
123                Ok((
124                    chunk_range.start,
125                    commit_count(chunk_size / object_hash.len_in_bytes())?,
126                ))
127            })
128            .or_raise(|| corruption("Error getting offset for OID lookup chunk"))?
129            .or_raise(|| message("Error getting offset for OID lookup chunk"))?;
130
131        let extra_edges_list_range = chunks
132            .validated_usize_offset_by_id(EXTENDED_EDGES_LIST_CHUNK_ID, |chunk_range| -> Result<_> {
133                if chunk_range.len() % 4 != 0 {
134                    bail!("Commit-graph chunk {EXTENDED_EDGES_LIST_CHUNK_ID:?} has invalid size: chunk size {} is not a multiple of 4".corrupted(), chunk_range.len());
135                }
136                Ok(chunk_range)
137            })
138            .ok()
139            .transpose()?;
140
141        let generation_data_offset = chunks
142            .validated_usize_offset_by_id(GENERATION_DATA_CHUNK_ID, |range| -> Result<_> {
143                if range.len() / 4 != commit_data_count as usize || range.len() % 4 != 0 {
144                    bail!("Commit-graph generation data must contain one u32 per commit".corrupted());
145                }
146                Ok(range.start)
147            })
148            .ok()
149            .transpose()?;
150        let generation_overflow_range = chunks
151            .validated_usize_offset_by_id(GENERATION_OVERFLOW_CHUNK_ID, |range| -> Result<_> {
152                if range.len() % 8 != 0 {
153                    bail!("Commit-graph generation overflow data must contain whole u64 values".corrupted());
154                }
155                Ok(range)
156            })
157            .ok()
158            .transpose()?;
159
160        let trailer = &data[chunks.highest_offset() as usize..];
161        if trailer.len() != object_hash.len_in_bytes() {
162            bail!(
163                "Expected commit-graph trailer to contain {} bytes, got {}".corrupted(),
164                object_hash.len_in_bytes(),
165                trailer.len()
166            );
167        }
168
169        if base_graph_count > 0 && base_graphs_list_offset.is_none() {
170            bail!("Chunk named {BASE_GRAPHS_LIST_CHUNK_ID:?} was not found in chunk file index".corrupted());
171        }
172
173        let (fan, _) = read_fan(&data[fan_offset..]);
174        if fan.windows(2).any(|counts| counts[0] > counts[1]) {
175            bail!(corruption("Commit-graph fanout table is not monotonic"));
176        }
177        if oid_lookup_count != fan[255] {
178            bail!(
179                "Commit-graph {OID_FAN_CHUNK_ID:?} chunk contains {chunk1_commits} commits, but {OID_LOOKUP_CHUNK_ID:?} chunk contains {chunk2_commits} commits".corrupted(),
180                chunk1_commits = fan[255],
181                chunk2_commits = oid_lookup_count,
182            );
183        }
184        if commit_data_count != fan[255] {
185            bail!(
186                "Commit-graph {OID_FAN_CHUNK_ID:?} chunk contains {chunk1_commits} commits, but {COMMIT_DATA_CHUNK_ID:?} chunk contains {chunk2_commits} commits".corrupted(),
187                chunk1_commits = fan[255],
188                chunk2_commits = commit_data_count,
189            );
190        }
191        Ok(File {
192            base_graph_count,
193            base_graphs_list_offset,
194            commit_data_offset,
195            generation_data_offset,
196            generation_overflow_range,
197            data,
198            extra_edges_list_range,
199            fan,
200            oid_lookup_offset,
201            path,
202            hash_len: object_hash.len_in_bytes(),
203            object_hash,
204            parent_position_limit: if base_graph_count == 0 {
205                fan[255]
206            } else {
207                crate::MAX_COMMITS
208            },
209        })
210    }
211}
212
213fn commit_count(count: usize) -> Result<u32> {
214    if count > crate::MAX_COMMITS as usize {
215        bail!(
216            "Commit-graph chunk contains {count} commits, but only {} commits are allowed".corrupted(),
217            crate::MAX_COMMITS
218        );
219    }
220    Ok(count as u32)
221}
222
223impl TryFrom<&Path> for File {
224    type Error = gix_error::Error;
225
226    fn try_from(path: &Path) -> Result<Self> {
227        let data = std::fs::File::open(path)
228            .and_then(|file| {
229                // SAFETY: we have to take the risk of somebody changing the file underneath. Git never writes into the same file.
230                #[expect(unsafe_code)]
231                unsafe {
232                    memmap2::MmapOptions::new().map_copy_read_only(&file)
233                }
234            })
235            .or_raise(|| message!("Could not open commit-graph file at \"{path}\"", path = path.display()))?;
236        Self::new(data, path.to_owned())
237    }
238}
239
240// Copied from gix-odb/pack/index/init.rs
241fn read_fan(d: &[u8]) -> ([u32; FAN_LEN], usize) {
242    assert!(d.len() >= FAN_LEN * 4);
243
244    let mut fan = [0; FAN_LEN];
245    for (c, f) in d.as_chunks::<4>().0.iter().zip(fan.iter_mut()) {
246        *f = u32::from_be_bytes(*c);
247    }
248    (fan, FAN_LEN * 4)
249}
250
251#[cfg(test)]
252mod tests {
253    #[test]
254    fn commit_counts_cannot_exceed_the_format_limit() -> gix_error::TestResult {
255        assert_eq!(
256            super::commit_count(crate::MAX_COMMITS as usize)?,
257            crate::MAX_COMMITS,
258            "the format's maximum commit count is representable"
259        );
260        for count in [crate::MAX_COMMITS as usize + 1, usize::MAX] {
261            let err = super::commit_count(count).expect_err("oversized counts are rejected before narrowing");
262            assert!(
263                err.is_corrupted(),
264                "unrepresentable stored commit counts are corruption"
265            );
266        }
267        Ok(())
268    }
269}