[LTP] [PATCH v2] genload: fix memory corruption in hogvm()

Jiwei Sun
2024-06-12T02:58:01Z

From: Jiwei Sun <sunjw10@lenovo.com>

When running memory stress test with the following commands,

# ./genload -v --vm 10 --vm-chunks 4 --vm-bytes 1073741824

or

# ./genload -v --vm 10 --vm-chunks 0 --vm-bytes 1073741824

The following error log will be shown,

malloc(): corrupted top size

The root cause of the issue is that allocated memory for ptr is less
than what is actually needed.

Reviewed-by: Adrian Huang <ahuang12@lenovo.com>
Signed-off-by: Jiwei Sun <sunjw10@lenovo.com>
---
v2 changes:
- Delete excess "* 2" when allocate memory for ptr
- Adjust "chunks" from 0 to 1

tools/genload/genload.c | 15 ++++++++++-----
tools/genload/stress.c | 15 ++++++++++-----
2 files changed, 20 insertions(+), 10 deletions(-)

diff --git a/tools/genload/genload.c b/tools/genload/genload.c
index 7f56d5272..a19d519fd 100644
--- a/tools/genload/genload.c
+++ b/tools/genload/genload.c
@@ -641,9 +641,16 @@ int hogvm(long long forks, long long chunks, long long bytes)
/* Use a backoff sleep to ensure we get good fork throughput. */
usleep(backoff);

+ /* If chunks is 0, ptr will allocate 0 bytes's
+ * memory, it will cause the process to crash
+ * during runtime, so adjust to 1 */
+ if (chunks == 0)
+ chunks = 1;
+
while (1) {
- ptr = (char **)malloc(chunks * 2);
- for (j = 0; chunks == 0 || j < chunks; j++) {
+ ptr = (char **)malloc(chunks *
+ sizeof(char *));
+ for (j = 0; j < chunks; j++) {
if ((ptr[j] =
(char *)malloc(bytes *
sizeof(char)))) {
@@ -674,10 +681,8 @@ int hogvm(long long forks, long long chunks, long long bytes)
if (retval == 0) {
dbg(stdout,
"hogvm worker freeing memory and starting over\n");
- for (j = 0; chunks == 0 || j < chunks;
- j++) {
+ for (j = 0; j < chunks; j++)
free(ptr[j]);
- }
free(ptr);
continue;
}
diff --git a/tools/genload/stress.c b/tools/genload/stress.c
index 7f56d5272..a19d519fd 100644
--- a/tools/genload/stress.c
+++ b/tools/genload/stress.c
@@ -641,9 +641,16 @@ int hogvm(long long forks, long long chunks, long long bytes)
/* Use a backoff sleep to ensure we get good fork throughput. */
usleep(backoff);

+ /* If chunks is 0, ptr will allocate 0 bytes's
+ * memory, it will cause the process to crash
+ * during runtime, so adjust to 1 */
+ if (chunks == 0)
+ chunks = 1;
+
while (1) {
- ptr = (char **)malloc(chunks * 2);
- for (j = 0; chunks == 0 || j < chunks; j++) {
+ ptr = (char **)malloc(chunks *
+ sizeof(char *));
+ for (j = 0; j < chunks; j++) {
if ((ptr[j] =
(char *)malloc(bytes *
sizeof(char)))) {
@@ -674,10 +681,8 @@ int hogvm(long long forks, long long chunks, long long bytes)
if (retval == 0) {
dbg(stdout,
"hogvm worker freeing memory and starting over\n");
- for (j = 0; chunks == 0 || j < chunks;
- j++) {
+ for (j = 0; j < chunks; j++)
free(ptr[j]);
- }
free(ptr);
continue;
}
--
2.27.0