From 622afb068f10a1a7daf98cf1380deefd902600e0 Mon Sep 17 00:00:00 2001
From: ohnx <me@masonx.ca>
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.
---
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
|
b
|
dosfs_initialize(int fd, partition_id partitionID, const char* name,
|
432 | 432 | written = write_pos(fd, pos, zerobuffer, writesize); |
433 | 433 | if (written != writesize) { |
434 | 434 | dprintf("dosfs Error: write error near sector %Ld\n",pos / 512); |
| 435 | free(zerobuffer); |
435 | 436 | return B_ERROR; |
436 | 437 | } |
437 | 438 | bytes_to_write -= writesize; |
diff --git a/src/bin/mkdos/mkdos.cpp b/src/bin/mkdos/mkdos.cpp
index bd653521f7..3b1ba9f263 100644
a
|
b
|
status_t Initialize(int fatbits, const char *device, const char *label, bool nop
|
467 | 467 | // avoid doing 512 byte writes here, they are slow |
468 | 468 | printf("Writing FAT\n"); |
469 | 469 | char * zerobuffer = (char *)malloc(65536); |
| 470 | if (zerobuffer == NULL) { |
| 471 | fprintf(stderr,"Error: out of memory\n"); |
| 472 | close(fd); |
| 473 | return B_ERROR; |
| 474 | } |
470 | 475 | memset(zerobuffer,0,65536); |
471 | 476 | int64 bytes_to_write = 512LL * (reservedSectorCount + (numFATs * FATSize) + rootDirSectors); |
472 | 477 | int64 pos = 0; |
… |
… |
status_t Initialize(int fatbits, const char *device, const char *label, bool nop
|
476 | 481 | if (written != writesize) { |
477 | 482 | fprintf(stderr,"Error: write error near sector %Ld\n",pos / 512); |
478 | 483 | close(fd); |
| 484 | free(zerobuffer); |
479 | 485 | return B_ERROR; |
480 | 486 | } |
481 | 487 | bytes_to_write -= writesize; |
… |
… |
status_t Initialize(int fatbits, const char *device, const char *label, bool nop
|
592 | 598 | } else if (fatbits == 32) { |
593 | 599 | int size = 512 * sectorPerCluster; |
594 | 600 | uint8 *cluster = (uint8*)malloc(size); |
| 601 | if (cluster == NULL) { |
| 602 | fprintf(stderr,"Error: out of memory\n"); |
| 603 | close(fd); |
| 604 | return B_ERROR; |
| 605 | } |
595 | 606 | memset(cluster, 0, size); |
596 | 607 | CreateVolumeLabel(cluster, label); |
597 | 608 | uint32 rootDirSector = reservedSectorCount + (numFATs * FATSize) + rootDirSectors; |