Skip to content

Commit bfc66da

Browse files
sigprofJunio C Hamano
authored andcommitted
[PATCH] Plug memory leak in write_sha1_to_fd()
If the object to write was packed, both its uncompressed and compressed data were leaked. If the object was not packed, its file was not unmapped. [jc: I think it still leaks on the write error path of write_sha1_to_fd(), but that should be fixable in a small separate patch.] Signed-off-by: Sergey Vlasov <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 1cf58e7 commit bfc66da

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

sha1_file.c

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1297,8 +1297,11 @@ int write_sha1_to_fd(int fd, const unsigned char *sha1)
12971297
ssize_t size;
12981298
unsigned long objsize;
12991299
int posn = 0;
1300-
void *buf = map_sha1_file_internal(sha1, &objsize);
1300+
void *map = map_sha1_file_internal(sha1, &objsize);
1301+
void *buf = map;
1302+
void *temp_obj = NULL;
13011303
z_stream stream;
1304+
13021305
if (!buf) {
13031306
unsigned char *unpacked;
13041307
unsigned long len;
@@ -1314,7 +1317,7 @@ int write_sha1_to_fd(int fd, const unsigned char *sha1)
13141317
memset(&stream, 0, sizeof(stream));
13151318
deflateInit(&stream, Z_BEST_COMPRESSION);
13161319
size = deflateBound(&stream, len + hdrlen);
1317-
buf = xmalloc(size);
1320+
temp_obj = buf = xmalloc(size);
13181321

13191322
/* Compress it */
13201323
stream.next_out = buf;
@@ -1332,6 +1335,7 @@ int write_sha1_to_fd(int fd, const unsigned char *sha1)
13321335
while (deflate(&stream, Z_FINISH) == Z_OK)
13331336
/* nothing */;
13341337
deflateEnd(&stream);
1338+
free(unpacked);
13351339

13361340
objsize = stream.total_out;
13371341
}
@@ -1348,6 +1352,12 @@ int write_sha1_to_fd(int fd, const unsigned char *sha1)
13481352
}
13491353
posn += size;
13501354
} while (posn < objsize);
1355+
1356+
if (map)
1357+
munmap(map, objsize);
1358+
if (temp_obj)
1359+
free(temp_obj);
1360+
13511361
return 0;
13521362
}
13531363

0 commit comments

Comments
 (0)