Skip to content

Segfault when using an invalid TID for a BAM HeaderView #505

@tculvahouse-atlasds

Description

@tculvahouse-atlasds

The bug

Hello! I found that indexing into a BAM HeaderView with a TID outside of its range of references causes a segfault. Specifically, this happens when rust_htslib::bam::HeaderView::tid2name(…) is called. Here's a minimal example:

fn main() {
    use ::rust_htslib::bam::{Header, HeaderView};
    let header = Header::new();
    let header_view = HeaderView::from_header(&header);
    _ = header_view.tid2name(0);
}

It looks to me like the problem is that tid2name(…) doesn't check its input before calling the C binding for htslib's sam_hdr_tid2name. Maybe some edit to its definition like this would help, without changing the API:

pub fn tid2name(&self, tid: u32) -> &[u8] {
    if self.target_count() > tid { 
        unsafe { ffi::CStr::from_ptr(htslib::sam_hdr_tid2name(self.inner, tid as i32)).to_bytes() }
    } else {
        panic!(<some error message>)
    }
}

But I'm no expert on the inner workings of htslib, so I'm not certain that that's a complete solution. Just a guess.

From what I can tell, the only place in rust-htslib that tid2name(…) is being used is in the rust_htslib::bam::record::Record implementation of bio_types::genome::AbstractInterval::contig(). That's where I ran into this issue: I called .contig() after setting the Record's TID to an invalid value.

I hope this was helpful!

Some version details

rust-htslib version: 0.51.0

output from cargo -v version:

cargo 1.92.0 (Homebrew)
release: 1.92.0
host: aarch64-apple-darwin
libgit2: 1.9.2 (sys:0.20.2 system)
libcurl: 8.7.1 (sys:0.4.83+curl-8.15.0 system ssl:(SecureTransport) LibreSSL/3.3.6)
os: Mac OS 15.7.3 [64-bit]

output from rustc -v version:

rustc 1.92.0 (ded5c06cf 2025-12-08) (Homebrew)
binary: rustc
commit-hash: ded5c06cf21d2b93bffd5d884aa6e96934ee4234
commit-date: 2025-12-08
host: aarch64-apple-darwin
release: 1.92.0
LLVM version: 21.1.7

Please let me know if there's any other info I ought to provide. Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions