reftable/blocksource: handle allocation failures

Handle allocation failures in the blocksource code. Signed-off-by: Patrick Steinhardt <ps@pks.im> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Patrick Steinhardt committed Oct 2, 2024 at 12:56 UTC cd6a47167e068812735950b841c7174cd7cd321e
1 file changed +20 -5
reftable/blocksource.c
+20 -5
@@ -30,6 +30,8 @@ static int strbuf_read_block(void *v, struct reftable_block *dest, uint64_t off,
30 struct strbuf *b = v;
31 assert(off + size <= b->len);
32 REFTABLE_CALLOC_ARRAY(dest->data, size);
33 + if (!dest->data)
34 + return -1;
35 memcpy(dest->data, b->buf + off, size);
36 dest->len = size;
37 return size;
@@ -98,27 +100,40 @@ int reftable_block_source_from_file(struct reftable_block_source *bs,
100 {
101 struct file_block_source *p;
102 struct stat st;
101 - int fd;
103 + int fd, err;
104
105 fd = open(name, O_RDONLY);
106 if (fd < 0) {
107 if (errno == ENOENT)
108 return REFTABLE_NOT_EXIST_ERROR;
107 - return -1;
109 + err = -1;
110 + goto out;
111 }
112
113 if (fstat(fd, &st) < 0) {
111 - close(fd);
112 - return REFTABLE_IO_ERROR;
114 + err = REFTABLE_IO_ERROR;
115 + goto out;
116 }
117
118 REFTABLE_CALLOC_ARRAY(p, 1);
119 + if (!p) {
120 + err = REFTABLE_OUT_OF_MEMORY_ERROR;
121 + goto out;
122 + }
123 +
124 p->size = st.st_size;
125 p->data = xmmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
118 - close(fd);
126
127 assert(!bs->ops);
128 bs->ops = &file_vtable;
129 bs->arg = p;
130 +
131 + err = 0;
132 +
133 +out:
134 + if (fd >= 0)
135 + close(fd);
136 + if (err < 0)
137 + reftable_free(p);
138 return 0;
139 }