From ca3667721ab0dda35274def5ea91919d2bfbf4cb Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Wed, 11 Nov 2026 14:52:08 +0000 Subject: [PATCH 01/22] Fix worst-case memory used by cram_huffman_encode_store. 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 --- cram/cram_codecs.c | 83 +++++++++++++++++++++++++++++----------------- cram/cram_io.c | 62 ++++++++++++++++++++++++++-------- 2 files changed, 100 insertions(+), 45 deletions(-) diff --git a/cram/cram_codecs.c b/cram/cram_codecs.c index f14f66310..b53fa134b 100644 --- a/cram/cram_codecs.c +++ b/cram/cram_codecs.c @@ -551,13 +551,14 @@ int cram_external_encode_store(cram_codec *c, cram_block *b, char *prefix, len += l; } - tp += c->vv->varint_put32(tp, tpend, c->u.e_external.content_id); - len += (n = c->vv->varint_put32_blk(b, c->codec)); r |= n; - len += (n = c->vv->varint_put32_blk(b, tp-tmp)); r |= n; + tp += (n = c->vv->varint_put32(tp, tpend, c->u.e_external.content_id)); + r |= n<=0; + len += (n = c->vv->varint_put32_blk(b, c->codec)); r |= n<=0; + len += (n = c->vv->varint_put32_blk(b, tp-tmp)); r |= n<=0; BLOCK_APPEND(b, tmp, tp-tmp); len += tp-tmp; - if (r > 0) + if (r == 0) return len; block_err: @@ -720,15 +721,15 @@ int cram_beta_encode_store(cram_codec *c, cram_block *b, len += l; } - len += (n = c->vv->varint_put32_blk(b, c->codec)); r |= n; + len += (n = c->vv->varint_put32_blk(b, c->codec)); r |= n<=0; // codec length len += (n = c->vv->varint_put32_blk(b, c->vv->varint_size(c->u.e_beta.offset) + c->vv->varint_size(c->u.e_beta.nbits))); - r |= n; - len += (n = c->vv->varint_put32_blk(b, c->u.e_beta.offset)); r |= n; - len += (n = c->vv->varint_put32_blk(b, c->u.e_beta.nbits)); r |= n; + r |= n<=0; + len += (n = c->vv->varint_put32_blk(b, c->u.e_beta.offset)); r |= n<=0; + len += (n = c->vv->varint_put32_blk(b, c->u.e_beta.nbits)); r |= n<=0; - if (r > 0) return len; + if (r == 0) return len; block_err: return -1; @@ -1525,48 +1526,59 @@ int cram_huffman_encode_store(cram_codec *c, cram_block *b, char *prefix, * * Symbols themselves could be 5 bytes (eg -1 is 5 bytes in itf8). * - * Therefore 6*ncodes + 5 + 5 + 1 + 5 is max memory + * Therefore 6*ncodes + 5 + 5 + 1 + 5 is max memory (ITF8) + * 10*ncodes + 5 + 5 + 1 + 5 for LTF8. */ - char *tmp = hts_malloc_pse(6, c->u.e_huffman.nvals, 0, 16); - char *tp = tmp, *tpend = tmp+6*c->u.e_huffman.nvals+16; - + size_t per_sym = c->u.e_huffman.option == E_LONG ? 10 : 6; + char *tmp = hts_malloc_pse(per_sym, c->u.e_huffman.nvals, 0, 16); if (!tmp) return -1; + char *tp = tmp, *tpend = tmp + per_sym*c->u.e_huffman.nvals + 16; + if (prefix) { size_t l = strlen(prefix); BLOCK_APPEND(b, prefix, l); len += l; } - tp += c->vv->varint_put32(tp, tpend, c->u.e_huffman.nvals); + tp += (n = c->vv->varint_put32(tp, tpend, c->u.e_huffman.nvals)); + r |= n<=0; if (c->u.e_huffman.option == E_LONG) { for (i = 0; i < c->u.e_huffman.nvals; i++) { - tp += c->vv->varint_put64(tp, tpend, codes[i].symbol); + tp += (n = c->vv->varint_put64(tp, tpend, codes[i].symbol)); + r |= n<=0; } } else if (c->u.e_huffman.option == E_INT || c->u.e_huffman.option == E_BYTE) { for (i = 0; i < c->u.e_huffman.nvals; i++) { - tp += c->vv->varint_put32(tp, tpend, codes[i].symbol); + tp += (n = c->vv->varint_put32(tp, tpend, codes[i].symbol)); + r |= n<=0; } } else { + free(tmp); return -1; } - tp += c->vv->varint_put32(tp, tpend, c->u.e_huffman.nvals); - for (i = 0; i < c->u.e_huffman.nvals; i++) - tp += c->vv->varint_put32(tp, tpend, codes[i].len); + tp += (n = c->vv->varint_put32(tp, tpend, c->u.e_huffman.nvals)); + r |= n <= 0; + for (i = 0; i < c->u.e_huffman.nvals; i++) { + tp += (n = c->vv->varint_put32(tp, tpend, codes[i].len)); + r |= n<=0; + } - len += (n = c->vv->varint_put32_blk(b, c->codec)); r |= n; - len += (n = c->vv->varint_put32_blk(b, tp-tmp)); r |= n; + len += (n = c->vv->varint_put32_blk(b, c->codec)); r |= n<=0; + len += (n = c->vv->varint_put32_blk(b, tp-tmp)); r |= n<=0; BLOCK_APPEND(b, tmp, tp-tmp); len += tp-tmp; free(tmp); + tmp = NULL; - if (r > 0) + if (r == 0) return len; block_err: + free(tmp); return -1; } @@ -1924,12 +1936,12 @@ int cram_byte_array_len_encode_store(cram_codec *c, cram_block *b, len3 = tc->store(tc, b_val, NULL, version); if (len3 < 0) goto block_err; - len += (n = c->vv->varint_put32_blk(b, c->codec)); r |= n; - len += (n = c->vv->varint_put32_blk(b, len2+len3)); r |= n; + len += (n = c->vv->varint_put32_blk(b, c->codec)); r |= n<=0; + len += (n = c->vv->varint_put32_blk(b, len2+len3)); r |= n<=0; BLOCK_APPEND(b, BLOCK_DATA(b_len), BLOCK_SIZE(b_len)); BLOCK_APPEND(b, BLOCK_DATA(b_val), BLOCK_SIZE(b_val)); - if (r <= 0) + if (r) goto block_err; cram_free_block(b_len); @@ -2147,7 +2159,7 @@ void cram_byte_array_stop_encode_free(cram_codec *c) { int cram_byte_array_stop_encode_store(cram_codec *c, cram_block *b, char *prefix, int version) { - int len = 0; + int len = 0, r = 0, n; char buf[20], *cp = buf; if (prefix) { @@ -2156,25 +2168,34 @@ int cram_byte_array_stop_encode_store(cram_codec *c, cram_block *b, len += l; } - cp += c->vv->varint_put32(cp, buf+20, c->codec); + cp += (n = c->vv->varint_put32(cp, buf+20, c->codec)); + r |= n<=0; if (CRAM_MAJOR_VERS(version) == 1) { - cp += c->vv->varint_put32(cp, buf+20, 5); + cp += (n = c->vv->varint_put32(cp, buf+20, 5)); + r |= n <= 0; *cp++ = c->u.e_byte_array_stop.stop; *cp++ = (c->u.e_byte_array_stop.content_id >> 0) & 0xff; *cp++ = (c->u.e_byte_array_stop.content_id >> 8) & 0xff; *cp++ = (c->u.e_byte_array_stop.content_id >> 16) & 0xff; *cp++ = (c->u.e_byte_array_stop.content_id >> 24) & 0xff; } else { - cp += c->vv->varint_put32(cp, buf+20, 1 + - c->vv->varint_size(c->u.e_byte_array_stop.content_id)); + cp += (n = c->vv->varint_put32 + (cp, buf+20, + 1 + c->vv->varint_size(c->u.e_byte_array_stop.content_id))); + r |= n<=0; *cp++ = c->u.e_byte_array_stop.stop; - cp += c->vv->varint_put32(cp, buf+20, c->u.e_byte_array_stop.content_id); + cp += (n = c->vv->varint_put32(cp, buf+20, + c->u.e_byte_array_stop.content_id)); + r |= n<=0; } BLOCK_APPEND(b, buf, cp-buf); len += cp-buf; + if (r) + return -1; + return len; block_err: diff --git a/cram/cram_io.c b/cram/cram_io.c index 5abd7d54d..45e1916d2 100644 --- a/cram/cram_io.c +++ b/cram/cram_io.c @@ -743,17 +743,46 @@ static int64_t safe_ltf8_get(char **cp, const char *endp, int *err) { } } -// Wrapper for now -static int safe_itf8_put(char *cp, char *cp_end, int32_t val) { - return itf8_put(cp, val); + +static inline int itf8_size(int64_t v) { + return ( (!((v)&~0x7f))?1 + :(!((v)&~0x3fff))?2 + :(!((v)&~0x1fffff))?3 + :(!((v)&~0xfffffff))?4 + :5); } -static int safe_ltf8_put(char *cp, char *cp_end, int64_t val) { - return ltf8_put(cp, val); +static inline int ltf8_size(int64_t v) { + return ( (!((v)&~0x7f))?1 + :(!((v)&~0x3fff))?2 + :(!((v)&~0x1fffff))?3 + :(!((v)&~0xfffffff))?4 + :(!((v)&~0x7ffffffff))?5 + :(!((v)&~0x3ffffffffff))?6 + :(!((v)&~0x1ffffffffffff))?7 + :(!((v)&~0xffffffffffffff))?8 + :9); } -static int itf8_size(int64_t v) { - return ((!((v)&~0x7f))?1:(!((v)&~0x3fff))?2:(!((v)&~0x1fffff))?3:(!((v)&~0xfffffff))?4:5); +// Returns 0 so we can do cp += safe_itf8_put(...) without decrementing +// pointer. (We should check, but this is the safer option for code that +// doesn't.) +static int safe_itf8_put(char *cp, char *cp_end, int32_t val) { + if (!cp_end || cp_end - cp >= 5) + return itf8_put(cp, val); + if (cp_end - cp >= itf8_size(val)) + return itf8_put(cp, val); + else + return 0; +} + +static int safe_ltf8_put(char *cp, char *cp_end, int64_t val) { + if (!cp_end || cp_end - cp >= 9) + return ltf8_put(cp, val); + if (cp_end - cp >= ltf8_size(val)) + return ltf8_put(cp, val); + else + return 0; } //----------------------------------------------------------------------------- @@ -1248,14 +1277,18 @@ uint32_t cram_block_size(cram_block *b) { int cram_write_block(cram_fd *fd, cram_block *b) { char vardata[100]; int vardata_o = 0; + int r = 0, n; assert(b->method != RAW || (b->comp_size == b->uncomp_size)); if (hputc(b->method, fd->fp) == EOF) return -1; if (hputc(b->content_type, fd->fp) == EOF) return -1; - vardata_o += fd->vv.varint_put32(vardata , vardata+100, b->content_id); - vardata_o += fd->vv.varint_put32(vardata+vardata_o, vardata+100, b->comp_size); - vardata_o += fd->vv.varint_put32(vardata+vardata_o, vardata+100, b->uncomp_size); + vardata_o += (n = fd->vv.varint_put32(vardata , vardata+100, b->content_id)); + r |= n <= 0; + vardata_o += (n = fd->vv.varint_put32(vardata+vardata_o, vardata+100, b->comp_size)); + r |= n <= 0; + vardata_o += (n = fd->vv.varint_put32(vardata+vardata_o, vardata+100, b->uncomp_size)); + r |= n <= 0; if (vardata_o != hwrite(fd->fp, vardata, vardata_o)) return -1; @@ -1278,9 +1311,10 @@ int cram_write_block(cram_fd *fd, cram_block *b) { *cp++ = b->method; *cp++ = b->content_type; - cp += fd->vv.varint_put32(cp, dat+100, b->content_id); - cp += fd->vv.varint_put32(cp, dat+100, b->comp_size); - cp += fd->vv.varint_put32(cp, dat+100, b->uncomp_size); + cp += (n = fd->vv.varint_put32(cp, dat+100, b->content_id)); r |= n <= 0; + cp += (n = fd->vv.varint_put32(cp, dat+100, b->comp_size)); r |= n <= 0; + cp += (n = fd->vv.varint_put32(cp, dat+100, b->uncomp_size)); r |= n <= 0; + crc = crc32(0L, (uc *)dat, cp-dat); if (b->method == RAW) { @@ -1293,7 +1327,7 @@ int cram_write_block(cram_fd *fd, cram_block *b) { return -1; } - return 0; + return r ? -1 : 0; } /* From 31ed3b64cb8269968c55267c64bfd15756ebd853 Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Wed, 11 Nov 2026 16:45:45 +0000 Subject: [PATCH 02/22] Avoid double free in cram_codec_decoder2encoder on error 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 --- cram/cram_codecs.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cram/cram_codecs.c b/cram/cram_codecs.c index b53fa134b..45d06919f 100644 --- a/cram/cram_codecs.c +++ b/cram/cram_codecs.c @@ -2473,6 +2473,8 @@ int cram_codec_decoder2encoder(cram_fd *fd, cram_codec *c) { t->u.e_byte_array_len.val_codec = c->u.byte_array_len.val_codec; if (cram_codec_decoder2encoder(fd, t->u.e_byte_array_len.len_codec) == -1 || cram_codec_decoder2encoder(fd, t->u.e_byte_array_len.val_codec) == -1) { + t->u.e_byte_array_len.len_codec = NULL; // avoid double free + t->u.e_byte_array_len.val_codec = NULL; t->free(t); return -1; } From 3139dba5387ffb4babbeeb7620fb917b7931e12a Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Wed, 11 Nov 2026 16:59:19 +0000 Subject: [PATCH 03/22] Fix cram_populate_ref / mfsteal interaction on empty files. 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 --- cram/cram_io.c | 15 +++++++++++++-- cram/mFILE.c | 5 ++--- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/cram/cram_io.c b/cram/cram_io.c index 45e1916d2..574713bb3 100644 --- a/cram/cram_io.c +++ b/cram/cram_io.c @@ -2831,11 +2831,22 @@ static int cram_populate_ref(cram_fd *fd, int id, ref_entry *r) { r->seq = mfsteal(mf, &sz); if (r->seq) { r->mf = NULL; - } else { - // keep mf around as we couldn't detach + } else if (mf->data) { + // keep mf around as we couldn't detach, eg mmaped r->seq = mf->data; r->mf = mf; + } else { + // Empty file, but mf->data = NULL. We treat that as an error. + mfdestroy(mf); + return -1; } + + if (sz == 0) { + // An empty file but mf->data != NULL is still an error. + ref_entry_free_seq(r); + return -1; + } + r->length = sz; r->is_md5 = 1; r->validated_md5 = 1; diff --git a/cram/mFILE.c b/cram/mFILE.c index 3ecdca39c..c1596a173 100644 --- a/cram/mFILE.c +++ b/cram/mFILE.c @@ -429,11 +429,10 @@ void *mfsteal(mFILE *mf, size_t *size_out) { void *data; if (!mf) return NULL; + if (size_out) *size_out = mf->size; + if (!mf->data) return NULL; data = mf->data; - - if (NULL != size_out) *size_out = mf->size; - if (mfdetach(mf) != 0) return NULL; From 99ca6c786212948ebef44b1a33051e7f20bf4fc9 Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Wed, 11 Nov 2026 17:19:18 +0000 Subject: [PATCH 04/22] Protect against recursion in cram_byte_array_len_decode_init. 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 --- cram/cram_codecs.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cram/cram_codecs.c b/cram/cram_codecs.c index 45d06919f..3e377650e 100644 --- a/cram/cram_codecs.c +++ b/cram/cram_codecs.c @@ -1843,6 +1843,9 @@ cram_codec *cram_byte_array_len_decode_init(cram_block_compression_hdr *hdr, char *cp = data; char *endp = data + size; + if (option != E_BYTE_ARRAY && option != E_BYTE_ARRAY_BLOCK) + return NULL; + if (!(c = malloc(sizeof(*c)))) return NULL; From 500b283e8d52805ab166099922d7dd2e8bd4585b Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Thu, 12 Nov 2026 12:12:53 +0000 Subject: [PATCH 05/22] Fix bugs in tokenise_search_path. 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 --- cram/open_trace_file.c | 41 +++++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/cram/open_trace_file.c b/cram/open_trace_file.c index 0d5489f1c..2e51713dd 100644 --- a/cram/open_trace_file.c +++ b/cram/open_trace_file.c @@ -83,6 +83,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "../htslib/hfile.h" #include "../htslib/hts_log.h" #include "../htslib/hts.h" +#include "../textutils_internal.h" /* * Returns whether the path refers to a regular file. @@ -138,6 +139,7 @@ char *tokenise_search_path(const char *searchpath) { !strncmp(&searchpath[i], "URL=http:", 9) || !strncmp(&searchpath[i], "URL=https:",10)|| !strncmp(&searchpath[i], "URL=ftp:", 8))) { + // Copy protocol + colon(s) + "//" do { newsearch[j++] = searchpath[i]; } while (i all colons are literal chars to copy if (searchpath[i] == path_sep) { /* Skip blank path components */ if (j && newsearch[j-1] != 0) newsearch[j++] = 0; } else { - newsearch[j++] = searchpath[i]; + if (searchpath[i]) + newsearch[j++] = searchpath[i]; } } - if (j) + if (j && newsearch[j-1] != 0) newsearch[j++] = 0; newsearch[j++] = '.'; newsearch[j++] = '/'; @@ -176,6 +186,21 @@ char *tokenise_search_path(const char *searchpath) { return newsearch; } +// Can test tokenise_search_path above with: +// cc -I. -g -DOTF_MAIN cram/open_trace_file.c cram/mFILE.c -L. -lhts -Wl,-rpath,`pwd` +#ifdef OTF_MAIN +int main(int argc, char **argv) { + if (argc < 2) + exit(1); + char *newsearch = tokenise_search_path(argv[1]); + for (char *ele = newsearch; *ele; ele += strlen(ele)+1) { + printf("Path: '%s', len %ld\n", ele, strlen(ele)); + } + free(newsearch); + return 0; +} +#endif + static char *expand_path(const char *file, const char *dirname, int max_s_digits); From 805cc949200ffb06ad90b63903be6c13f49eaa23 Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Thu, 12 Nov 2026 12:34:54 +0000 Subject: [PATCH 06/22] Basic validation on CRAM fai loading. Amongst other things, bases_per_line of 0 gives a divide-by-zero error. Also improve memory freeing. Signed-off-by: James Bonfield --- cram/cram_io.c | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/cram/cram_io.c b/cram/cram_io.c index 574713bb3..2d79a1200 100644 --- a/cram/cram_io.c +++ b/cram/cram_io.c @@ -2330,9 +2330,12 @@ static refs_t *refs_load_fai(refs_t *r_orig, const char *fn, int is_err) { if (!(r = refs_create())) goto err; - if (r->fp) - if (bgzf_close(r->fp) != 0) + if (r->fp) { + if (bgzf_close(r->fp) != 0) { + r->fp = NULL; goto err; + } + } r->fp = NULL; /* Look for a FASTA##idx##FAI format */ @@ -2370,18 +2373,19 @@ static refs_t *refs_load_fai(refs_t *r_orig, const char *fn, int is_err) { goto err; } while (hgets(line, 8192, fp) != NULL) { - ref_entry *e = malloc(sizeof(*e)); + ref_entry *e = calloc(1, sizeof(*e)); char *cp; int n; khint_t k; if (!e) - return NULL; + goto err; // id for (cp = line; *cp && !isspace_c(*cp); cp++) ; - *cp++ = 0; + if (*cp) + *cp++ = 0; e->name = string_dup(r->pool, line); // length @@ -2407,6 +2411,13 @@ static refs_t *refs_load_fai(refs_t *r_orig, const char *fn, int is_err) { // filename e->fn = r->fn; + if (e->length < 0 || e->offset < 0 || e->bases_per_line < 0 || + e->line_length <= 0 || e->line_length < e->bases_per_line || + !e->name) { + free(e); + goto err; + } + e->count = 0; e->seq = NULL; e->mf = NULL; @@ -2416,7 +2427,7 @@ static refs_t *refs_load_fai(refs_t *r_orig, const char *fn, int is_err) { k = kh_put(refs, r->h_meta, e->name, &n); if (-1 == n) { free(e); - return NULL; + goto err; } if (n) { @@ -3031,6 +3042,9 @@ static char *load_ref_portion(BGZF *fp, ref_entry *e, * space (the diff between line_length and bases_per_line) only occurs * at the end of a line of text. */ + if (e->line_length && e->bases_per_line <= 0) + return NULL; + offset = e->line_length ? e->offset + (start-1)/e->bases_per_line * e->line_length + (start-1) % e->bases_per_line From eb83d05542d3a9e29fa399b5c107bb1b472d07a6 Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Thu, 12 Nov 2026 12:40:21 +0000 Subject: [PATCH 07/22] Check basic filename validity in expand_cache_path. 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 --- cram/cram_io.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/cram/cram_io.c b/cram/cram_io.c index 2d79a1200..4a560a829 100644 --- a/cram/cram_io.c +++ b/cram/cram_io.c @@ -2676,6 +2676,9 @@ static int expand_cache_path(char *path, char *dir, const char *fn) { size_t len; size_t sz = PATH_MAX; + if (strchr(fn, '/')) + return -1; + while ((cp = strchr(dir, '%'))) { if (cp-dir >= sz) return -1; strncpy(path, dir, cp-dir); @@ -2786,6 +2789,10 @@ static int cram_populate_ref(cram_fd *fd, int id, ref_entry *r) { goto no_M5; hts_log_info("Querying ref %s", tag->str+3); + if (strchr(tag->str+3, '/')) { + hts_log_error("Invalid M5 tag"); + goto no_M5; + } /* Use cache if available */ if (local_cache && *local_cache) { From 9f97468dd633fb7c903ea70e40ca2a7a6dddb93f Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Thu, 12 Nov 2026 12:56:45 +0000 Subject: [PATCH 08/22] Fix hts_pos_t vs int in cram_get_ref. 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 --- cram/cram_io.c | 51 ++++++++++++++++++++++++++------------------------ 1 file changed, 27 insertions(+), 24 deletions(-) diff --git a/cram/cram_io.c b/cram/cram_io.c index 4a560a829..80a04345f 100644 --- a/cram/cram_io.c +++ b/cram/cram_io.c @@ -3038,6 +3038,10 @@ static char *load_ref_portion(BGZF *fp, ref_entry *e, off_t offset, len; char *seq; + if (start < 1) + start = 1; + if (end < 1) + end = 1; if (end < start) end = start; @@ -3220,7 +3224,7 @@ ref_entry *cram_ref_load(refs_t *r, int id, int is_md5) { char *cram_get_ref(cram_fd *fd, int id, hts_pos_t start, hts_pos_t end) { ref_entry *r; char *seq; - int ostart = start; + hts_pos_t ostart = start; if (id == -1 || start < 1) return NULL; @@ -3273,15 +3277,20 @@ char *cram_get_ref(cram_fd *fd, int id, hts_pos_t start, hts_pos_t end) { hts_log_warning("Failed to populate reference \"%s\"", r->name); hts_log_warning("See https://www.htslib.org/doc/reference_seqs.html for further suggestions"); - pthread_mutex_unlock(&fd->refs->lock); - pthread_mutex_unlock(&fd->ref_lock); - return NULL; + goto err_lock; } r = fd->refs->ref_id[id]; + if (ostart > r->length) + goto err_lock; + if (fd->unsorted) cram_ref_incr_locked(fd->refs, id); } + // Duplicate of above to cover the r->length != 0 case, while avoiding + // ref-count leakages + if (ostart > r->length) + goto err_lock; /* * We now know that we the filename containing the reference, so check @@ -3290,8 +3299,8 @@ char *cram_get_ref(cram_fd *fd, int id, hts_pos_t start, hts_pos_t end) { */ if (end < 1) end = r->length; - if (end >= r->length) - end = r->length; + if (end > r->length) + end = r->length; if (end - start >= 0.5*r->length || fd->shared_ref) { start = 1; @@ -3314,11 +3323,8 @@ char *cram_get_ref(cram_fd *fd, int id, hts_pos_t start, hts_pos_t end) { cram_ref_incr_locked(fd->refs, id); } else { ref_entry *e; - if (!(e = cram_ref_load(fd->refs, id, r->is_md5))) { - pthread_mutex_unlock(&fd->refs->lock); - pthread_mutex_unlock(&fd->ref_lock); - return NULL; - } + if (!(e = cram_ref_load(fd->refs, id, r->is_md5))) + goto err_lock; /* unsorted data implies cache ref indefinitely, to avoid * continually loading and unloading. @@ -3361,9 +3367,7 @@ char *cram_get_ref(cram_fd *fd, int id, hts_pos_t start, hts_pos_t end) { } fd->ref = NULL; fd->ref_id = id; - pthread_mutex_unlock(&fd->refs->lock); - pthread_mutex_unlock(&fd->ref_lock); - return NULL; + goto err_lock; } /* Open file if it's not already the current open reference */ @@ -3372,18 +3376,12 @@ char *cram_get_ref(cram_fd *fd, int id, hts_pos_t start, hts_pos_t end) { if (bgzf_close(fd->refs->fp) != 0) return NULL; fd->refs->fn = r->fn; - if (!(fd->refs->fp = bgzf_open_ref(fd->refs->fn, "r", r->is_md5))) { - pthread_mutex_unlock(&fd->refs->lock); - pthread_mutex_unlock(&fd->ref_lock); - return NULL; - } + if (!(fd->refs->fp = bgzf_open_ref(fd->refs->fn, "r", r->is_md5))) + goto err_lock; } - if (!(fd->ref = load_ref_portion(fd->refs->fp, r, start, end))) { - pthread_mutex_unlock(&fd->refs->lock); - pthread_mutex_unlock(&fd->ref_lock); - return NULL; - } + if (!(fd->ref = load_ref_portion(fd->refs->fp, r, start, end))) + goto err_lock; if (fd->ref_free) free(fd->ref_free); @@ -3398,6 +3396,11 @@ char *cram_get_ref(cram_fd *fd, int id, hts_pos_t start, hts_pos_t end) { pthread_mutex_unlock(&fd->ref_lock); return seq ? seq + ostart - start : NULL; + + err_lock: // an error needing both locks unlocking. + pthread_mutex_unlock(&fd->refs->lock); + pthread_mutex_unlock(&fd->ref_lock); + return NULL; } /* From 5e14072f61c3f3a40ddf1ec735123dd514a5aa1c Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Thu, 12 Nov 2026 13:05:53 +0000 Subject: [PATCH 09/22] Fix missing pthread unlocks in cram_get_ref error-on-bgzf_close case Signed-off-by: James Bonfield --- cram/cram_io.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/cram/cram_io.c b/cram/cram_io.c index 80a04345f..618d9513a 100644 --- a/cram/cram_io.c +++ b/cram/cram_io.c @@ -3372,9 +3372,13 @@ char *cram_get_ref(cram_fd *fd, int id, hts_pos_t start, hts_pos_t end) { /* Open file if it's not already the current open reference */ if (strcmp(fd->refs->fn, r->fn) || fd->refs->fp == NULL) { - if (fd->refs->fp) - if (bgzf_close(fd->refs->fp) != 0) - return NULL; + if (fd->refs->fp) { + if (bgzf_close(fd->refs->fp) != 0) { + fd->refs->fp = NULL; + goto err_lock; + } + } + fd->refs->fn = r->fn; if (!(fd->refs->fp = bgzf_open_ref(fd->refs->fn, "r", r->is_md5))) goto err_lock; From fd2915d9c308be9b080607875f6b1a15f79458da Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Thu, 12 Nov 2026 14:47:23 +0000 Subject: [PATCH 10/22] Fix decode failure on large queries using bit-based codecs. 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 --- cram/cram_codecs.h | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/cram/cram_codecs.h b/cram/cram_codecs.h index 5ec096ba4..2ff334cc3 100644 --- a/cram/cram_codecs.h +++ b/cram/cram_codecs.h @@ -166,14 +166,12 @@ cram_codec *cram_encoder_init(enum cram_encoding codec, cram_stats *st, * Return 0 if there are enough * 1 if not. */ - static inline int cram_not_enough_bits(cram_block *blk, uint64_t nbits) { - if ((blk->byte >= blk->uncomp_size && nbits > 0) || - (blk->uncomp_size - blk->byte <= INT32_MAX / 8 + 1 && - (blk->uncomp_size - blk->byte) * 8 + blk->bit - 7 < nbits)) { - return 1; - } - return 0; + if (blk->byte >= (size_t)blk->uncomp_size) + return nbits > 0; + + uint64_t rem = (uint64_t)(blk->uncomp_size-blk->byte) * 8 + blk->bit - 7; + return rem < nbits; } /* From 33bfa0fa67a0cb863b27fa86c4bb6bb031395910 Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Thu, 12 Nov 2026 14:58:46 +0000 Subject: [PATCH 11/22] Some adjustments to accommodate 64-bit values in the encodings. 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 --- cram/cram_codecs.c | 4 ++-- cram/cram_stats.c | 12 +++++++----- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/cram/cram_codecs.c b/cram/cram_codecs.c index 3e377650e..755dcddc7 100644 --- a/cram/cram_codecs.c +++ b/cram/cram_codecs.c @@ -1476,7 +1476,7 @@ int cram_huffman_encode_long(cram_slice *slice, cram_codec *c, int64_t *syms = (int64_t *)in; while (in_size--) { - int sym = *syms++; + int64_t sym = *syms++; if (sym >= -1 && sym < MAX_HUFF) { i = c->u.e_huffman.val2code[sym+1]; @@ -2424,7 +2424,7 @@ int cram_codec_decoder2encoder(cram_fd *fd, cram_codec *c) { t->u.e_huffman.nvals = c->u.huffman.ncodes; t->u.e_huffman.option = c->u.huffman.option; for (j = 0; j < t->u.e_huffman.nvals; j++) { - int32_t sym = t->u.e_huffman.codes[j].symbol; + int64_t sym = t->u.e_huffman.codes[j].symbol; if (sym >= -1 && sym < MAX_HUFF) t->u.e_huffman.val2code[sym+1] = j; } diff --git a/cram/cram_stats.c b/cram/cram_stats.c index 0ee8b14a7..e2623beef 100644 --- a/cram/cram_stats.c +++ b/cram/cram_stats.c @@ -133,8 +133,10 @@ void cram_stats_dump(cram_stats *st) { * Returns the best codec to use. */ enum cram_encoding cram_stats_encoding(cram_fd *fd, cram_stats *st) { - int nvals, i, max_val = 0, min_val = INT_MAX; - int *vals = NULL, *freqs = NULL, vals_alloc = 0; + int nvals, i; + int64_t max_val = 0, min_val = INT64_MAX; + int64_t *vals = NULL; + int *freqs = NULL, vals_alloc = 0; int ntot HTS_UNUSED = 0; #if DEBUG_CRAM_STATS @@ -147,7 +149,7 @@ enum cram_encoding cram_stats_encoding(cram_fd *fd, cram_stats *st) { continue; 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); int *freqs_tmp = hts_realloc_p(freqs, sizeof(*freqs), vals_alloc); if (!vals_tmp || !freqs_tmp) { free(vals_tmp ? vals_tmp : vals); @@ -166,7 +168,7 @@ enum cram_encoding cram_stats_encoding(cram_fd *fd, cram_stats *st) { } if (st->h) { khint_t k; - int i; + int64_t i; for (k = kh_begin(st->h); k != kh_end(st->h); k++) { if (!kh_exist(st->h, k)) @@ -174,7 +176,7 @@ enum cram_encoding cram_stats_encoding(cram_fd *fd, cram_stats *st) { 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); int *freqs_tmp = hts_realloc_p(freqs, sizeof(*freqs), vals_alloc); if (!vals_tmp || !freqs_tmp) { free(vals_tmp ? vals_tmp : vals); From 0f48e8a60bfa3cc7ecc3e57852560d74cf26e308 Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Thu, 12 Nov 2026 15:54:17 +0000 Subject: [PATCH 12/22] Fix cram-store_container's record_counter encoding. 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 --- cram/cram_io.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cram/cram_io.c b/cram/cram_io.c index 618d9513a..82453a5ca 100644 --- a/cram/cram_io.c +++ b/cram/cram_io.c @@ -3755,7 +3755,7 @@ cram_container *cram_read_container(cram_fd *fd) { /* MAXIMUM storage size needed for the container. */ int cram_container_size(cram_container *c) { - return 55 + 5*c->num_landmarks; + return 56 + 5*c->num_landmarks; } @@ -3794,9 +3794,9 @@ int cram_store_container(cram_fd *fd, cram_container *c, char *dat, int *size) } cp += fd->vv.varint_put32(cp, NULL, c->num_records); if (CRAM_MAJOR_VERS(fd->version) == 2) { - cp += fd->vv.varint_put64(cp, NULL, c->record_counter); - } else if (CRAM_MAJOR_VERS(fd->version) >= 3) { cp += fd->vv.varint_put32(cp, NULL, c->record_counter); + } else if (CRAM_MAJOR_VERS(fd->version) >= 3) { + cp += fd->vv.varint_put64(cp, NULL, c->record_counter); } cp += fd->vv.varint_put64(cp, NULL, c->num_bases); cp += fd->vv.varint_put32(cp, NULL, c->num_blocks); From 8b8c852981cbe874fdea45a2fc719da6690f0cdc Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Thu, 12 Nov 2026 16:06:03 +0000 Subject: [PATCH 13/22] Correct parameter sizing in cram_container_num2offset_ 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 --- cram/cram_index.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cram/cram_index.c b/cram/cram_index.c index 719a77888..1c8cbed16 100644 --- a/cram/cram_index.c +++ b/cram/cram_index.c @@ -928,8 +928,8 @@ int64_t cram_num_containers(cram_fd *fd) { * * The index must have previously been loaded, otherwise <0 is returned. */ -static cram_index *cram_container_num2offset_(cram_index *e, int num, - int64_t *last_pos, int *nc) { +static cram_index *cram_container_num2offset_(cram_index *e, int64_t num, + int64_t *last_pos, int64_t *nc) { if (e->offset) { if (e->offset != *last_pos) { if (*nc == num) @@ -953,8 +953,8 @@ static cram_index *cram_container_num2offset_(cram_index *e, int num, } off_t cram_container_num2offset(cram_fd *fd, int64_t num) { - int nc = 0, i; - int64_t last_pos = -9; + int i; + int64_t nc = 0, last_pos = -9; cram_index *e = NULL; for (i = 0; i < fd->index_sz; i++) { From 7bb5efcd60980e1f7af8624ad92ab2d2e54e2523 Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Thu, 12 Nov 2026 16:09:10 +0000 Subject: [PATCH 14/22] Use 64-bit positions in cram_index_build_multiref. (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 --- cram/cram_index.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cram/cram_index.c b/cram/cram_index.c index 1c8cbed16..7b9991358 100644 --- a/cram/cram_index.c +++ b/cram/cram_index.c @@ -644,7 +644,7 @@ static int cram_index_build_multiref(cram_fd *fd, ref_end = INT_MIN; int32_t last_ref = -9; - int32_t last_pos = -9; + int64_t last_pos = -9; for (i = 0; i < s->hdr->num_records; i++) { if (s->crecs[i].ref_id == last_ref && s->crecs[i].apos < last_pos) { hts_log_error("CRAM file is not sorted by chromosome / position"); From 0c125aa6b5dc8b660ff31d0b8f4a1715e4c82f45 Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Thu, 12 Nov 2026 16:13:15 +0000 Subject: [PATCH 15/22] Fix bounds checks in expand_cache_path expansion. 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 --- cram/cram_io.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/cram/cram_io.c b/cram/cram_io.c index 82453a5ca..a4989cf41 100644 --- a/cram/cram_io.c +++ b/cram/cram_io.c @@ -2676,9 +2676,6 @@ static int expand_cache_path(char *path, char *dir, const char *fn) { size_t len; size_t sz = PATH_MAX; - if (strchr(fn, '/')) - return -1; - while ((cp = strchr(dir, '%'))) { if (cp-dir >= sz) return -1; strncpy(path, dir, cp-dir); @@ -2711,11 +2708,13 @@ static int expand_cache_path(char *path, char *dir, const char *fn) { if (sz < 3) return -1; *path++ = '%'; *path++ = *cp++; + sz -= 2; } } else { if (sz < 3) return -1; *path++ = '%'; *path++ = *cp++; + sz -= 2; } dir = cp; } @@ -2796,6 +2795,10 @@ static int cram_populate_ref(cram_fd *fd, int id, ref_entry *r) { /* Use cache if available */ if (local_cache && *local_cache) { + if (strchr(tag->str+3, '/')) { + hts_log_error("Invalid LOCAL_CACHE environment variable"); + return -1; + } struct stat sb; if (expand_cache_path(path, local_cache, tag->str+3) == 0 && stat(path, &sb) == 0) From 2747b45fdb2c8e2ab17c2d3324ee26392a30db02 Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Thu, 12 Nov 2026 16:28:49 +0000 Subject: [PATCH 16/22] Improve cram_read_file_def version validation. A rogue CRAM 4.0 signature was still permitted, even though we only decode using 3.x semantics. Signed-off-by: James Bonfield --- cram/cram_io.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cram/cram_io.c b/cram/cram_io.c index a4989cf41..312aa9f45 100644 --- a/cram/cram_io.c +++ b/cram/cram_io.c @@ -4509,8 +4509,8 @@ cram_file_def *cram_read_file_def(cram_fd *fd) { return NULL; } - if (def->major_version > 4) { - hts_log_error("CRAM version number mismatch. Expected 1.x, 2.x, 3.x or 4.x, got %d.%d", + if (def->major_version < 1 || def->major_version > 3) { + hts_log_error("CRAM version number mismatch. Expected 1.x, 2.x, or 3.x, got %d.%d", def->major_version, def->minor_version); free(def); return NULL; From 917aed919f1257c092cf1d7eafa70d95506bec66 Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Thu, 12 Nov 2026 16:29:24 +0000 Subject: [PATCH 17/22] Improved fread error handling in mfload. A non-EOF error could potentially cause infinite loops. Signed-off-by: James Bonfield --- cram/mFILE.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/cram/mFILE.c b/cram/mFILE.c index c1596a173..09dd41308 100644 --- a/cram/mFILE.c +++ b/cram/mFILE.c @@ -94,8 +94,8 @@ static char *mfload(FILE *fp, const char *fn, size_t *size, int binary) { fn = NULL; } + size_t len = 0; do { - size_t len; if (used + bufsize > allocated) { allocated += bufsize; char *datan = realloc(data, allocated); @@ -109,8 +109,16 @@ static char *mfload(FILE *fp, const char *fn, size_t *size, int binary) { len = fread(data + used, 1, allocated - used, fp); if (len > 0) used += len; + if (len == 0) + break; } while (!feof(fp) && (fn == NULL || used < sb.st_size)); + if (len == 0 && !feof(fp)) { + // error + free(data); + return NULL; + } + *size = used; return data; From e7e6b6882c20c9a896c81ec4e46e737ece441d7e Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Thu, 12 Nov 2026 16:44:19 +0000 Subject: [PATCH 18/22] Miscellaneous minor cram memory leak fixes. These are all on error handling cases. We haven't found any leaks with normal correctly behaving data. Signed-off-by: James Bonfield --- cram/cram_codecs.c | 2 +- cram/cram_index.c | 2 +- cram/cram_io.c | 13 ++++++++++--- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/cram/cram_codecs.c b/cram/cram_codecs.c index 755dcddc7..50108f73a 100644 --- a/cram/cram_codecs.c +++ b/cram/cram_codecs.c @@ -1379,7 +1379,7 @@ cram_codec *cram_huffman_decode_init(cram_block_compression_hdr *hdr, else h->decode = cram_huffman_decode_int; } else { - return NULL; + goto malformed; } h->describe = cram_huffman_describe; diff --git a/cram/cram_index.c b/cram/cram_index.c index 7b9991358..3355c7097 100644 --- a/cram/cram_index.c +++ b/cram/cram_index.c @@ -801,7 +801,7 @@ int cram_index_build(cram_fd *fd, const char *fn_base, const char *fn_idx) { while ((c = cram_read_container(fd))) { if (fd->err) { perror("Cram container read"); - return -1; + goto err; } hpos = htell(fd->fp); diff --git a/cram/cram_io.c b/cram/cram_io.c index 312aa9f45..7606baf0b 100644 --- a/cram/cram_io.c +++ b/cram/cram_io.c @@ -1013,6 +1013,7 @@ static char *zlib_mem_deflate(char *data, size_t size, size_t *cdata_size, err = deflateInit2(&s, level, Z_DEFLATED, 15|16, 9, strat); if (err != Z_OK) { hts_log_error("Call to zlib deflateInit2 failed: %s", s.msg); + free(cdata); return NULL; } @@ -1022,6 +1023,8 @@ static char *zlib_mem_deflate(char *data, size_t size, size_t *cdata_size, s.avail_out = cdata_alloc - cdata_pos; if (cdata_alloc - cdata_pos <= 0) { hts_log_error("Deflate produced larger output than expected"); + deflateEnd(&s); + free(cdata); return NULL; } err = deflate(&s, Z_NO_FLUSH); @@ -1070,8 +1073,10 @@ static char *lzma_mem_deflate(char *data, size_t size, size_t *cdata_size, if (LZMA_OK != lzma_easy_buffer_encode(level, LZMA_CHECK_CRC32, NULL, (uint8_t *)data, size, (uint8_t *)out, cdata_size, - out_size)) + out_size)) { + free(out); return NULL; + } return out; } @@ -3989,8 +3994,10 @@ static int cram_flush_result(cram_fd *fd) { c = j->c; if (fd->mode == 'w') - if (0 != cram_flush_container2(fd, c)) + if (0 != cram_flush_container2(fd, c)) { + hts_tpool_delete_result(r, 1); return -1; + } // Free the slices; filled out by encoder only if (c->slices) { @@ -5149,7 +5156,7 @@ cram_fd *cram_dopen(hFILE *fp, const char *filename, const char *mode) { /* Writer */ cram_file_def *def = calloc(1, sizeof(*def)); if (!def) - return NULL; + goto err; fd->file_def = def; From d40dfd3b47e7125a99c4c75c7b5f8f5f1a03f2f4 Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Mon, 23 Nov 2026 16:48:24 +0000 Subject: [PATCH 19/22] Avoid variable shadowing in cram_stats_encoding Signed-off-by: James Bonfield --- cram/cram_stats.c | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/cram/cram_stats.c b/cram/cram_stats.c index e2623beef..87c6ff23e 100644 --- a/cram/cram_stats.c +++ b/cram/cram_stats.c @@ -133,8 +133,8 @@ void cram_stats_dump(cram_stats *st) { * Returns the best codec to use. */ enum cram_encoding cram_stats_encoding(cram_fd *fd, cram_stats *st) { - int nvals, i; - int64_t max_val = 0, min_val = INT64_MAX; + int nvals; + int64_t max_val = 0, min_val = INT64_MAX, v; int64_t *vals = NULL; int *freqs = NULL, vals_alloc = 0; int ntot HTS_UNUSED = 0; @@ -144,8 +144,8 @@ enum cram_encoding cram_stats_encoding(cram_fd *fd, cram_stats *st) { #endif /* Count number of unique symbols */ - for (nvals = i = 0; i < MAX_STAT_VAL; i++) { - if (!st->freqs[i]) + for (nvals = 0, v = 0; v < MAX_STAT_VAL; v++) { + if (!st->freqs[v]) continue; if (nvals >= vals_alloc) { vals_alloc = vals_alloc ? vals_alloc*2 : 1024; @@ -159,16 +159,15 @@ enum cram_encoding cram_stats_encoding(cram_fd *fd, cram_stats *st) { vals = vals_tmp; freqs = freqs_tmp; } - vals[nvals] = i; - freqs[nvals] = st->freqs[i]; + vals[nvals] = v; + freqs[nvals] = st->freqs[v]; ntot += freqs[nvals]; - if (max_val < i) max_val = i; - if (min_val > i) min_val = i; + if (max_val < v) max_val = v; + if (min_val > v) min_val = v; nvals++; } if (st->h) { khint_t k; - int64_t i; for (k = kh_begin(st->h); k != kh_end(st->h); k++) { if (!kh_exist(st->h, k)) @@ -186,12 +185,12 @@ enum cram_encoding cram_stats_encoding(cram_fd *fd, cram_stats *st) { vals = vals_tmp; freqs = freqs_tmp; } - i = kh_key(st->h, k); - vals[nvals]=i; + v = kh_key(st->h, k); + vals[nvals]=v; freqs[nvals] = kh_val(st->h, k); ntot += freqs[nvals]; - if (max_val < i) max_val = i; - if (min_val > i) min_val = i; + if (max_val < v) max_val = v; + if (min_val > v) min_val = v; nvals++; } } From f923e2dda0f70ae0a2bf30aa4bd1482b4dc653a2 Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Mon, 23 Nov 2026 16:55:38 +0000 Subject: [PATCH 20/22] Optimise reallocation in cram_stats_encoding 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 --- cram/cram_stats.c | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/cram/cram_stats.c b/cram/cram_stats.c index 87c6ff23e..8c7e1dde9 100644 --- a/cram/cram_stats.c +++ b/cram/cram_stats.c @@ -169,22 +169,23 @@ enum cram_encoding cram_stats_encoding(cram_fd *fd, cram_stats *st) { if (st->h) { khint_t k; + if (nvals + kh_size(st->h) >= vals_alloc) { + vals_alloc = vals_alloc ? vals_alloc*2 : 1024; + int64_t *vals_tmp = hts_realloc_p(vals, sizeof(*vals), vals_alloc); + int *freqs_tmp = hts_realloc_p(freqs, sizeof(*freqs), vals_alloc); + if (!vals_tmp || !freqs_tmp) { + free(vals_tmp ? vals_tmp : vals); + free(freqs_tmp ? freqs_tmp : freqs); + return E_HUFFMAN; // Cannot do much else atm + } + vals = vals_tmp; + freqs = freqs_tmp; + } + for (k = kh_begin(st->h); k != kh_end(st->h); k++) { if (!kh_exist(st->h, k)) continue; - if (nvals >= vals_alloc) { - vals_alloc = vals_alloc ? vals_alloc*2 : 1024; - int64_t *vals_tmp = hts_realloc_p(vals, sizeof(*vals), vals_alloc); - int *freqs_tmp = hts_realloc_p(freqs, sizeof(*freqs), vals_alloc); - if (!vals_tmp || !freqs_tmp) { - free(vals_tmp ? vals_tmp : vals); - free(freqs_tmp ? freqs_tmp : freqs); - return E_HUFFMAN; // Cannot do much else atm - } - vals = vals_tmp; - freqs = freqs_tmp; - } v = kh_key(st->h, k); vals[nvals]=v; freqs[nvals] = kh_val(st->h, k); From 58bcfb3bb3158db6c9f4195592aa222e53278444 Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Thu, 26 Nov 2026 12:18:56 +0000 Subject: [PATCH 21/22] Switch mfload to using fstat over stat. This mades the fn field redudant. Signed-off-by: James Bonfield --- cram/mFILE.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/cram/mFILE.c b/cram/mFILE.c index 09dd41308..1aba8fc9a 100644 --- a/cram/mFILE.c +++ b/cram/mFILE.c @@ -78,16 +78,24 @@ static char *mfload(FILE *fp, const char *fn, size_t *size, int binary) { size_t allocated = 0, used = 0; int bufsize = 8192; +#ifdef _WIN32 + int fd = _fileno(fp); +#else + int fd = fileno(fp); +#endif + if (fd < 0) + return NULL; + #ifdef _WIN32 if (binary) - _setmode(_fileno(fp), _O_BINARY); + _setmode(fd, _O_BINARY); else - _setmode(_fileno(fp), _O_TEXT); + _setmode(fd, _O_TEXT); #endif - if (fn && -1 != stat(fn, &sb)) { + if (-1 != fstat(fd, &sb)) { data = malloc(allocated = sb.st_size); - if (!data) + if (sb.st_size && !data) return NULL; bufsize = sb.st_size; } else { From 2b42336f53cc3e0314eb854055cbda04d939e48b Mon Sep 17 00:00:00 2001 From: James Bonfield Date: Mon, 30 Nov 2026 17:04:04 +0000 Subject: [PATCH 22/22] Simplify cram_stats_encoding. 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 --- cram/cram_stats.c | 40 +++------------------------------------- 1 file changed, 3 insertions(+), 37 deletions(-) diff --git a/cram/cram_stats.c b/cram/cram_stats.c index 8c7e1dde9..1ee4df674 100644 --- a/cram/cram_stats.c +++ b/cram/cram_stats.c @@ -135,8 +135,6 @@ void cram_stats_dump(cram_stats *st) { enum cram_encoding cram_stats_encoding(cram_fd *fd, cram_stats *st) { int nvals; int64_t max_val = 0, min_val = INT64_MAX, v; - int64_t *vals = NULL; - int *freqs = NULL, vals_alloc = 0; int ntot HTS_UNUSED = 0; #if DEBUG_CRAM_STATS @@ -147,49 +145,20 @@ enum cram_encoding cram_stats_encoding(cram_fd *fd, cram_stats *st) { for (nvals = 0, v = 0; v < MAX_STAT_VAL; v++) { if (!st->freqs[v]) continue; - if (nvals >= vals_alloc) { - vals_alloc = vals_alloc ? vals_alloc*2 : 1024; - int64_t *vals_tmp = hts_realloc_p(vals, sizeof(*vals), vals_alloc); - int *freqs_tmp = hts_realloc_p(freqs, sizeof(*freqs), vals_alloc); - if (!vals_tmp || !freqs_tmp) { - free(vals_tmp ? vals_tmp : vals); - free(freqs_tmp ? freqs_tmp : freqs); - return E_HUFFMAN; // Cannot do much else atm - } - vals = vals_tmp; - freqs = freqs_tmp; - } - vals[nvals] = v; - freqs[nvals] = st->freqs[v]; - ntot += freqs[nvals]; + ntot += st->freqs[v]; if (max_val < v) max_val = v; if (min_val > v) min_val = v; nvals++; } + if (st->h) { khint_t k; - - if (nvals + kh_size(st->h) >= vals_alloc) { - vals_alloc = vals_alloc ? vals_alloc*2 : 1024; - int64_t *vals_tmp = hts_realloc_p(vals, sizeof(*vals), vals_alloc); - int *freqs_tmp = hts_realloc_p(freqs, sizeof(*freqs), vals_alloc); - if (!vals_tmp || !freqs_tmp) { - free(vals_tmp ? vals_tmp : vals); - free(freqs_tmp ? freqs_tmp : freqs); - return E_HUFFMAN; // Cannot do much else atm - } - vals = vals_tmp; - freqs = freqs_tmp; - } - for (k = kh_begin(st->h); k != kh_end(st->h); k++) { if (!kh_exist(st->h, k)) continue; v = kh_key(st->h, k); - vals[nvals]=v; - freqs[nvals] = kh_val(st->h, k); - ntot += freqs[nvals]; + ntot += kh_val(st->h, k); if (max_val < v) max_val = v; if (min_val > v) min_val = v; nvals++; @@ -201,9 +170,6 @@ enum cram_encoding cram_stats_encoding(cram_fd *fd, cram_stats *st) { st->max_val = max_val; assert(ntot == st->nsamp); - free(vals); - free(freqs); - /* * Simple policy that everything is external unless it can be * encoded using zero bits as a unary item huffman table.