util: Add handling code to safely read and write arrays 13/314913/3 accepted/tizen_unified_dev accepted/tizen_unified_toolchain accepted/tizen/9.0/unified/20241031.000036 accepted/tizen/unified/20240725.155024 accepted/tizen/unified/dev/20240729.000858 accepted/tizen/unified/toolchain/20240812.132145 accepted/tizen/unified/x/20240726.013207 accepted/tizen/unified/x/asan/20240813.230430 tizen_9.0_m2_release
authorYunhee Seo <yuni.seo@samsung.com>
Tue, 16 Jul 2024 07:21:32 +0000 (16:21 +0900)
committerYunhee Seo <yuni.seo@samsung.com>
Wed, 24 Jul 2024 06:43:37 +0000 (15:43 +0900)
There was a missing code for handling the null character
so that it doesn't exceed the array size when reading and storing strings.
The code has been modified to handle the array safely.
To avoid overflow issue, this is necessary.

Change-Id: Ib75301a07906391c57fb739ef3399ff211cd1503
Signed-off-by: Yunhee Seo <yuni.seo@samsung.com>
src/util.c

index e2abf4b6fced68a99f2c5ddef3481bcc74d280ec..87e0fccbb5e5c17e01eff09a782111c86a26ad91 100644 (file)
@@ -30,19 +30,18 @@ static int sysfs_read_buf(char *path, char *buf, int len)
 
        fd = open(path, O_RDONLY);
        if (fd == -1)
-               return -ENOENT;
+               return -errno;
 
        r = read(fd, buf, len);
        close(fd);
 
-       if ((r < 0) || (r > len))
+       if ((r < 0) || (r >= len)) {
+               buf[0] = '\0';
                return -EIO;
+       }
 
-       /* Replace '\n' with space (ascii code is 32) */
-       buf[strcspn(buf, "\n")] = (char)32;
        buf[r] = '\0';
-
-       return 0;
+       return r;
 }
 
 int sysfs_write_buf(char *path, char *buf)
@@ -54,7 +53,7 @@ int sysfs_write_buf(char *path, char *buf)
 
        fd = open(path, O_WRONLY);
        if (fd == -1)
-               return -ENOENT;
+               return -errno;
 
        w = write(fd, buf, strlen(buf));
        close(fd);
@@ -67,13 +66,13 @@ int sysfs_write_buf(char *path, char *buf)
 
 int sysfs_read_int(char *path, int *val)
 {
-       char buf[MAX_BUF_SIZE + 1];
+       char buf[MAX_BUF_SIZE];
        int r;
 
        if ((!path) || (!val))
                return -EINVAL;
 
-       r = sysfs_read_buf(path, buf, MAX_BUF_SIZE);
+       r = sysfs_read_buf(path, buf, sizeof(buf));
        if (r < 0)
                return r;
 
@@ -97,13 +96,13 @@ int sysfs_read_str(char *path, char *str, int len)
 
 int sysfs_write_int(char *path, int val)
 {
-       char buf[MAX_BUF_SIZE + 1];
+       char buf[MAX_BUF_SIZE];
        int w;
 
        if (!path)
                return -EINVAL;
 
-       snprintf(buf, MAX_BUF_SIZE, "%d", val);
+       snprintf(buf, sizeof(buf), "%d", val);
        w = sysfs_write_buf(path, buf);
        if (w < 0)
                return w;