forked from samtools/htslib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sam.c
6357 lines (5617 loc) · 199 KB
/
sam.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* sam.c -- SAM and BAM file I/O and manipulation.
Copyright (C) 2008-2010, 2012-2023 Genome Research Ltd.
Copyright (C) 2010, 2012, 2013 Broad Institute.
Author: Heng Li <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. */
#define HTS_BUILDING_LIBRARY // Enables HTSLIB_EXPORT, see htslib/hts_defs.h
#include <config.h>
#include <strings.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <zlib.h>
#include <assert.h>
#include <signal.h>
#include <inttypes.h>
#include <unistd.h>
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
#include "fuzz_settings.h"
#endif
// Suppress deprecation message for cigar_tab, which we initialise
#include "htslib/hts_defs.h"
#undef HTS_DEPRECATED
#define HTS_DEPRECATED(message)
#include "htslib/sam.h"
#include "htslib/bgzf.h"
#include "cram/cram.h"
#include "hts_internal.h"
#include "sam_internal.h"
#include "htslib/hfile.h"
#include "htslib/hts_endian.h"
#include "htslib/hts_expr.h"
#include "header.h"
#include "htslib/khash.h"
KHASH_DECLARE(s2i, kh_cstr_t, int64_t)
KHASH_SET_INIT_INT(tag)
#ifndef EFTYPE
#define EFTYPE ENOEXEC
#endif
#ifndef EOVERFLOW
#define EOVERFLOW ERANGE
#endif
/**********************
*** BAM header I/O ***
**********************/
HTSLIB_EXPORT
const int8_t bam_cigar_table[256] = {
// 0 .. 47
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
// 48 .. 63 (including =)
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, BAM_CEQUAL, -1, -1,
// 64 .. 79 (including MIDNHB)
-1, -1, BAM_CBACK, -1, BAM_CDEL, -1, -1, -1,
BAM_CHARD_CLIP, BAM_CINS, -1, -1, -1, BAM_CMATCH, BAM_CREF_SKIP, -1,
// 80 .. 95 (including SPX)
BAM_CPAD, -1, -1, BAM_CSOFT_CLIP, -1, -1, -1, -1,
BAM_CDIFF, -1, -1, -1, -1, -1, -1, -1,
// 96 .. 127
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
// 128 .. 255
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
sam_hdr_t *sam_hdr_init()
{
sam_hdr_t *bh = (sam_hdr_t*)calloc(1, sizeof(sam_hdr_t));
if (bh == NULL) return NULL;
bh->cigar_tab = bam_cigar_table;
return bh;
}
void sam_hdr_destroy(sam_hdr_t *bh)
{
int32_t i;
if (bh == NULL) return;
if (bh->ref_count > 0) {
--bh->ref_count;
return;
}
if (bh->target_name) {
for (i = 0; i < bh->n_targets; ++i)
free(bh->target_name[i]);
free(bh->target_name);
free(bh->target_len);
}
free(bh->text);
if (bh->hrecs)
sam_hrecs_free(bh->hrecs);
if (bh->sdict)
kh_destroy(s2i, (khash_t(s2i) *) bh->sdict);
free(bh);
}
// Copy the sam_hdr_t::sdict hash, used to store the real lengths of long
// references before sam_hdr_t::hrecs is populated
int sam_hdr_dup_sdict(const sam_hdr_t *h0, sam_hdr_t *h)
{
const khash_t(s2i) *src_long_refs = (khash_t(s2i) *) h0->sdict;
khash_t(s2i) *dest_long_refs = kh_init(s2i);
int i;
if (!dest_long_refs) return -1;
for (i = 0; i < h->n_targets; i++) {
int ret;
khiter_t ksrc, kdest;
if (h->target_len[i] < UINT32_MAX) continue;
ksrc = kh_get(s2i, src_long_refs, h->target_name[i]);
if (ksrc == kh_end(src_long_refs)) continue;
kdest = kh_put(s2i, dest_long_refs, h->target_name[i], &ret);
if (ret < 0) {
kh_destroy(s2i, dest_long_refs);
return -1;
}
kh_val(dest_long_refs, kdest) = kh_val(src_long_refs, ksrc);
}
h->sdict = dest_long_refs;
return 0;
}
sam_hdr_t *sam_hdr_dup(const sam_hdr_t *h0)
{
if (h0 == NULL) return NULL;
sam_hdr_t *h;
if ((h = sam_hdr_init()) == NULL) return NULL;
// copy the simple data
h->n_targets = 0;
h->ignore_sam_err = h0->ignore_sam_err;
h->l_text = 0;
// Then the pointery stuff
if (!h0->hrecs) {
h->target_len = (uint32_t*)calloc(h0->n_targets, sizeof(uint32_t));
if (!h->target_len) goto fail;
h->target_name = (char**)calloc(h0->n_targets, sizeof(char*));
if (!h->target_name) goto fail;
int i;
for (i = 0; i < h0->n_targets; ++i) {
h->target_len[i] = h0->target_len[i];
h->target_name[i] = strdup(h0->target_name[i]);
if (!h->target_name[i]) break;
}
h->n_targets = i;
if (i < h0->n_targets) goto fail;
if (h0->sdict) {
if (sam_hdr_dup_sdict(h0, h) < 0) goto fail;
}
}
if (h0->hrecs) {
kstring_t tmp = { 0, 0, NULL };
if (sam_hrecs_rebuild_text(h0->hrecs, &tmp) != 0) {
free(ks_release(&tmp));
goto fail;
}
h->l_text = tmp.l;
h->text = ks_release(&tmp);
if (sam_hdr_update_target_arrays(h, h0->hrecs, 0) != 0)
goto fail;
} else {
h->l_text = h0->l_text;
h->text = malloc(h->l_text + 1);
if (!h->text) goto fail;
memcpy(h->text, h0->text, h->l_text);
h->text[h->l_text] = '\0';
}
return h;
fail:
sam_hdr_destroy(h);
return NULL;
}
sam_hdr_t *bam_hdr_read(BGZF *fp)
{
sam_hdr_t *h;
uint8_t buf[4];
int magic_len, has_EOF;
int32_t i, name_len, num_names = 0;
size_t bufsize;
ssize_t bytes;
// check EOF
has_EOF = bgzf_check_EOF(fp);
if (has_EOF < 0) {
perror("[W::bam_hdr_read] bgzf_check_EOF");
} else if (has_EOF == 0) {
hts_log_warning("EOF marker is absent. The input is probably truncated");
}
// read "BAM1"
magic_len = bgzf_read(fp, buf, 4);
if (magic_len != 4 || memcmp(buf, "BAM\1", 4)) {
hts_log_error("Invalid BAM binary header");
return 0;
}
h = sam_hdr_init();
if (!h) goto nomem;
// read plain text and the number of reference sequences
bytes = bgzf_read(fp, buf, 4);
if (bytes != 4) goto read_err;
h->l_text = le_to_u32(buf);
bufsize = h->l_text + 1;
if (bufsize < h->l_text) goto nomem; // so large that adding 1 overflowed
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
if (bufsize > FUZZ_ALLOC_LIMIT) goto nomem;
#endif
h->text = (char*)malloc(bufsize);
if (!h->text) goto nomem;
h->text[h->l_text] = 0; // make sure it is NULL terminated
bytes = bgzf_read(fp, h->text, h->l_text);
if (bytes != h->l_text) goto read_err;
bytes = bgzf_read(fp, &h->n_targets, 4);
if (bytes != 4) goto read_err;
if (fp->is_be) ed_swap_4p(&h->n_targets);
if (h->n_targets < 0) goto invalid;
// read reference sequence names and lengths
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
if (h->n_targets > (FUZZ_ALLOC_LIMIT - bufsize)/(sizeof(char*)+sizeof(uint32_t)))
goto nomem;
#endif
if (h->n_targets > 0) {
h->target_name = (char**)calloc(h->n_targets, sizeof(char*));
if (!h->target_name) goto nomem;
h->target_len = (uint32_t*)calloc(h->n_targets, sizeof(uint32_t));
if (!h->target_len) goto nomem;
}
else {
h->target_name = NULL;
h->target_len = NULL;
}
for (i = 0; i != h->n_targets; ++i) {
bytes = bgzf_read(fp, &name_len, 4);
if (bytes != 4) goto read_err;
if (fp->is_be) ed_swap_4p(&name_len);
if (name_len <= 0) goto invalid;
h->target_name[i] = (char*)malloc(name_len);
if (!h->target_name[i]) goto nomem;
num_names++;
bytes = bgzf_read(fp, h->target_name[i], name_len);
if (bytes != name_len) goto read_err;
if (h->target_name[i][name_len - 1] != '\0') {
/* Fix missing NUL-termination. Is this being too nice?
We could alternatively bail out with an error. */
char *new_name;
if (name_len == INT32_MAX) goto invalid;
new_name = realloc(h->target_name[i], name_len + 1);
if (new_name == NULL) goto nomem;
h->target_name[i] = new_name;
h->target_name[i][name_len] = '\0';
}
bytes = bgzf_read(fp, &h->target_len[i], 4);
if (bytes != 4) goto read_err;
if (fp->is_be) ed_swap_4p(&h->target_len[i]);
}
return h;
nomem:
hts_log_error("Out of memory");
goto clean;
read_err:
if (bytes < 0) {
hts_log_error("Error reading BGZF stream");
} else {
hts_log_error("Truncated BAM header");
}
goto clean;
invalid:
hts_log_error("Invalid BAM binary header");
clean:
if (h != NULL) {
h->n_targets = num_names; // ensure we free only allocated target_names
sam_hdr_destroy(h);
}
return NULL;
}
int bam_hdr_write(BGZF *fp, const sam_hdr_t *h)
{
int32_t i, name_len, x;
kstring_t hdr_ks = { 0, 0, NULL };
char *text;
uint32_t l_text;
if (!h) return -1;
if (h->hrecs) {
if (sam_hrecs_rebuild_text(h->hrecs, &hdr_ks) != 0) return -1;
if (hdr_ks.l > UINT32_MAX) {
hts_log_error("Header too long for BAM format");
free(hdr_ks.s);
return -1;
} else if (hdr_ks.l > INT32_MAX) {
hts_log_warning("Header too long for BAM specification (>2GB)");
hts_log_warning("Output file may not be portable");
}
text = hdr_ks.s;
l_text = hdr_ks.l;
} else {
if (h->l_text > UINT32_MAX) {
hts_log_error("Header too long for BAM format");
return -1;
} else if (h->l_text > INT32_MAX) {
hts_log_warning("Header too long for BAM specification (>2GB)");
hts_log_warning("Output file may not be portable");
}
text = h->text;
l_text = h->l_text;
}
// write "BAM1"
if (bgzf_write(fp, "BAM\1", 4) < 0) { free(hdr_ks.s); return -1; }
// write plain text and the number of reference sequences
if (fp->is_be) {
x = ed_swap_4(l_text);
if (bgzf_write(fp, &x, 4) < 0) { free(hdr_ks.s); return -1; }
if (l_text) {
if (bgzf_write(fp, text, l_text) < 0) { free(hdr_ks.s); return -1; }
}
x = ed_swap_4(h->n_targets);
if (bgzf_write(fp, &x, 4) < 0) { free(hdr_ks.s); return -1; }
} else {
if (bgzf_write(fp, &l_text, 4) < 0) { free(hdr_ks.s); return -1; }
if (l_text) {
if (bgzf_write(fp, text, l_text) < 0) { free(hdr_ks.s); return -1; }
}
if (bgzf_write(fp, &h->n_targets, 4) < 0) { free(hdr_ks.s); return -1; }
}
free(hdr_ks.s);
// write sequence names and lengths
for (i = 0; i != h->n_targets; ++i) {
char *p = h->target_name[i];
name_len = strlen(p) + 1;
if (fp->is_be) {
x = ed_swap_4(name_len);
if (bgzf_write(fp, &x, 4) < 0) return -1;
} else {
if (bgzf_write(fp, &name_len, 4) < 0) return -1;
}
if (bgzf_write(fp, p, name_len) < 0) return -1;
if (fp->is_be) {
x = ed_swap_4(h->target_len[i]);
if (bgzf_write(fp, &x, 4) < 0) return -1;
} else {
if (bgzf_write(fp, &h->target_len[i], 4) < 0) return -1;
}
}
if (bgzf_flush(fp) < 0) return -1;
return 0;
}
const char *sam_parse_region(sam_hdr_t *h, const char *s, int *tid,
hts_pos_t *beg, hts_pos_t *end, int flags) {
return hts_parse_region(s, tid, beg, end, (hts_name2id_f)bam_name2id, h, flags);
}
/*************************
*** BAM alignment I/O ***
*************************/
bam1_t *bam_init1()
{
return (bam1_t*)calloc(1, sizeof(bam1_t));
}
int sam_realloc_bam_data(bam1_t *b, size_t desired)
{
uint32_t new_m_data;
uint8_t *new_data;
new_m_data = desired;
kroundup32(new_m_data);
if (new_m_data < desired) {
errno = ENOMEM; // Not strictly true but we can't store the size
return -1;
}
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
if (new_m_data > FUZZ_ALLOC_LIMIT) {
errno = ENOMEM;
return -1;
}
#endif
if ((bam_get_mempolicy(b) & BAM_USER_OWNS_DATA) == 0) {
new_data = realloc(b->data, new_m_data);
} else {
if ((new_data = malloc(new_m_data)) != NULL) {
if (b->l_data > 0)
memcpy(new_data, b->data,
b->l_data < b->m_data ? b->l_data : b->m_data);
bam_set_mempolicy(b, bam_get_mempolicy(b) & (~BAM_USER_OWNS_DATA));
}
}
if (!new_data) return -1;
b->data = new_data;
b->m_data = new_m_data;
return 0;
}
void bam_destroy1(bam1_t *b)
{
if (b == 0) return;
if ((bam_get_mempolicy(b) & BAM_USER_OWNS_DATA) == 0) {
free(b->data);
if ((bam_get_mempolicy(b) & BAM_USER_OWNS_STRUCT) != 0) {
// In case of reuse
b->data = NULL;
b->m_data = 0;
b->l_data = 0;
}
}
if ((bam_get_mempolicy(b) & BAM_USER_OWNS_STRUCT) == 0)
free(b);
}
bam1_t *bam_copy1(bam1_t *bdst, const bam1_t *bsrc)
{
if (realloc_bam_data(bdst, bsrc->l_data) < 0) return NULL;
memcpy(bdst->data, bsrc->data, bsrc->l_data); // copy var-len data
memcpy(&bdst->core, &bsrc->core, sizeof(bsrc->core)); // copy the rest
bdst->l_data = bsrc->l_data;
bdst->id = bsrc->id;
return bdst;
}
bam1_t *bam_dup1(const bam1_t *bsrc)
{
if (bsrc == NULL) return NULL;
bam1_t *bdst = bam_init1();
if (bdst == NULL) return NULL;
if (bam_copy1(bdst, bsrc) == NULL) {
bam_destroy1(bdst);
return NULL;
}
return bdst;
}
static void bam_cigar2rqlens(int n_cigar, const uint32_t *cigar,
hts_pos_t *rlen, hts_pos_t *qlen)
{
int k;
*rlen = *qlen = 0;
for (k = 0; k < n_cigar; ++k) {
int type = bam_cigar_type(bam_cigar_op(cigar[k]));
int len = bam_cigar_oplen(cigar[k]);
if (type & 1) *qlen += len;
if (type & 2) *rlen += len;
}
}
static int subtract_check_underflow(size_t length, size_t *limit)
{
if (length <= *limit) {
*limit -= length;
return 0;
}
return -1;
}
int bam_set1(bam1_t *bam,
size_t l_qname, const char *qname,
uint16_t flag, int32_t tid, hts_pos_t pos, uint8_t mapq,
size_t n_cigar, const uint32_t *cigar,
int32_t mtid, hts_pos_t mpos, hts_pos_t isize,
size_t l_seq, const char *seq, const char *qual,
size_t l_aux)
{
// use a default qname "*" if none is provided
if (l_qname == 0) {
l_qname = 1;
qname = "*";
}
// note: the qname is stored nul terminated and padded as described in the
// documentation for the bam1_t struct.
size_t qname_nuls = 4 - l_qname % 4;
// the aligment length, needed for bam_reg2bin(), is calculated as in bam_endpos().
// can't use bam_endpos() directly as some fields not yet set up.
hts_pos_t rlen = 0, qlen = 0;
if (!(flag & BAM_FUNMAP)) {
bam_cigar2rqlens((int)n_cigar, cigar, &rlen, &qlen);
}
if (rlen == 0) {
rlen = 1;
}
// validate parameters
if (l_qname > 254) {
hts_log_error("Query name too long");
errno = EINVAL;
return -1;
}
if (HTS_POS_MAX - rlen <= pos) {
hts_log_error("Read ends beyond highest supported position");
errno = EINVAL;
return -1;
}
if (!(flag & BAM_FUNMAP) && l_seq > 0 && n_cigar == 0) {
hts_log_error("Mapped query must have a CIGAR");
errno = EINVAL;
return -1;
}
if (!(flag & BAM_FUNMAP) && l_seq > 0 && l_seq != qlen) {
hts_log_error("CIGAR and query sequence are of different length");
errno = EINVAL;
return -1;
}
size_t limit = INT32_MAX;
int u = subtract_check_underflow(l_qname + qname_nuls, &limit);
u += subtract_check_underflow(n_cigar * 4, &limit);
u += subtract_check_underflow((l_seq + 1) / 2, &limit);
u += subtract_check_underflow(l_seq, &limit);
u += subtract_check_underflow(l_aux, &limit);
if (u != 0) {
hts_log_error("Size overflow");
errno = EINVAL;
return -1;
}
// re-allocate the data buffer as needed.
size_t data_len = l_qname + qname_nuls + n_cigar * 4 + (l_seq + 1) / 2 + l_seq;
if (realloc_bam_data(bam, data_len + l_aux) < 0) {
return -1;
}
bam->l_data = (int)data_len;
bam->core.pos = pos;
bam->core.tid = tid;
bam->core.bin = bam_reg2bin(pos, pos + rlen);
bam->core.qual = mapq;
bam->core.l_extranul = (uint8_t)(qname_nuls - 1);
bam->core.flag = flag;
bam->core.l_qname = (uint16_t)(l_qname + qname_nuls);
bam->core.n_cigar = (uint32_t)n_cigar;
bam->core.l_qseq = (int32_t)l_seq;
bam->core.mtid = mtid;
bam->core.mpos = mpos;
bam->core.isize = isize;
uint8_t *cp = bam->data;
strncpy((char *)cp, qname, l_qname);
int i;
for (i = 0; i < qname_nuls; i++) {
cp[l_qname + i] = '\0';
}
cp += l_qname + qname_nuls;
if (n_cigar > 0) {
memcpy(cp, cigar, n_cigar * 4);
}
cp += n_cigar * 4;
#define NN 16
const uint8_t *useq = (uint8_t *)seq;
for (i = 0; i + NN < l_seq; i += NN) {
int j;
const uint8_t *u2 = useq+i;
for (j = 0; j < NN/2; j++)
cp[j] = (seq_nt16_table[u2[j*2]]<<4) | seq_nt16_table[u2[j*2+1]];
cp += NN/2;
}
for (; i + 1 < l_seq; i += 2) {
*cp++ = (seq_nt16_table[useq[i]] << 4) | seq_nt16_table[useq[i + 1]];
}
for (; i < l_seq; i++) {
*cp++ = seq_nt16_table[(unsigned char)seq[i]] << 4;
}
if (qual) {
memcpy(cp, qual, l_seq);
}
else {
memset(cp, '\xff', l_seq);
}
return (int)data_len;
}
hts_pos_t bam_cigar2qlen(int n_cigar, const uint32_t *cigar)
{
int k;
hts_pos_t l;
for (k = l = 0; k < n_cigar; ++k)
if (bam_cigar_type(bam_cigar_op(cigar[k]))&1)
l += bam_cigar_oplen(cigar[k]);
return l;
}
hts_pos_t bam_cigar2rlen(int n_cigar, const uint32_t *cigar)
{
int k;
hts_pos_t l;
for (k = l = 0; k < n_cigar; ++k)
if (bam_cigar_type(bam_cigar_op(cigar[k]))&2)
l += bam_cigar_oplen(cigar[k]);
return l;
}
hts_pos_t bam_endpos(const bam1_t *b)
{
hts_pos_t rlen = (b->core.flag & BAM_FUNMAP)? 0 : bam_cigar2rlen(b->core.n_cigar, bam_get_cigar(b));
if (rlen == 0) rlen = 1;
return b->core.pos + rlen;
}
static int bam_tag2cigar(bam1_t *b, int recal_bin, int give_warning) // return 0 if CIGAR is untouched; 1 if CIGAR is updated with CG
{
bam1_core_t *c = &b->core;
uint32_t cigar_st, n_cigar4, CG_st, CG_en, ori_len = b->l_data, *cigar0, CG_len, fake_bytes;
uint8_t *CG;
// test where there is a real CIGAR in the CG tag to move
if (c->n_cigar == 0 || c->tid < 0 || c->pos < 0) return 0;
cigar0 = bam_get_cigar(b);
if (bam_cigar_op(cigar0[0]) != BAM_CSOFT_CLIP || bam_cigar_oplen(cigar0[0]) != c->l_qseq) return 0;
fake_bytes = c->n_cigar * 4;
int saved_errno = errno;
CG = bam_aux_get(b, "CG");
if (!CG) {
if (errno != ENOENT) return -1; // Bad aux data
errno = saved_errno; // restore errno on expected no-CG-tag case
return 0;
}
if (CG[0] != 'B' || !(CG[1] == 'I' || CG[1] == 'i'))
return 0; // not of type B,I
CG_len = le_to_u32(CG + 2);
if (CG_len < c->n_cigar || CG_len >= 1U<<29) return 0; // don't move if the real CIGAR length is shorter than the fake cigar length
// move from the CG tag to the right position
cigar_st = (uint8_t*)cigar0 - b->data;
c->n_cigar = CG_len;
n_cigar4 = c->n_cigar * 4;
CG_st = CG - b->data - 2;
CG_en = CG_st + 8 + n_cigar4;
if (possibly_expand_bam_data(b, n_cigar4 - fake_bytes) < 0) return -1;
b->l_data = b->l_data - fake_bytes + n_cigar4; // we need c->n_cigar-fake_bytes bytes to swap CIGAR to the right place
memmove(b->data + cigar_st + n_cigar4, b->data + cigar_st + fake_bytes, ori_len - (cigar_st + fake_bytes)); // insert c->n_cigar-fake_bytes empty space to make room
memcpy(b->data + cigar_st, b->data + (n_cigar4 - fake_bytes) + CG_st + 8, n_cigar4); // copy the real CIGAR to the right place; -fake_bytes for the fake CIGAR
if (ori_len > CG_en) // move data after the CG tag
memmove(b->data + CG_st + n_cigar4 - fake_bytes, b->data + CG_en + n_cigar4 - fake_bytes, ori_len - CG_en);
b->l_data -= n_cigar4 + 8; // 8: CGBI (4 bytes) and CGBI length (4)
if (recal_bin)
b->core.bin = hts_reg2bin(b->core.pos, bam_endpos(b), 14, 5);
if (give_warning)
hts_log_error("%s encodes a CIGAR with %d operators at the CG tag", bam_get_qname(b), c->n_cigar);
return 1;
}
static inline int aux_type2size(uint8_t type)
{
switch (type) {
case 'A': case 'c': case 'C':
return 1;
case 's': case 'S':
return 2;
case 'i': case 'I': case 'f':
return 4;
case 'd':
return 8;
case 'Z': case 'H': case 'B':
return type;
default:
return 0;
}
}
static void swap_data(const bam1_core_t *c, int l_data, uint8_t *data, int is_host)
{
uint32_t *cigar = (uint32_t*)(data + c->l_qname);
uint32_t i;
for (i = 0; i < c->n_cigar; ++i) ed_swap_4p(&cigar[i]);
}
// Fix bad records where qname is not terminated correctly.
static int fixup_missing_qname_nul(bam1_t *b) {
bam1_core_t *c = &b->core;
// Note this is called before c->l_extranul is added to c->l_qname
if (c->l_extranul > 0) {
b->data[c->l_qname++] = '\0';
c->l_extranul--;
} else {
if (b->l_data > INT_MAX - 4) return -1;
if (realloc_bam_data(b, b->l_data + 4) < 0) return -1;
b->l_data += 4;
b->data[c->l_qname++] = '\0';
c->l_extranul = 3;
}
return 0;
}
/*
* Note a second interface that returns a bam pointer instead would avoid bam_copy1
* in multi-threaded handling. This may be worth considering for htslib2.
*/
int bam_read1(BGZF *fp, bam1_t *b)
{
bam1_core_t *c = &b->core;
int32_t block_len, ret, i;
uint32_t x[8], new_l_data;
b->l_data = 0;
if ((ret = bgzf_read(fp, &block_len, 4)) != 4) {
if (ret == 0) return -1; // normal end-of-file
else return -2; // truncated
}
if (fp->is_be)
ed_swap_4p(&block_len);
if (block_len < 32) return -4; // block_len includes core data
if (bgzf_read(fp, x, 32) != 32) return -3;
if (fp->is_be) {
for (i = 0; i < 8; ++i) ed_swap_4p(x + i);
}
c->tid = x[0]; c->pos = (int32_t)x[1];
c->bin = x[2]>>16; c->qual = x[2]>>8&0xff; c->l_qname = x[2]&0xff;
c->l_extranul = (c->l_qname%4 != 0)? (4 - c->l_qname%4) : 0;
c->flag = x[3]>>16; c->n_cigar = x[3]&0xffff;
c->l_qseq = x[4];
c->mtid = x[5]; c->mpos = (int32_t)x[6]; c->isize = (int32_t)x[7];
new_l_data = block_len - 32 + c->l_extranul;
if (new_l_data > INT_MAX || c->l_qseq < 0 || c->l_qname < 1) return -4;
if (((uint64_t) c->n_cigar << 2) + c->l_qname + c->l_extranul
+ (((uint64_t) c->l_qseq + 1) >> 1) + c->l_qseq > (uint64_t) new_l_data)
return -4;
if (realloc_bam_data(b, new_l_data) < 0) return -4;
b->l_data = new_l_data;
if (bgzf_read(fp, b->data, c->l_qname) != c->l_qname) return -4;
if (b->data[c->l_qname - 1] != '\0') { // Try to fix missing NUL termination
if (fixup_missing_qname_nul(b) < 0) return -4;
}
for (i = 0; i < c->l_extranul; ++i) b->data[c->l_qname+i] = '\0';
c->l_qname += c->l_extranul;
if (b->l_data < c->l_qname ||
bgzf_read(fp, b->data + c->l_qname, b->l_data - c->l_qname) != b->l_data - c->l_qname)
return -4;
if (fp->is_be) swap_data(c, b->l_data, b->data, 0);
if (bam_tag2cigar(b, 0, 0) < 0)
return -4;
if (c->n_cigar > 0) { // recompute "bin" and check CIGAR-qlen consistency
hts_pos_t rlen, qlen;
bam_cigar2rqlens(c->n_cigar, bam_get_cigar(b), &rlen, &qlen);
if ((b->core.flag & BAM_FUNMAP) || rlen == 0) rlen = 1;
b->core.bin = hts_reg2bin(b->core.pos, b->core.pos + rlen, 14, 5);
// Sanity check for broken CIGAR alignments
if (c->l_qseq > 0 && !(c->flag & BAM_FUNMAP) && qlen != c->l_qseq) {
hts_log_error("CIGAR and query sequence lengths differ for %s",
bam_get_qname(b));
return -4;
}
}
return 4 + block_len;
}
int bam_write1(BGZF *fp, const bam1_t *b)
{
const bam1_core_t *c = &b->core;
uint32_t x[8], block_len = b->l_data - c->l_extranul + 32, y;
int i, ok;
if (c->l_qname - c->l_extranul > 255) {
hts_log_error("QNAME \"%s\" is longer than 254 characters", bam_get_qname(b));
errno = EOVERFLOW;
return -1;
}
if (c->n_cigar > 0xffff) block_len += 16; // "16" for "CGBI", 4-byte tag length and 8-byte fake CIGAR
if (c->pos > INT_MAX ||
c->mpos > INT_MAX ||
c->isize < INT_MIN || c->isize > INT_MAX) {
hts_log_error("Positional data is too large for BAM format");
return -1;
}
x[0] = c->tid;
x[1] = c->pos;
x[2] = (uint32_t)c->bin<<16 | c->qual<<8 | (c->l_qname - c->l_extranul);
if (c->n_cigar > 0xffff) x[3] = (uint32_t)c->flag << 16 | 2;
else x[3] = (uint32_t)c->flag << 16 | (c->n_cigar & 0xffff);
x[4] = c->l_qseq;
x[5] = c->mtid;
x[6] = c->mpos;
x[7] = c->isize;
ok = (bgzf_flush_try(fp, 4 + block_len) >= 0);
if (fp->is_be) {
for (i = 0; i < 8; ++i) ed_swap_4p(x + i);
y = block_len;
if (ok) ok = (bgzf_write(fp, ed_swap_4p(&y), 4) >= 0);
swap_data(c, b->l_data, b->data, 1);
} else {
if (ok) ok = (bgzf_write(fp, &block_len, 4) >= 0);
}
if (ok) ok = (bgzf_write(fp, x, 32) >= 0);
if (ok) ok = (bgzf_write(fp, b->data, c->l_qname - c->l_extranul) >= 0);
if (c->n_cigar <= 0xffff) { // no long CIGAR; write normally
if (ok) ok = (bgzf_write(fp, b->data + c->l_qname, b->l_data - c->l_qname) >= 0);
} else { // with long CIGAR, insert a fake CIGAR record and move the real CIGAR to the CG:B,I tag
uint8_t buf[8];
uint32_t cigar_st, cigar_en, cigar[2];
hts_pos_t cigreflen = bam_cigar2rlen(c->n_cigar, bam_get_cigar(b));
if (cigreflen >= (1<<28)) {
// Length of reference covered is greater than the biggest
// CIGAR operation currently allowed.
hts_log_error("Record %s with %d CIGAR ops and ref length %"PRIhts_pos
" cannot be written in BAM. Try writing SAM or CRAM instead.\n",
bam_get_qname(b), c->n_cigar, cigreflen);
return -1;
}
cigar_st = (uint8_t*)bam_get_cigar(b) - b->data;
cigar_en = cigar_st + c->n_cigar * 4;
cigar[0] = (uint32_t)c->l_qseq << 4 | BAM_CSOFT_CLIP;
cigar[1] = (uint32_t)cigreflen << 4 | BAM_CREF_SKIP;
u32_to_le(cigar[0], buf);
u32_to_le(cigar[1], buf + 4);
if (ok) ok = (bgzf_write(fp, buf, 8) >= 0); // write cigar: <read_length>S<ref_length>N
if (ok) ok = (bgzf_write(fp, &b->data[cigar_en], b->l_data - cigar_en) >= 0); // write data after CIGAR
if (ok) ok = (bgzf_write(fp, "CGBI", 4) >= 0); // write CG:B,I
u32_to_le(c->n_cigar, buf);
if (ok) ok = (bgzf_write(fp, buf, 4) >= 0); // write the true CIGAR length
if (ok) ok = (bgzf_write(fp, &b->data[cigar_st], c->n_cigar * 4) >= 0); // write the real CIGAR
}
if (fp->is_be) swap_data(c, b->l_data, b->data, 0);
return ok? 4 + block_len : -1;
}
/*
* Write a BAM file and append to the in-memory index simultaneously.
*/
static int bam_write_idx1(htsFile *fp, const sam_hdr_t *h, const bam1_t *b) {
BGZF *bfp = fp->fp.bgzf;
if (!fp->idx)
return bam_write1(bfp, b);
uint32_t block_len = b->l_data - b->core.l_extranul + 32;
if (bgzf_flush_try(bfp, 4 + block_len) < 0)
return -1;
if (!bfp->mt)
hts_idx_amend_last(fp->idx, bgzf_tell(bfp));
int ret = bam_write1(bfp, b);
if (ret < 0)
return -1;
if (bgzf_idx_push(bfp, fp->idx, b->core.tid, b->core.pos, bam_endpos(b), bgzf_tell(bfp), !(b->core.flag&BAM_FUNMAP)) < 0) {
hts_log_error("Read '%s' with ref_name='%s', ref_length=%"PRIhts_pos", flags=%d, pos=%"PRIhts_pos" cannot be indexed",
bam_get_qname(b), sam_hdr_tid2name(h, b->core.tid), sam_hdr_tid2len(h, b->core.tid), b->core.flag, b->core.pos+1);
ret = -1;
}
return ret;
}
/*
* Set the qname in a BAM record
*/
int bam_set_qname(bam1_t *rec, const char *qname)
{
if (!rec) return -1;
if (!qname || !*qname) return -1;
size_t old_len = rec->core.l_qname;
size_t new_len = strlen(qname) + 1;
if (new_len < 1 || new_len > 255) return -1;
int extranul = (new_len%4 != 0) ? (4 - new_len%4) : 0;
size_t new_data_len = rec->l_data - old_len + new_len + extranul;
if (realloc_bam_data(rec, new_data_len) < 0) return -1;
// Make room
if (new_len + extranul != rec->core.l_qname)
memmove(rec->data + new_len + extranul, rec->data + rec->core.l_qname, rec->l_data - rec->core.l_qname);
// Copy in new name and pad if needed
memcpy(rec->data, qname, new_len);
int n;
for (n = 0; n < extranul; n++) rec->data[new_len + n] = '\0';
rec->l_data = new_data_len;
rec->core.l_qname = new_len + extranul;
rec->core.l_extranul = extranul;
return 0;
}
/********************
*** BAM indexing ***
********************/
static hts_idx_t *sam_index(htsFile *fp, int min_shift)
{
int n_lvls, i, fmt, ret;
bam1_t *b;
hts_idx_t *idx;
sam_hdr_t *h;
h = sam_hdr_read(fp);
if (h == NULL) return NULL;
if (min_shift > 0) {
hts_pos_t max_len = 0, s;
for (i = 0; i < h->n_targets; ++i) {
hts_pos_t len = sam_hdr_tid2len(h, i);
if (max_len < len) max_len = len;
}
max_len += 256;
for (n_lvls = 0, s = 1<<min_shift; max_len > s; ++n_lvls, s <<= 3);
fmt = HTS_FMT_CSI;
} else min_shift = 14, n_lvls = 5, fmt = HTS_FMT_BAI;
idx = hts_idx_init(h->n_targets, fmt, bgzf_tell(fp->fp.bgzf), min_shift, n_lvls);
b = bam_init1();
while ((ret = sam_read1(fp, h, b)) >= 0) {
ret = hts_idx_push(idx, b->core.tid, b->core.pos, bam_endpos(b), bgzf_tell(fp->fp.bgzf), !(b->core.flag&BAM_FUNMAP));
if (ret < 0) { // unsorted or doesn't fit
hts_log_error("Read '%s' with ref_name='%s', ref_length=%"PRIhts_pos", flags=%d, pos=%"PRIhts_pos" cannot be indexed", bam_get_qname(b), sam_hdr_tid2name(h, b->core.tid), sam_hdr_tid2len(h, b->core.tid), b->core.flag, b->core.pos+1);
goto err;
}
}
if (ret < -1) goto err; // corrupted BAM file
hts_idx_finish(idx, bgzf_tell(fp->fp.bgzf));
sam_hdr_destroy(h);
bam_destroy1(b);
return idx;
err:
bam_destroy1(b);
hts_idx_destroy(idx);
return NULL;
}
int sam_index_build3(const char *fn, const char *fnidx, int min_shift, int nthreads)
{
hts_idx_t *idx;
htsFile *fp;