Skip to content

Cram other fixes - #2145

Open
jkbonfield wants to merge 22 commits into
samtools:developfrom
jkbonfield:cram_other_fixes
Open

jkbonfield wants to merge 22 commits into
samtools:developfrom
jkbonfield:cram_other_fixes

Conversation

@jkbonfield

@jkbonfield jkbonfield commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Lots of small changes. Rather than produce 20 PRs, they're all separate commits in a general CRAM misc improvement PR. (The encoder specific and decoder specific ones have their own two PRs - this is everything else that was left in the cram directory.)

It's probably best to review commit by commit rather than the entire files list, as they're each quite simple.

  • Improve cram_extract_block error handling.
  • Fix worst-case memory used by cram_huffman_encode_store.
  • Avoid double free in cram_codec_decoder2encoder on error
  • Fix cram_populate_ref / mfsteal interaction on empty files.
  • Protect against recursion in cram_byte_array_len_decode_init.
  • Fix bugs in tokenise_search_path.
  • Basic validation on CRAM fai loading.
  • Check basic filename validity in expand_cache_path.
  • Fix missing pthread unlocks in cram_get_ref error-on-bgzf_close case
  • Fix decode failure on large queries using bit-based codecs.
  • Some adjustments to accommodate 64-bit values in the encodings.
  • Fix cram-store_container's record_counter encoding.
  • Correct parameter sizing in cram_container_num2offset_
  • Use 64-bit positions in cram_index_build_multiref.
  • Fix bounds checks in expand_cache_path expansion.
  • Improve cram_read_file_def version validation.
  • Improved fread error handling in mfload.
  • Miscellaneous minor cram memory leak fixes.

@daviesrob daviesrob self-assigned this Nov 18, 2026

@daviesrob daviesrob left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Commit 5cca987 (Fix hts_pos_t vs int in cram_get_ref) adds lines goto err_lock;, but the label doesn't turn up until the next commit 6a55074 (Fix missing pthread unlocks in cram_get_ref error-on-bgzf_close case). Ideally the lines for the error handler should be added to the earlier commit so that anyone trying a git bisect that hits it will get something that builds. It should be reasonably easy to sort with an interactive rebase.

Comment thread cram/cram_codecs.c Resolved
Comment thread cram/cram_stats.c Outdated
if (st->h) {
khint_t k;
int i;
int64_t i;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A preexisting issue, but I note that i here (used to hold the value) shadows the the i outside the if statement (used as a loop counter). Now might be a good time to rename it so that doesn't happen (maybe to val, although that does mean you'd get the weird assignment val = kh_key(st->h, k);...)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll rename this i to something.

Note this is also the perfect case for for (int i = 0; ...) { semantics in the loop above, as it properly scopes the variable to the for loop. It's not used anywhere else, but has to be declared as a higher scope due to our request to avoid C99isms (which is too late anyway given it's already in use).

@jkbonfield jkbonfield Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, sharing the same variable name is actually the right approach. Consider the code at present:

    /* Count number of unique symbols */
    for (nvals = i = 0; i < MAX_STAT_VAL; i++) {
        ...
        vals[nvals] = i;
        freqs[nvals] = st->freqs[i];
        ntot += freqs[nvals];
        if (max_val < i) max_val = i;
        if (min_val > i) min_val = i;
        nvals++;
    }

    if (st->h) {
        khint_t k;
        int i;

        for (k = kh_begin(st->h); k != kh_end(st->h); k++) {
            ...
            i = kh_key(st->h, k);
            vals[nvals]=i;
            freqs[nvals] = kh_val(st->h, k);
            ntot += freqs[nvals];
            if (max_val < i) max_val = i;
            if (min_val > i) min_val = i;
            nvals++;
        }
    }

It's the same code twice over, with the same variable naming. i is our value (which perhaps shouldn't be i, but it's consistent at least). It's used for both fixed small values held in the array, or larger values that don't fit into the small array which are obtained by the hash table instead. Using two different variable names is just obscuring the intent.

I think the correct fix therefore would be use the same i in both blocks and just make it int64_t.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. I called it v for vals, which is conveniently short so the code is easy to read, while avoiding the oddity of vals coming from keys. :)

Comment thread cram/cram_stats.c Outdated
if (nvals >= vals_alloc) {
vals_alloc = vals_alloc ? vals_alloc*2 : 1024;
int *vals_tmp = hts_realloc_p(vals, sizeof(*vals), vals_alloc);
int64_t *vals_tmp = hts_realloc_p(vals, sizeof(*vals), vals_alloc);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be a bigger change, so maybe for later, but you could pull this out of the loop by noting that the number of items added should be kh_size(t->h).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I could do - I always forget about kh_size for querying the number of existing buckets. Although it's got a nice symmetry with the fixed array code at present. I guess it still does with the code moved a few lines above. I'll tweak it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

Comment thread cram/mFILE.c
break;
} while (!feof(fp) && (fn == NULL || used < sb.st_size));

if (len == 0 && !feof(fp)) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will treat trying to load an empty file as an error. Is that what we want to happen? I also note that the initial malloc() might return NULL in that case on some platforms.

It might also be a good idea to switch to using fstat() to get the size, to avoid TOCTOU problems and incorrect sizes for symbolic links. And should we allow reading beyond sb.st_size, which might happen if we hit a named pipe or other exotic file type?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't that what the && !feof(fp) is protecting against? A zero length file will be at EOF surely?

Switching to fstat works I think, although it rather makes fn redundant which is fine. I don't know what to do regarding files which are growing during read. It handles that already as fn is optional and when it doesn't exist it just dynamically grows, so being beyond sb.st_size is fine. I don't think it's a major concern really. It's like doing ls -l file; wc file and getting more out of it than the ls said was there. It's not wrong.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, interestingly mFILE.c code is now over 21 years old :-)

https://sourceforge.net/p/staden/code/712/

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I switched to fstat, but avoided checking on sb.st_size changes.

The code was explicitly designed to be able to work from stdin, named pipes, etc. Arguably there's a difference between a file that is changing size, but I think that's a nuance we needn't worry about. It's a snapshot of whatever it had when it loaded it so that's enough.

Encoding huffman symbols for longs (LTF8) is a maximum of 9 bytes per
symbol, not 6.  Although we compute lpend, the safe_ltf8_put was never
fully implemented (unlike get) on the assumption that we've
pre-assigned the buffers already.

Also fixed safe_itf8_put and safe_ltf8_put to actually be safe when
given an end pointer.  We still have the fast path when not near the
buffer end.

Finally, modified the error checking in cram_codecs.  Our err checking
on varint_put32_blk was correct due to -1 being an error, but for
safety of (ptr += varint_put32) we return 0 there.  Extended the
checks to apply to the non-block version of the itf8/ltf8 putting
too.

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
A failure in the E_BYTE_ARRAY_LEN case freed len_codec and val_codec,
but they're also still in the input 'c' cram_codec, meaning they're
freed there too.

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
An empty file is an error, but it could cause reading from a null
pointer.  This is a bit complicated by mfsteal which previously
destroyed mf when it's empty, further complicated by mf->data being
NULL or not-NULL for a memory allocation or mmap.  We cover both cases
and consider empty references as an error.  (We can have no alignments
against zero length sequences so they should be unmapped.)

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
This function is only valid for byte arrays, but the lack of a type
check meants the E_INT len_codec or val_codec could recurse many times
given a sufficiently complex compression header.

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
This code is ancient (predating htslib), but also had some glitches in
certain URIs leading to small reads or write overflows.  The inputs are
controlled by environment variables rather than file data.

Problem strings:

"http:"         - read overflow
"http:/"        - read/write overflow
"http:/foo"     - read/write overflow
"http::10"      - read overflow
"http://a/"     - truncated early and didn't add implicit "./"

There are some subtle differences too in tokenisation

"http:::://a/"  - Was "http::://a/", now "http::", "//a/" (both nonsense)
"http://x:/tmp" - Was "http://host:/tmp" (wrong), now "http://host", "/tmp"

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
Amongst other things, bases_per_line of 0 gives a divide-by-zero
error.  Also improve memory freeing.

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
This is used for inserting an M5 tag into a REF_PATH.
We could scan for [0-9a-f] hex digits, but malformed md5 strings just
lead to being unable to find the file.

The only potential glitch is using M5=../../some/path to escape the
requested REF_PATH directory, although the impact of this is it'll
promptly fail the md5sum validation unless it really is the reference
we expect it to be.  Hence this is simply a nicety.

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
Also validate start is within ref length.  We did this for end, but
not start.  These could get passed into load_ref_portion (which has
also gained some minimal range checking).  The consequences of getting
these wrong however is either attempting to malloc a negative size and
failing, or simply reading from the wrong part of the file and failing
an MD5sum validation check.

Also simplified cram_get_ref with a dedicated error handler.

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
I don't think we were ever likely to trigger it, but asking to decode
a large array of items using over 268MB would fail, claiming the block
is too small.

This arose due to overly tight error checking in 93094c7, presumably
concerned over the impact of size_t on a 32-bit platform.
Being explicit to 64-bit maths resolves this.

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
These were added only for CRAM v4 so they're no longer active bugs,
but we didn't fully remove support for long values. That said, we also
didn't managed to fully convert the old 32-bit only code to 64-bit,
with a few missing data types changes.  Making these consistent.

- cram_huffman_encode_long and cram_codec_decoder2encoder both fetched
  the huffman symbol (which is 64-bit) as 32-bit.

- cram_stats_encoding used a hash table with 64-bit keys, but stored
  those keys in an int again in some cases.

Also questionable is cram_stats_encoding max_val=0 initialisation.
This implies we can never track the frequency of negatives, but that
is true for 32-bit too.  It's possible this is dealt with elsewhere,
such as the various "offset" encoder fields.

(Note some encodings, such as BETA, only have 32-bit offsets, so the
spec would have had to change there too.)

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
We had the logic swapped for v2 and v3 with regards to 32-bit and
64-bit (itf8 vs ltf8) encodings.   It's unused in samtools/htslib
except for samtools reheader, which uses it only on the first
container (header), so it's a NOP.

NB: ITF8 and LTF8 encodings start to differ when nrecs >= 1<<28.

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
A bit of a technicality: int vs int64_t, but for container numbers.
(I can't imagine us ever going beyond 2 billion cram containers.)

TODO: fix the use of it in samtools cat too.

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
(Also a technicality as CRAM 3.x doesn't support 64-bit positions, but
just incase we ever update it we need to be consistent.)

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
A %x (or any other unrecognised % encoding) wasn't decrementing sz.
This means our overflow detection was coming up short.

Impact: potential stack overflow where an attacker has control over
the REF_CACHE environment variable. (Very unlikely.)

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
A rogue CRAM 4.0 signature was still permitted, even though we only
decode using 3.x semantics.

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
A non-EOF error could potentially cause infinite loops.

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
These are all on error handling cases.  We haven't found any leaks with
normal correctly behaving data.

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
In the second pass iterating over the st->h hash table we already know
the number of items we'll add, so do a single reallocation instead of
a check per loop iteration.

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
This mades the fn field redudant.

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
@jkbonfield

Copy link
Copy Markdown
Contributor Author

Tweaked the old "Fix bounds checks in expand_cache_path expansion" commit as the fix it did needed to be in two places rather than one. (Subsequently found by a new round of Claude analysis)

Comment thread cram/cram_stats.c Outdated
int i;

if (nvals + kh_size(st->h) >= vals_alloc) {
vals_alloc = vals_alloc ? vals_alloc*2 : 1024;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could leave vals_alloc undersized if vals_alloc > 0 && nvals + kh_size(st->h) >= vals_alloc*2. As this is only going to grow once, it could just be made exactly the right size.

Suggested change
vals_alloc = vals_alloc ? vals_alloc*2 : 1024;
vals_alloc = nvals + kh_size(st->h);

Although I also notice that after this function carefully grows the arrays and stores data in them, it just throws everything away again without using the contents. So we could make it much simpler and faster by removing the code that builds the arrays, and just leave the lines that update the bits that are used (nvals, max_val and min_val).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on simply removing the allocations. The history of why it kept vals and freqs arrays is so old it's not worth keeping (and predates the inclusion of CRAM into htslib). They should have been removed when we culled the code that analysed them.

The allocation of vals and freqs arrays predates this even arriving in
htslib.  The history comes from io_lib which originally aggregated the list
of values and their frequencies into arrays so it could quantify the number
of bits used for HUFFMAN, BETA, UNARY, GAMMA and SUB-EXPONENTIAL encoding
schemes.  This was later dropped in favour of HUFFMAN for small alphabets
and BETA for bigger ones, and later still simply EXTERNAL for everything
except single-value data series.

Signed-off-by: James Bonfield <jkb@sanger.ac.uk>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants