Skip to content

Commit 0fa8598

Browse files
committed
cli: fix cli_options.target leaking memory
1 parent c998dd0 commit 0fa8598

File tree

2 files changed

+22
-9
lines changed

2 files changed

+22
-9
lines changed

include/cli.h

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,12 @@
22
#define HAVE_CLI_H
33
#include "common.h"
44

5+
/* System */
6+
7+
#include <linux/limits.h>
8+
59
/* Local */
10+
611
#include "ept.h"
712

813
/* Enumerable */
@@ -54,7 +59,7 @@ struct
5459
uint64_t gap_partition;
5560
uint64_t gap_reserved;
5661
size_t size;
57-
char * target;
62+
char target[PATH_MAX];
5863
};
5964

6065
/* Variable */

src/cli.c

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
/* System */
66

7+
#include <bits/getopt_core.h>
78
#include <errno.h>
89
#include <fcntl.h>
910
#include <getopt.h>
@@ -77,7 +78,7 @@ struct cli_options cli_options = {
7778
.gap_partition = EPT_PARTITION_GAP_GENERIC,
7879
.gap_reserved = EPT_PARTITION_GAP_RESERVED,
7980
.size = 0,
80-
.target = NULL
81+
.target = ""
8182
};
8283

8384
/* Function */
@@ -302,6 +303,17 @@ cli_parse_options(
302303
return 0;
303304
}
304305

306+
static inline
307+
void
308+
cli_option_replace_target(
309+
// struct cli_options *const restrict cli_options,
310+
char const *const restrict target
311+
){
312+
size_t len_target = strnlen(target, (sizeof cli_options.target) - 1);
313+
memcpy(cli_options.target, target, len_target);
314+
cli_options.target[len_target] = '\0';
315+
}
316+
305317
static inline
306318
int
307319
cli_find_disk(){
@@ -311,8 +323,8 @@ cli_find_disk(){
311323
return 1;
312324
}
313325
pr_error("CLI interface: Operating on '%s' instead, content type is now disk\n", path_disk);
314-
free(cli_options.target);
315-
cli_options.target = path_disk;
326+
cli_option_replace_target(path_disk);
327+
free(path_disk);
316328
cli_options.content = CLI_CONTENT_TYPE_DISK;
317329
return 0;
318330
}
@@ -384,11 +396,7 @@ cli_complete_options(
384396
cli_options.write = CLI_WRITE_NOTHING;
385397
}
386398
if (optind < argc) {
387-
cli_options.target = strdup(argv[optind++]);
388-
if (!cli_options.target) {
389-
pr_error("CLI interface: Failed to duplicate target string '%s'\n", argv[optind-1]);
390-
return 2;
391-
}
399+
cli_option_replace_target(argv[optind++]);
392400
pr_error("CLI interface: Operating on target file/block device '%s'\n", cli_options.target);
393401
int const r = cli_options_complete_target_info();
394402
if (r) {

0 commit comments

Comments
 (0)