Debian Codegraph @

rust/hg-core/src/revlog/mod.rs

raw
1 // Copyright 2018-2023 Georges Racinet <[email protected]>
2 // and Mercurial contributors
3 //
4 // This software may be used and distributed according to the terms of the
5 // GNU General Public License version 2 or any later version.
6 //! Mercurial concepts for handling revision history
7
8 pub mod deltas;
9 pub mod diff;
10 pub mod node;
11 pub mod nodemap;
12 mod nodemap_docket;
13 pub mod path_encode;
14 use inner_revlog::CoreRevisionBuffer;
15 use inner_revlog::InnerRevlog;
16 use inner_revlog::RevisionBuffer;
17 use memmap2::MmapOptions;
18 pub use node::FromHexError;
19 pub use node::Node;
20 pub use node::NodePrefix;
21 pub use node::NULL_NODE;
22 pub use node::NULL_NODE_ID;
23 use nodemap::read_persistent_nodemap;
24 use options::RevlogOpenOptions;
25 pub mod changelog;
26 pub mod compression;
27 pub mod file_io;
28 pub mod filelog;
29 pub mod index;
30 pub mod inner_revlog;
31 pub mod manifest;
32 pub mod options;
33 pub mod patch;
34
35 use std::io::ErrorKind;
36 use std::io::Read;
37 use std::path::Path;
38
39 use self::nodemap_docket::NodeMapDocket;
40 use crate::dyn_bytes::DynBytes;
41 use crate::errors::HgBacktrace;
42 use crate::errors::HgError;
43 use crate::errors::IoResultExt;
44 use crate::exit_codes;
45 use crate::revlog::index::Index;
46 use crate::revlog::nodemap::NodeMapError;
47 use crate::utils::u32_u;
48 use crate::utils::RawData;
49 use crate::vfs::Vfs;
50 use crate::vfs::VfsImpl;
51
52 /// As noted in revlog.c, revision numbers are actually encoded in
53 /// 4 bytes, and are liberally converted to ints, whence the i32
54 pub type BaseRevision = i32;
55
56 /// Mercurial revision numbers
57 /// In contrast to the more general [`UncheckedRevision`], these are "checked"
58 /// in the sense that they should only be used for revisions that are
59 /// valid for a given index (i.e. in bounds).
60 #[derive(
61 Debug,
62 derive_more::Display,
63 Clone,
64 Copy,
65 Hash,
66 PartialEq,
67 Eq,
68 PartialOrd,
69 Ord,
70 )]
71 pub struct Revision(pub BaseRevision);
72
73 impl format_bytes::DisplayBytes for Revision {
74 fn display_bytes(
75 &self,
76 output: &mut dyn std::io::Write,
77 ) -> std::io::Result<()> {
78 self.0.display_bytes(output)
79 }
80 }
81
82 /// Unchecked Mercurial revision numbers.
83 ///
84 /// Values of this type have no guarantee of being a valid revision number
85 /// in any context. Use method `check_revision` to get a valid revision within
86 /// the appropriate index object.
87 #[derive(
88 Debug,
89 derive_more::Display,
90 Clone,
91 Copy,
92 Hash,
93 PartialEq,
94 Eq,
95 PartialOrd,
96 Ord,
97 )]
98 pub struct UncheckedRevision(pub BaseRevision);
99
100 impl UncheckedRevision {
101 pub fn is_nullrev(&self) -> bool {
102 self.0 == -1
103 }
104 }
105
106 impl format_bytes::DisplayBytes for UncheckedRevision {
107 fn display_bytes(
108 &self,
109 output: &mut dyn std::io::Write,
110 ) -> std::io::Result<()> {
111 self.0.display_bytes(output)
112 }
113 }
114
115 impl From<Revision> for UncheckedRevision {
116 fn from(value: Revision) -> Self {
117 Self(value.0)
118 }
119 }
120
121 impl From<BaseRevision> for UncheckedRevision {
122 fn from(value: BaseRevision) -> Self {
123 Self(value)
124 }
125 }
126
127 /// Marker expressing the absence of a parent
128 ///
129 /// Independently of the actual representation, `NULL_REVISION` is guaranteed
130 /// to be smaller than all existing revisions.
131 pub const NULL_REVISION: Revision = Revision(-1);
132
133 /// Same as `mercurial.node.wdirrev`
134 ///
135 /// This is also equal to `i32::max_value()`, but it's better to spell
136 /// it out explicitely, same as in `mercurial.node`
137 #[allow(clippy::unreadable_literal)]
138 pub const WORKING_DIRECTORY_REVISION: UncheckedRevision =
139 UncheckedRevision(0x7fffffff);
140
141 pub const WORKING_DIRECTORY_HEX: &str =
142 "ffffffffffffffffffffffffffffffffffffffff";
143
144 /// Either a checked revision or the working directory.
145 /// Note that [`Revision`] will never hold [`WORKING_DIRECTORY_REVISION`]
146 /// because that is not a valid revision in any revlog.
147 #[derive(Copy, Clone, Hash, Debug, Eq, PartialEq, Ord, PartialOrd)]
148 pub struct RevisionOrWdir(BaseRevision);
149
150 impl From<Revision> for RevisionOrWdir {
151 fn from(value: Revision) -> Self {
152 RevisionOrWdir(value.0)
153 }
154 }
155
156 impl RevisionOrWdir {
157 /// Creates a [`RevisionOrWdir`] representing the working directory.
158 pub fn wdir() -> Self {
159 RevisionOrWdir(WORKING_DIRECTORY_REVISION.0)
160 }
161
162 /// Returns the revision, or `None` if this is the working directory.
163 pub fn exclude_wdir(self) -> Option<Revision> {
164 if self.0 == WORKING_DIRECTORY_REVISION.0 {
165 None
166 } else {
167 Some(Revision(self.0))
168 }
169 }
170
171 /// Returns true if this is the working directory.
172 pub fn is_wdir(&self) -> bool {
173 *self == Self::wdir()
174 }
175 }
176
177 /// The simplest expression of what we need of Mercurial DAGs.
178 pub trait Graph {
179 /// Return the two parents of the given `Revision`.
180 ///
181 /// Each of the parents can be independently `NULL_REVISION`
182 fn parents(&self, rev: Revision) -> Result<[Revision; 2], GraphError>;
183 }
184
185 #[derive(Clone, Debug, PartialEq)]
186 pub enum GraphError {
187 /// Parent revision does not exist, i.e. below 0 or above max revision.
188 ParentOutOfRange(Revision),
189 /// Parent revision number is greater than one of its descendants.
190 ParentOutOfOrder(Revision),
191 }
192
193 impl std::fmt::Display for GraphError {
194 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195 match self {
196 GraphError::ParentOutOfRange(revision) => {
197 write!(f, "parent out of range ({})", revision)
198 }
199 GraphError::ParentOutOfOrder(revision) => {
200 write!(f, "parent out of order ({})", revision)
201 }
202 }
203 }
204 }
205
206 impl<T: Graph> Graph for &T {
207 fn parents(&self, rev: Revision) -> Result<[Revision; 2], GraphError> {
208 (*self).parents(rev)
209 }
210 }
211
212 /// The Mercurial Revlog Index
213 ///
214 /// This is currently limited to the minimal interface that is needed for
215 /// the [`nodemap`](nodemap/index.html) module
216 pub trait RevlogIndex {
217 /// Total number of Revisions referenced in this index
218 fn len(&self) -> usize;
219
220 fn is_empty(&self) -> bool {
221 self.len() == 0
222 }
223
224 /// Return a reference to the Node
225 fn node(&self, rev: Revision) -> &Node;
226
227 /// Return a [`Revision`] if `rev` is a valid revision number for this
228 /// index.
229 ///
230 /// [`NULL_REVISION`] is considered to be valid.
231 #[inline(always)]
232 fn check_revision(&self, rev: UncheckedRevision) -> Option<Revision> {
233 let rev = rev.0;
234
235 if rev == NULL_REVISION.0 || (rev >= 0 && (rev as usize) < self.len()) {
236 Some(Revision(rev))
237 } else {
238 None
239 }
240 }
241 }
242
243 /// Internal trait used by [`InnerRevlog`], **should not be called directly**.
244 pub trait RevlogIndexNodeLookup: RevlogIndex {
245 /// This is used internally by the [`InnerRevlog`] nodemap and **should not
246 /// be called directly**.
247 ///
248 /// Finds a [`Revision`] from a given [`NodePrefix`] directly in the index.
249 ///
250 /// - `visit` is a function that is called on each revision we visit during
251 /// the lookup with the ([`Node`], [`Revision`]) pair.
252 /// - `from_rev_down` is the (potential) revision from which to start
253 /// iterating backwards into the index, used for optimizing multiple calls
254 /// that have already checked the top-most revisions. Using this parameter
255 /// in a context where the top-most revisions have not been checked yet
256 /// can yield false negatives.
257 /// - `prefix_match` is the (potential) revision that may have been found in
258 /// the existing (incomplete) nodemap, to return if there is no ambiguous
259 /// node that also matches `prefix`. Not giving this revision if it exists
260 /// and is higher than `from_rev_down` (if provided) will result in a
261 /// false negative or a wrong match in the case of an ambiguity.
262 fn rev_from_prefix(
263 &self,
264 prefix: NodePrefix,
265 mut visit: impl FnMut(Node, Revision),
266 from_rev_down: Option<Revision>,
267 prefix_match: Option<Revision>,
268 ) -> Result<Option<(Node, Revision)>, NodeMapError> {
269 let mut found_by_prefix =
270 prefix_match.map(|rev| (*self.node(rev), rev));
271 let from_rev_down = from_rev_down
272 .map(|r| r.0)
273 .unwrap_or_else(|| self.len() as BaseRevision);
274 // Linear scan of the revlog
275 for rev in (-1..from_rev_down).rev() {
276 let rev = Revision(rev as BaseRevision);
277 let candidate_node = if rev == Revision(-1) {
278 NULL_NODE
279 } else {
280 *self.node(rev)
281 };
282 visit(candidate_node, rev);
283 if prefix.is_prefix_of(&candidate_node) {
284 if let Some((found_prefix, found_rev)) = found_by_prefix {
285 if candidate_node != found_prefix || rev != found_rev {
286 return Err(NodeMapError::MultipleResults);
287 }
288 }
289 if prefix.nybbles_len() == candidate_node.nybbles_len() {
290 // Exact match, no need to keep looking
291 return Ok(Some((candidate_node, rev)));
292 }
293 // Only a prefix match, we need to keep traversing to make sure
294 // there is no ambiguity.
295 found_by_prefix = Some((candidate_node, rev))
296 }
297 }
298 Ok(found_by_prefix)
299 }
300 }
301
302 impl<T> RevlogIndexNodeLookup for T where T: RevlogIndex {}
303
304 const REVISION_FLAG_CENSORED: u16 = 1 << 15;
305 const REVISION_FLAG_ELLIPSIS: u16 = 1 << 14;
306 const REVISION_FLAG_EXTSTORED: u16 = 1 << 13;
307 const REVISION_FLAG_HASCOPIESINFO: u16 = 1 << 12;
308 const REVISION_FLAG_HASMETA: u16 = 1 << 11;
309 const REVISION_FLAG_DELTA_IS_SNAPSHOT: u16 = 1 << 10;
310 const REVISION_FLAG_DELTA_HAS_QUALITY: u16 = 1 << 9;
311 const REVISION_FLAG_DELTA_IS_GOOD: u16 = 1 << 8;
312 const REVISION_FLAG_DELTA_P1_IS_SMALL: u16 = 1 << 7;
313 const REVISION_FLAG_DELTA_P2_IS_SMALL: u16 = 1 << 6;
314
315 // Keep this in sync with REVIDX_KNOWN_FLAGS in
316 // mercurial/revlogutils/flagutil.py
317 const REVIDX_KNOWN_FLAGS: u16 = REVISION_FLAG_CENSORED
318 | REVISION_FLAG_ELLIPSIS
319 | REVISION_FLAG_EXTSTORED
320 | REVISION_FLAG_HASCOPIESINFO
321 | REVISION_FLAG_HASMETA
322 | REVISION_FLAG_DELTA_IS_SNAPSHOT
323 | REVISION_FLAG_DELTA_HAS_QUALITY
324 | REVISION_FLAG_DELTA_IS_GOOD
325 | REVISION_FLAG_DELTA_P1_IS_SMALL
326 | REVISION_FLAG_DELTA_P2_IS_SMALL;
327
328 const NULL_REVLOG_ENTRY_FLAGS: u16 = 0;
329
330 const REVIDX_DELTA_INFO_FLAGS: u16 = REVISION_FLAG_DELTA_IS_SNAPSHOT
331 | REVISION_FLAG_DELTA_HAS_QUALITY
332 | REVISION_FLAG_DELTA_IS_GOOD
333 | REVISION_FLAG_DELTA_P1_IS_SMALL
334 | REVISION_FLAG_DELTA_P2_IS_SMALL;
335
336 const LENGTH_NEUTRAL_FLAGS: u16 = REVISION_FLAG_HASCOPIESINFO
337 | REVISION_FLAG_HASMETA
338 | REVIDX_DELTA_INFO_FLAGS;
339
340 #[derive(Debug, derive_more::From, derive_more::Display)]
341 pub enum RevlogError {
342 #[display("invalid revision identifier: {}", "_0")]
343 InvalidRevision(String),
344 /// Working directory is not supported
345 WDirUnsupported,
346 /// Found more than one entry whose ID match the requested prefix
347 AmbiguousPrefix(String),
348 #[from]
349 Other(HgError),
350 }
351
352 impl From<(NodeMapError, String)> for RevlogError {
353 fn from((error, rev): (NodeMapError, String)) -> Self {
354 match error {
355 NodeMapError::MultipleResults => RevlogError::AmbiguousPrefix(rev),
356 NodeMapError::RevisionNotInIndex(rev) => RevlogError::corrupted(
357 format!("nodemap point to revision {} not in index", rev),
358 ),
359 }
360 }
361 }
362
363 fn corrupted<S: AsRef<str>>(context: S) -> HgError {
364 HgError::corrupted(format!("corrupted revlog, {}", context.as_ref()))
365 }
366
367 impl RevlogError {
368 fn corrupted<S: AsRef<str>>(context: S) -> Self {
369 RevlogError::Other(corrupted(context))
370 }
371 }
372
373 #[derive(derive_more::Display, Debug, Copy, Clone, PartialEq, Eq)]
374 pub enum RevlogType {
375 Changelog,
376 Manifestlog,
377 Filelog,
378 /// unknown destination, used by debug command looking at arbitrary file
379 Other,
380 }
381
382 impl TryFrom<usize> for RevlogType {
383 type Error = HgError;
384
385 fn try_from(value: usize) -> Result<Self, Self::Error> {
386 match value {
387 1001 => Ok(Self::Changelog),
388 1002 => Ok(Self::Manifestlog),
389 1003 => Ok(Self::Filelog),
390 1004 => Ok(Self::Other),
391 t => Err(HgError::abort(
392 format!("Unknown revlog type {}", t),
393 exit_codes::ABORT,
394 None,
395 )),
396 }
397 }
398 }
399
400 pub struct Revlog {
401 inner: InnerRevlog,
402 }
403
404 impl Graph for Revlog {
405 fn parents(&self, rev: Revision) -> Result<[Revision; 2], GraphError> {
406 self.index().parents(rev)
407 }
408 }
409 impl Revlog {
410 /// Open a revlog index file.
411 ///
412 /// It will also open the associated data file if index and data are not
413 /// interleaved.
414 pub fn open(
415 // Todo use the `Vfs` trait here once we create a function for mmap
416 store_vfs: &VfsImpl,
417 index_path: impl AsRef<Path>,
418 data_path: Option<&Path>,
419 options: RevlogOpenOptions,
420 revlog_type: RevlogType,
421 ) -> Result<Self, HgError> {
422 Self::open_gen(
423 store_vfs,
424 index_path,
425 data_path,
426 options,
427 None,
428 revlog_type,
429 )
430 }
431
432 fn index(&self) -> &Index {
433 &self.inner.index
434 }
435
436 fn open_gen(
437 // Todo use the `Vfs` trait here once we create a function for mmap
438 store_vfs: &VfsImpl,
439 index_path: impl AsRef<Path>,
440 data_path: Option<&Path>,
441 options: RevlogOpenOptions,
442 nodemap_for_test: Option<nodemap::NodeTree>,
443 revlog_type: RevlogType,
444 ) -> Result<Self, HgError> {
445 let index_path = index_path.as_ref();
446 let index = open_index(store_vfs, index_path, options)?;
447
448 let default_data_path = index_path.with_extension("d");
449 let data_path = data_path.unwrap_or(&default_data_path);
450
451 let nodemap = if index.is_inline() || !options.use_nodemap {
452 None
453 } else {
454 read_persistent_nodemap(store_vfs, index_path, &index)?
455 };
456
457 let nodemap = nodemap_for_test.or(nodemap);
458
459 Ok(Revlog {
460 inner: InnerRevlog::new(
461 Box::new(store_vfs.clone()),
462 index,
463 index_path.to_path_buf(),
464 data_path.to_path_buf(),
465 options.data_config,
466 options.delta_config,
467 options.feature_config,
468 revlog_type,
469 nodemap,
470 ),
471 })
472 }
473
474 /// Return number of entries of the `Revlog`.
475 pub fn len(&self) -> usize {
476 self.index().len()
477 }
478
479 /// Returns `true` if the `Revlog` has zero `entries`.
480 pub fn is_empty(&self) -> bool {
481 self.index().is_empty()
482 }
483
484 /// Returns the node ID for the given revision number, if it exists in this
485 /// revlog
486 pub fn node_from_rev(&self, rev: Revision) -> &Node {
487 self.index().get_entry(rev).hash()
488 }
489
490 /// Like [`Self::node_from_rev`] but checks `rev` first.
491 pub fn node_from_unchecked_rev(
492 &self,
493 rev: UncheckedRevision,
494 ) -> Option<&Node> {
495 Some(self.node_from_rev(self.index().check_revision(rev)?))
496 }
497
498 /// Return the revision number for the given node ID, if it exists in this
499 /// revlog
500 pub fn rev_from_node(
501 &self,
502 node: NodePrefix,
503 ) -> Result<Revision, RevlogError> {
504 self.inner
505 .rev_from_node_prefix(node)?
506 .ok_or_else(|| RevlogError::InvalidRevision(format!("{:x}", node)))
507 }
508
509 /// Returns whether the given revision exists in this revlog.
510 pub fn has_rev(&self, rev: UncheckedRevision) -> bool {
511 self.index().check_revision(rev).is_some()
512 }
513
514 pub fn get_entry(&self, rev: Revision) -> Result<RevlogEntry, RevlogError> {
515 self.inner.get_entry(rev)
516 }
517
518 pub fn get_entry_for_unchecked_rev(
519 &self,
520 rev: UncheckedRevision,
521 ) -> Result<RevlogEntry, RevlogError> {
522 self.inner.get_entry_for_unchecked_rev(rev)
523 }
524
525 /// Returns the delta parent of the given revision.
526 pub fn delta_parent(&self, rev: Revision) -> Revision {
527 if rev == NULL_REVISION {
528 NULL_REVISION
529 } else {
530 self.inner.delta_parent(rev)
531 }
532 }
533
534 /// Returns the link revision (a.k.a. "linkrev") of the given revision.
535 /// Returns an error if the linkrev does not exist in `linked_revlog`.
536 pub fn link_revision(
537 &self,
538 rev: Revision,
539 linked_revlog: &Self,
540 ) -> Result<Revision, RevlogError> {
541 let entry = self.index().get_entry(rev);
542 linked_revlog.index().check_revision(entry.link_revision()).ok_or_else(
543 || {
544 RevlogError::corrupted(format!(
545 "linkrev for rev {} is invalid",
546 rev
547 ))
548 },
549 )
550 }
551
552 /// Return the full data associated to a revision.
553 ///
554 /// All entries required to build the final data out of deltas will be
555 /// retrieved as needed, and the deltas will be applied to the initial
556 /// snapshot to rebuild the final data.
557 pub fn get_data_for_unchecked_rev(
558 &self,
559 rev: UncheckedRevision,
560 ) -> Result<RawData, RevlogError> {
561 if rev == NULL_REVISION.into() {
562 return Ok(RawData::empty());
563 };
564 self.get_entry_for_unchecked_rev(rev)?.data()
565 }
566
567 /// [`Self::get_data_for_unchecked_rev`] for a checked [`Revision`].
568 pub fn get_data(&self, rev: Revision) -> Result<RawData, RevlogError> {
569 if rev == NULL_REVISION {
570 return Ok(RawData::empty());
571 };
572 self.get_entry(rev)?.data()
573 }
574
575 /// Gets the raw uncompressed data stored for a revision, which is either
576 /// the full text or a delta. Panics if `rev` is null.
577 pub fn get_data_incr(
578 &self,
579 rev: Revision,
580 ) -> Result<RawdataBuf, RevlogError> {
581 let index = self.index();
582 let entry = index.get_entry(rev);
583 let delta_base = entry.base_revision_or_base_of_delta_chain();
584 let base = if UncheckedRevision::from(rev) == delta_base {
585 None
586 } else if index.uses_generaldelta() {
587 Some(delta_base)
588 } else {
589 Some(UncheckedRevision(rev.0 - 1))
590 };
591 let data = self.inner.chunk_for_rev(rev)?;
592 Ok(RawdataBuf { base, data })
593 }
594
595 /// Check the hash of some given data against the recorded hash.
596 pub fn check_hash(
597 &self,
598 p1: Revision,
599 p2: Revision,
600 expected: &[u8],
601 data: &[u8],
602 ) -> bool {
603 self.inner.check_hash(p1, p2, expected, data)
604 }
605 }
606
607 pub struct RawdataBuf {
608 // If `Some`, data is a delta.
609 base: Option<UncheckedRevision>,
610 data: RawData,
611 }
612
613 impl<'a> RawdataBuf {
614 fn as_delta(
615 &'a self,
616 ) -> Result<patch::Delta<'a, patch::PlainDeltaPiece<'a>>, RevlogError> {
617 match self.base {
618 None => Ok(patch::Delta::full_snapshot(&self.data)),
619 Some(_) => patch::Delta::new(&self.data),
620 }
621 }
622 }
623
624 /// TODO We should check for version 5.14+ at runtime, but we either should
625 /// add the `nix` dependency to get it efficiently, or vendor the code to read
626 /// both of which are overkill for such a feature. If we need this dependency
627 /// for more things later, we'll use it here too.
628 #[cfg(target_os = "linux")]
629 fn can_advise_populate_read() -> bool {
630 true
631 }
632
633 #[cfg(not(target_os = "linux"))]
634 fn can_advise_populate_read() -> bool {
635 false
636 }
637
638 /// Call `madvise` on the mmap with `MADV_POPULATE_READ` in a separate thread
639 /// to populate the mmap in the background for a small perf improvement.
640 #[cfg(target_os = "linux")]
641 fn advise_populate_read_mmap(mmap: &memmap2::Mmap) {
642 const MADV_POPULATE_READ: i32 = 22;
643
644 // This is fine because the mmap is still referenced for at least
645 // the duration of this function, and the kernel will reject any wrong
646 // address.
647 let ptr = mmap.as_ptr() as u64;
648 let len = mmap.len();
649
650 // Fire and forget. The `JoinHandle` returned by `spawn` is dropped right
651 // after the call, the thread is thus detached. We don't care about success
652 // or failure here.
653 std::thread::spawn(move || unsafe {
654 // mmap's pointer is always page-aligned on Linux. In the case of
655 // file-based mmap (which is our use-case), the length should be
656 // correct. If not, it's not a safety concern as the kernel will just
657 // ignore unmapped pages and return ENOMEM, which we will promptly
658 // ignore, because we don't care about any errors.
659 libc::madvise(ptr as *mut libc::c_void, len, MADV_POPULATE_READ);
660 });
661 }
662
663 #[cfg(not(target_os = "linux"))]
664 fn advise_populate_read_mmap(mmap: &memmap2::Mmap) {}
665
666 /// Open the revlog [`Index`] at `index_path`, through the `store_vfs` and the
667 /// given `options`. This controls whether (and how) we `mmap` the index file,
668 /// and returns an empty buffer if the index does not exist on disk.
669 /// This is only used when doing pure-Rust work, in Python contexts this is
670 /// unused at the time of writing.
671 pub fn open_index(
672 store_vfs: &impl Vfs,
673 index_path: &Path,
674 options: RevlogOpenOptions,
675 ) -> Result<Index, HgError> {
676 let buf: DynBytes = match store_vfs.open(index_path) {
677 Ok(mut file) => {
678 let mut buf = if let Some(threshold) =
679 options.data_config.mmap_index_threshold
680 {
681 let size = store_vfs.file_size(&file)?;
682 if size >= threshold {
683 // TODO madvise populate read in a background thread
684 let mut mmap_options = MmapOptions::new();
685 if !can_advise_populate_read() {
686 // Fall back to populating in the main thread if
687 // post-creation advice is not supported.
688 // Does nothing on platforms where it's not defined.
689 mmap_options.populate();
690 }
691 // Safety is "enforced" by locks and assuming other
692 // processes are well-behaved. If any misbehaving or
693 // malicious process does touch the index, it could lead
694 // to corruption. This is somewhat inherent to file-based
695 // `mmap`, though some platforms have some ways of
696 // mitigating.
697 // TODO linux: set the immutable flag with `chattr(1)`?
698 let mmap = unsafe { mmap_options.map(&file) }
699 .when_reading_file(index_path)?;
700
701 if can_advise_populate_read() {
702 advise_populate_read_mmap(&mmap);
703 }
704
705 Some(DynBytes::new(Box::new(mmap)))
706 } else {
707 None
708 }
709 } else {
710 None
711 };
712
713 if buf.is_none() {
714 let mut data = vec![];
715 file.read_to_end(&mut data).when_reading_file(index_path)?;
716 buf = Some(DynBytes::new(Box::new(data)));
717 }
718 buf.unwrap()
719 }
720 Err(err) => match err {
721 HgError::IoError { error, context, backtrace } => {
722 match error.kind() {
723 ErrorKind::NotFound => DynBytes::default(),
724 _ => {
725 return Err(HgError::IoError {
726 error,
727 context,
728 backtrace,
729 })
730 }
731 }
732 }
733 e => return Err(e),
734 },
735 };
736
737 let index = Index::new(buf, options.index_header())?;
738 Ok(index)
739 }
740
741 /// The revlog entry's bytes and the necessary informations to extract
742 /// the entry's data.
743 #[derive(Clone)]
744 pub struct RevlogEntry<'revlog> {
745 revlog: &'revlog InnerRevlog,
746 rev: Revision,
747 uncompressed_len: i32,
748 p1: Revision,
749 p2: Revision,
750 flags: u16,
751 hash: Node,
752 }
753
754 impl<'revlog> RevlogEntry<'revlog> {
755 pub fn revision(&self) -> Revision {
756 self.rev
757 }
758
759 pub fn node(&self) -> &Node {
760 &self.hash
761 }
762
763 pub fn uncompressed_len(&self) -> Option<u32> {
764 u32::try_from(self.uncompressed_len).ok()
765 }
766
767 pub fn has_p1(&self) -> bool {
768 self.p1 != NULL_REVISION
769 }
770
771 pub fn p1_entry(
772 &self,
773 ) -> Result<Option<RevlogEntry<'revlog>>, RevlogError> {
774 if self.p1 == NULL_REVISION {
775 Ok(None)
776 } else {
777 Ok(Some(self.revlog.get_entry(self.p1)?))
778 }
779 }
780
781 pub fn p2_entry(
782 &self,
783 ) -> Result<Option<RevlogEntry<'revlog>>, RevlogError> {
784 if self.p2 == NULL_REVISION {
785 Ok(None)
786 } else {
787 Ok(Some(self.revlog.get_entry(self.p2)?))
788 }
789 }
790
791 pub fn p1(&self) -> Option<Revision> {
792 if self.p1 == NULL_REVISION {
793 None
794 } else {
795 Some(self.p1)
796 }
797 }
798
799 pub fn p2(&self) -> Option<Revision> {
800 if self.p2 == NULL_REVISION {
801 None
802 } else {
803 Some(self.p2)
804 }
805 }
806
807 pub fn is_censored(&self) -> bool {
808 (self.flags & REVISION_FLAG_CENSORED) != 0
809 }
810
811 pub fn has_length_affecting_flag_processor(&self) -> bool {
812 // Relevant Python code: revlog.size()
813 (self.flags & !LENGTH_NEUTRAL_FLAGS) != 0
814 }
815
816 fn check_data(&self, data: RawData) -> Result<RawData, RevlogError> {
817 if self.revlog.check_hash(self.p1, self.p2, self.hash.as_bytes(), &data)
818 {
819 Ok(data)
820 } else {
821 if (self.flags & REVISION_FLAG_ELLIPSIS) != 0 {
822 return Err(HgError::unsupported(
823 "support for ellipsis nodes is missing",
824 )
825 .into());
826 }
827 Err(corrupted(format!(
828 "hash check failed for revision {}",
829 self.rev
830 ))
831 .into())
832 }
833 }
834
835 /// Get the revision data, without checking it integrity
836 fn data_unchecked(&self) -> Result<RawData, RevlogError> {
837 if self.rev == NULL_REVISION {
838 return Ok(RawData::empty());
839 }
840 if self.is_censored() {
841 return Err(HgError::CensoredNodeError(
842 *self.node(),
843 HgBacktrace::capture(),
844 )
845 .into());
846 }
847 let raw_size = self.uncompressed_len();
848 if let Some(size) = raw_size {
849 if size == 0 {
850 return Ok(RawData::empty());
851 }
852 self.revlog.seen_file_size(u32_u(size));
853 }
854 let cached_rev = self.revlog.get_rev_cache();
855 if let Some(ref cached) = cached_rev {
856 if cached.rev == self.rev {
857 let raw_text = cached.as_data();
858 self.revlog.set_rev_cache_native(self.rev, &raw_text);
859 return Ok(raw_text);
860 }
861 }
862 let cache = cached_rev.as_ref().map(|c| c.as_delta_base());
863 let stop_rev = cache.map(|(r, _)| r);
864 let (chunks, stopped) =
865 self.revlog.chunks_for_chain(self.revision(), stop_rev)?;
866 let (base_text, deltas) = if stopped {
867 if chunks.is_empty() {
868 // The revision is equivalent to another one, just return the
869 // equivalent one.
870 let cache_value =
871 cached_rev.expect("cannot stop without a cache");
872 let raw_text = cache_value.as_data();
873 self.revlog.set_rev_cache_native(self.rev, &raw_text);
874 return Ok(raw_text);
875 }
876 let cache_value = cache.expect("cannot stop without a cache");
877 let base_text = cache_value.1;
878 (base_text, &chunks[..])
879 } else {
880 let base_text = &chunks[0];
881 let deltas = &chunks[1..];
882 if deltas.is_empty() {
883 // The revision is equivalent to another one, just return the
884 // equivalent one.
885 return Ok(chunks
886 .into_iter()
887 .next()
888 .expect("the base must exists"));
889 }
890 (base_text.as_ref(), deltas)
891 };
892 let size = raw_size.map(|l| l as usize).unwrap_or(base_text.len());
893
894 let mut data = CoreRevisionBuffer::new();
895 data.resize(size);
896 patch::build_data_from_deltas(&mut data, base_text, deltas)?;
897 let raw_text: RawData = data.finish().into();
898 self.revlog.set_rev_cache_native(self.rev, &raw_text);
899 Ok(raw_text)
900 }
901
902 /// Get the revision data, checking its integrity in the process
903 pub fn data(&self) -> Result<RawData, RevlogError> {
904 if self.rev == NULL_REVISION {
905 return Ok(RawData::empty());
906 }
907 self.check_data(self.data_unchecked()?)
908 }
909 }
910
911 #[cfg(test)]
912 mod tests {
913 use itertools::Itertools;
914
915 use super::*;
916 use crate::revlog::index::IndexEntryBuilder;
917 use crate::revlog::path_encode::PathEncoding;
918
919 #[test]
920 fn test_empty() {
921 let temp = tempfile::tempdir().unwrap();
922 let vfs = VfsImpl::new(
923 temp.path().to_owned(),
924 false,
925 PathEncoding::DotEncode,
926 );
927 std::fs::write(temp.path().join("foo.i"), b"").unwrap();
928 std::fs::write(temp.path().join("foo.d"), b"").unwrap();
929 let revlog = Revlog::open(
930 &vfs,
931 "foo.i",
932 None,
933 RevlogOpenOptions::default(),
934 RevlogType::Changelog,
935 )
936 .unwrap();
937 assert!(revlog.is_empty());
938 assert_eq!(revlog.len(), 0);
939 assert!(revlog.get_entry_for_unchecked_rev(0.into()).is_err());
940 assert!(!revlog.has_rev(0.into()));
941 assert_eq!(
942 revlog.rev_from_node(NULL_NODE.into()).unwrap(),
943 NULL_REVISION
944 );
945 let null_entry = revlog
946 .get_entry_for_unchecked_rev(NULL_REVISION.into())
947 .ok()
948 .unwrap();
949 assert_eq!(null_entry.revision(), NULL_REVISION);
950 assert!(null_entry.data().unwrap().is_empty());
951 }
952
953 #[test]
954 fn test_inline() {
955 let temp = tempfile::tempdir().unwrap();
956 let vfs = VfsImpl::new(
957 temp.path().to_owned(),
958 false,
959 PathEncoding::DotEncode,
960 );
961 let node0 =
962 Node::from_hex("2ed2a3912a0b24502043eae84ee4b279c18b90dd").unwrap();
963 let node1 =
964 Node::from_hex("b004912a8510032a0350a74daa2803dadfb00e12").unwrap();
965 let node2 =
966 Node::from_hex("dd6ad206e907be60927b5a3117b97dffb2590582").unwrap();
967 let entry0_bytes = IndexEntryBuilder::new()
968 .is_first(true)
969 .with_version(1)
970 .with_inline(true)
971 .with_node(node0)
972 .build();
973 let entry1_bytes = IndexEntryBuilder::new().with_node(node1).build();
974 let entry2_bytes = IndexEntryBuilder::new()
975 .with_p1(Revision(0))
976 .with_p2(Revision(1))
977 .with_node(node2)
978 .build();
979 let contents = vec![entry0_bytes, entry1_bytes, entry2_bytes]
980 .into_iter()
981 .flatten()
982 .collect_vec();
983 std::fs::write(temp.path().join("foo.i"), contents).unwrap();
984 let revlog = Revlog::open(
985 &vfs,
986 "foo.i",
987 None,
988 RevlogOpenOptions::default(),
989 RevlogType::Changelog,
990 )
991 .unwrap();
992
993 let entry0 = revlog.get_entry_for_unchecked_rev(0.into()).ok().unwrap();
994 assert_eq!(entry0.revision(), Revision(0));
995 assert_eq!(*entry0.node(), node0);
996 assert!(!entry0.has_p1());
997 assert_eq!(entry0.p1(), None);
998 assert_eq!(entry0.p2(), None);
999 let p1_entry = entry0.p1_entry().unwrap();
1000 assert!(p1_entry.is_none());
1001 let p2_entry = entry0.p2_entry().unwrap();
1002 assert!(p2_entry.is_none());
1003
1004 let entry1 = revlog.get_entry_for_unchecked_rev(1.into()).ok().unwrap();
1005 assert_eq!(entry1.revision(), Revision(1));
1006 assert_eq!(*entry1.node(), node1);
1007 assert!(!entry1.has_p1());
1008 assert_eq!(entry1.p1(), None);
1009 assert_eq!(entry1.p2(), None);
1010 let p1_entry = entry1.p1_entry().unwrap();
1011 assert!(p1_entry.is_none());
1012 let p2_entry = entry1.p2_entry().unwrap();
1013 assert!(p2_entry.is_none());
1014
1015 let entry2 = revlog.get_entry_for_unchecked_rev(2.into()).ok().unwrap();
1016 assert_eq!(entry2.revision(), Revision(2));
1017 assert_eq!(*entry2.node(), node2);
1018 assert!(entry2.has_p1());
1019 assert_eq!(entry2.p1(), Some(Revision(0)));
1020 assert_eq!(entry2.p2(), Some(Revision(1)));
1021 let p1_entry = entry2.p1_entry().unwrap();
1022 assert!(p1_entry.is_some());
1023 assert_eq!(p1_entry.unwrap().revision(), Revision(0));
1024 let p2_entry = entry2.p2_entry().unwrap();
1025 assert!(p2_entry.is_some());
1026 assert_eq!(p2_entry.unwrap().revision(), Revision(1));
1027 }
1028
1029 #[test]
1030 fn test_nodemap() {
1031 let temp = tempfile::tempdir().unwrap();
1032 let vfs = VfsImpl::new(
1033 temp.path().to_owned(),
1034 false,
1035 PathEncoding::DotEncode,
1036 );
1037
1038 // building a revlog with a forced Node starting with zeros
1039 // This is a corruption, but it does not preclude using the nodemap
1040 // if we don't try and access the data
1041 let node0 =
1042 Node::from_hex("00d2a3912a0b24502043eae84ee4b279c18b90dd").unwrap();
1043 let node1 =
1044 Node::from_hex("b004912a8510032a0350a74daa2803dadfb00e12").unwrap();
1045 let entry0_bytes = IndexEntryBuilder::new()
1046 .is_first(true)
1047 .with_version(1)
1048 .with_inline(true)
1049 .with_node(node0)
1050 .build();
1051 let entry1_bytes = IndexEntryBuilder::new().with_node(node1).build();
1052 let contents = vec![entry0_bytes, entry1_bytes]
1053 .into_iter()
1054 .flatten()
1055 .collect_vec();
1056 std::fs::write(temp.path().join("foo.i"), contents).unwrap();
1057
1058 let mut idx = nodemap::tests::TestNtIndex::new();
1059 idx.insert_node(Revision(0), node0).unwrap();
1060 idx.insert_node(Revision(1), node1).unwrap();
1061
1062 let revlog = Revlog::open_gen(
1063 &vfs,
1064 "foo.i",
1065 None,
1066 RevlogOpenOptions::default(),
1067 Some(idx.nt),
1068 RevlogType::Changelog,
1069 )
1070 .unwrap();
1071
1072 // accessing the data shows the corruption
1073 revlog
1074 .get_entry_for_unchecked_rev(0.into())
1075 .unwrap()
1076 .data()
1077 .unwrap_err();
1078
1079 assert_eq!(
1080 revlog.rev_from_node(NULL_NODE.into()).unwrap(),
1081 Revision(-1)
1082 );
1083 assert_eq!(revlog.rev_from_node(node0.into()).unwrap(), Revision(0));
1084 assert_eq!(revlog.rev_from_node(node1.into()).unwrap(), Revision(1));
1085 assert_eq!(
1086 revlog.rev_from_node(NodePrefix::from_hex("000").unwrap()).unwrap(),
1087 Revision(-1)
1088 );
1089 assert_eq!(
1090 revlog.rev_from_node(NodePrefix::from_hex("b00").unwrap()).unwrap(),
1091 Revision(1)
1092 );
1093 // RevlogError does not implement PartialEq
1094 // (ultimately because io::Error does not)
1095 match revlog
1096 .rev_from_node(NodePrefix::from_hex("00").unwrap())
1097 .expect_err("Expected to give AmbiguousPrefix error")
1098 {
1099 RevlogError::AmbiguousPrefix(_) => (),
1100 e => {
1101 panic!("Got another error than AmbiguousPrefix: {:?}", e);
1102 }
1103 };
1104 }
1105
1106 #[test]
1107 fn test_revision_or_wdir_ord() {
1108 let highest: RevisionOrWdir = Revision(i32::MAX - 1).into();
1109 assert!(highest < RevisionOrWdir::wdir());
1110 }
1111 }