1 From 37f0f1550e7822584b858edde416a694fb902236 Mon Sep 17 00:00:00 2001
2 From: Ioana Ciornei <ioana.ciornei@nxp.com>
3 Date: Tue, 31 Jul 2018 13:33:20 +0300
4 Subject: [PATCH] restool: fix get_device_file() function
6 This patch fixes multiple problems encountered in the
7 get_device_file() function:
8 - The deprecated atoi() function is replaced by strtoul
9 - An invalid memory access was being performed by using
10 memory from dir->d_name even after closedir(). This is
11 fixed by a strdup() on the device filename.
12 - Also, error prints now print any relevant error code.
14 Signed-off-by: Ioana Ciornei <ioana.ciornei@nxp.com>
16 restool.c | 44 ++++++++++++++++++++++++++++----------------
17 1 file changed, 28 insertions(+), 16 deletions(-)
19 diff --git a/restool.c b/restool.c
20 index 7553659..78fd1bf 100644
23 @@ -1185,8 +1185,13 @@ out:
25 static int get_device_file(void)
27 + int num_dev_files = 0;
35 memset(restool.device_file, '\0', DEV_FILE_SIZE);
37 @@ -1214,10 +1219,6 @@ static int get_device_file(void)
43 - int num_dev_files = 0;
48 @@ -1227,26 +1228,34 @@ static int get_device_file(void)
50 while ((dir = readdir(d)) != NULL) {
51 if (strncmp(dir->d_name, "dprc.", 5) == 0) {
52 - dprc_index = &dir->d_name[5];
54 + if (num_dev_files == 0)
55 + device = strdup(dir->d_name);
61 if (num_dev_files == 1) {
62 - int temp_len = strlen(dprc_index);
64 + val = strtoul(&device[5], NULL, 0);
65 + if ((errno == ERANGE && val == LONG_MAX) ||
66 + ( errno != 0 && val == 0 )) {
67 + ERROR_PRINTF("error: device file malformed\n");
69 + goto out_free_device;;
71 + restool.root_dprc_id = val;
74 - num_char = sprintf(restool.device_file, "/dev/dprc.%s",
76 - if (num_char != temp_len) {
77 - ERROR_PRINTF("sprintf error\n");
78 + num_char = snprintf(restool.device_file, DEV_FILE_SIZE,
79 + "/dev/dprc.%d", restool.root_dprc_id);
80 + if (num_char < 0 || num_char >= DEV_FILE_SIZE) {
81 + ERROR_PRINTF("error: device file malformed\n");
84 + goto out_free_device;
86 - restool.root_dprc_id = atoi(dprc_index);
87 - if (access(restool.device_file, F_OK) != 0)
88 - printf("no such dev file\n");
89 + error = access(restool.device_file, F_OK);
91 + ERROR_PRINTF("error: access(%s) = %d\n", restool.device_file, error);
94 if (num_dev_files == 0)
95 @@ -1255,6 +1264,9 @@ static int get_device_file(void)
96 ERROR_PRINTF("error: multiple root containers\n");