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 <waddlesplash@gmail.com>
This commit is contained in:
ohnx 2018-01-03 16:50:35 +00:00 committed by Augustin Cavalier
parent e46e9fee6b
commit 452ac99fa7
2 changed files with 12 additions and 0 deletions

View File

@ -432,6 +432,7 @@ dosfs_initialize(int fd, partition_id partitionID, const char* name,
written = write_pos(fd, pos, zerobuffer, writesize); written = write_pos(fd, pos, zerobuffer, writesize);
if (written != writesize) { if (written != writesize) {
dprintf("dosfs Error: write error near sector %Ld\n",pos / 512); dprintf("dosfs Error: write error near sector %Ld\n",pos / 512);
free(zerobuffer);
return B_ERROR; return B_ERROR;
} }
bytes_to_write -= writesize; bytes_to_write -= writesize;

View File

@ -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 // avoid doing 512 byte writes here, they are slow
printf("Writing FAT\n"); printf("Writing FAT\n");
char * zerobuffer = (char *)malloc(65536); char * zerobuffer = (char *)malloc(65536);
if (zerobuffer == NULL) {
fprintf(stderr,"Error: out of memory\n");
close(fd);
return B_ERROR;
}
memset(zerobuffer,0,65536); memset(zerobuffer,0,65536);
int64 bytes_to_write = 512LL * (reservedSectorCount + (numFATs * FATSize) + rootDirSectors); int64 bytes_to_write = 512LL * (reservedSectorCount + (numFATs * FATSize) + rootDirSectors);
int64 pos = 0; int64 pos = 0;
@ -476,6 +481,7 @@ status_t Initialize(int fatbits, const char *device, const char *label, bool nop
if (written != writesize) { if (written != writesize) {
fprintf(stderr,"Error: write error near sector %Ld\n",pos / 512); fprintf(stderr,"Error: write error near sector %Ld\n",pos / 512);
close(fd); close(fd);
free(zerobuffer);
return B_ERROR; return B_ERROR;
} }
bytes_to_write -= writesize; 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) { } else if (fatbits == 32) {
int size = 512 * sectorPerCluster; int size = 512 * sectorPerCluster;
uint8 *cluster = (uint8*)malloc(size); uint8 *cluster = (uint8*)malloc(size);
if (cluster == NULL) {
fprintf(stderr,"Error: out of memory\n");
close(fd);
return B_ERROR;
}
memset(cluster, 0, size); memset(cluster, 0, size);
CreateVolumeLabel(cluster, label); CreateVolumeLabel(cluster, label);
uint32 rootDirSector = reservedSectorCount + (numFATs * FATSize) + rootDirSectors; uint32 rootDirSector = reservedSectorCount + (numFATs * FATSize) + rootDirSectors;