From 452ac99fa723a3a1a8467d81763050ad1c296a7d Mon Sep 17 00:00:00 2001 From: ohnx Date: Wed, 3 Jan 2018 16:50:35 +0000 Subject: [PATCH] mkdos: Handle memory allocation better In the kernel and command-line tool, don't leak allocated memory, even if the tool returns an error. In the command-line tool, also handle memory allocation errors nicely by giving the user an OOM message if allocation fails. Fixes CID 1425367 and 1425224. Signed-off-by: Augustin Cavalier --- src/add-ons/kernel/file_systems/fat/mkdos.cpp | 1 + src/bin/mkdos/mkdos.cpp | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/src/add-ons/kernel/file_systems/fat/mkdos.cpp b/src/add-ons/kernel/file_systems/fat/mkdos.cpp index 1557a27e7b..2c88dda5f7 100644 --- a/src/add-ons/kernel/file_systems/fat/mkdos.cpp +++ b/src/add-ons/kernel/file_systems/fat/mkdos.cpp @@ -432,6 +432,7 @@ dosfs_initialize(int fd, partition_id partitionID, const char* name, written = write_pos(fd, pos, zerobuffer, writesize); if (written != writesize) { dprintf("dosfs Error: write error near sector %Ld\n",pos / 512); + free(zerobuffer); return B_ERROR; } bytes_to_write -= writesize; diff --git a/src/bin/mkdos/mkdos.cpp b/src/bin/mkdos/mkdos.cpp index bd653521f7..3b1ba9f263 100644 --- a/src/bin/mkdos/mkdos.cpp +++ b/src/bin/mkdos/mkdos.cpp @@ -467,6 +467,11 @@ status_t Initialize(int fatbits, const char *device, const char *label, bool nop // avoid doing 512 byte writes here, they are slow printf("Writing FAT\n"); char * zerobuffer = (char *)malloc(65536); + if (zerobuffer == NULL) { + fprintf(stderr,"Error: out of memory\n"); + close(fd); + return B_ERROR; + } memset(zerobuffer,0,65536); int64 bytes_to_write = 512LL * (reservedSectorCount + (numFATs * FATSize) + rootDirSectors); int64 pos = 0; @@ -476,6 +481,7 @@ status_t Initialize(int fatbits, const char *device, const char *label, bool nop if (written != writesize) { fprintf(stderr,"Error: write error near sector %Ld\n",pos / 512); close(fd); + free(zerobuffer); return B_ERROR; } bytes_to_write -= writesize; @@ -592,6 +598,11 @@ status_t Initialize(int fatbits, const char *device, const char *label, bool nop } else if (fatbits == 32) { int size = 512 * sectorPerCluster; uint8 *cluster = (uint8*)malloc(size); + if (cluster == NULL) { + fprintf(stderr,"Error: out of memory\n"); + close(fd); + return B_ERROR; + } memset(cluster, 0, size); CreateVolumeLabel(cluster, label); uint32 rootDirSector = reservedSectorCount + (numFATs * FATSize) + rootDirSectors;