Skip to contentSkip to conversation

hexagon semihosting: Address coverity finding

PATCH Superseded Brian Cain 2 participants 9 messages Sep 23 – Oct 13

v3 of 5 Superseded Latest is v5 →

lore
Share & tools
lore

Brian Cain

author
#0 lore raw

v3 cover hexagon semihosting: Address coverity finding

These fixes are to mitigate the issue(s) reported by Coverity and Peter Maydell.

In v3:
- The first patch now uses get_user_*() for semihosting argument accesses, instead of hexagon_read_memory(), now removed.
- For HEX_SYS_OPEN, filename/len validation errors are handled together.

In v2:
- HEX_SYS_OPEN switched to lock_user() from lock_user_string()
- pulled in {open,read,close}dir from the a prev patch, changes since that v2:
* Replaces POSIX DIR, opendir(), readdir(), and closedir() with portable GLib GDir APIs. {un,}lock_user
* Replaces the fixed BUFSIZ path buffer and byte-by-byte guest reads with lock_user_string()/unlock_user().
* Adds SemihostingDir, which stores the GDir plus enumeration state
* Synthesizes . and .., omitted by glib
* Writes inode zero instead of host d_ino, which GLib does not expose portably.
* Limits returned names to 254 characters plus NUL, rather than depending on host struct dirent::d_name size. Prev opendir v2: https://lore.kernel.org/qemu-devel/[email protected]/

v2: https://lore.kernel.org/qemu-devel/[email protected]/
v1: https://lore.kernel.org/qemu-devel/[email protected]/

Brian Cain (3):
target/hexagon: fix semihosting OPEN filename handling target/hexagon: fix semihosting STAT filename handling target/hexagon: fix semihosting ACCESS filename handling

Matheus Tavares Bernardino (1):
target/hexagon: add directory semihosting operations

 include/hw/hexagon/hexagon.h              |  14 +-
 target/hexagon/cpu_helper.h               |   2 -
 hw/hexagon/hex-subsys.c                   |  32 ++-
 target/hexagon/cpu_helper.c               |  48 +----
 target/hexagon/hexswi.c                   | 242 +++++++++++++++++-----
 tests/functional/hexagon/test_systests.py |  11 +
 6 files changed, 235 insertions(+), 114 deletions(-)
Signature · 1 line
2.34.1
author
#1 lore raw

PATCH v3 1/4 target/hexagon: fix semihosting OPEN filename handling

HEX_SYS_OPEN copied guest bytes into a fixed-size buffer until it found a NUL. A missing terminator could overrun that buffer. Use lock_user() with the ABI filename length and validate its terminating NUL before opening it.

Replace hexagon_read_memory() with get_user_*() for semihosting argument accesses.

Fixes 7711fdba88b ("target/hexagon: add main arch-specific semihosting operations")
---
 target/hexagon/cpu_helper.h |   2 -
 target/hexagon/cpu_helper.c |  48 ++--------------
 target/hexagon/hexswi.c     | 107 ++++++++++++++++++++++--------------
 3 files changed, 70 insertions(+), 87 deletions(-)
target/hexagon/cpu_helper.h +0 -2
index 12512efd74f..d6b2dfa4b03 100644
@@ -7,8 +7,6 @@
 #ifndef HEXAGON_CPU_HELPER_H
 #define HEXAGON_CPU_HELPER_H
 
-void hexagon_read_memory(CPUHexagonState *env, target_ulong vaddr, int size,
-                         void *retptr, uintptr_t retaddr);
 void hexagon_write_memory(CPUHexagonState *env, target_ulong vaddr,
                           int size, uint64_t data, uintptr_t retaddr);
 void hexagon_peek_memory_range(CPUHexagonState *env, uint32_t start_addr,
target/hexagon/cpu_helper.c +4 -44

63 lines not on this page · raw message

target/hexagon/hexswi.c +66 -41

217 lines not on this page · raw message

Signature · 1 line
2.34.1
#2 lore raw

Re: [PATCH v3 1/4] target/hexagon: fix semihosting OPEN filename handling

Quoted 7 lines · Brian Cain

HEX_SYS_OPEN copied guest bytes into a fixed-size buffer until it found a NUL. A missing terminator could overrun that buffer. Use lock_user() with the ABI filename length and validate its terminating NUL before opening it.

Replace hexagon_read_memory() with get_user_*() for semihosting argument accesses.

This is doing two things; it really ought to be two patches, I think.

thanks
-- PMM

author
#3 lore raw

Re: [PATCH v3 1/4] target/hexagon: fix semihosting OPEN filename handling

Quoted 8 lines · Peter Maydell
Quoted 6 lines · Brian Cain

HEX_SYS_OPEN copied guest bytes into a fixed-size buffer until it found a NUL. A missing terminator could overrun that buffer. Use lock_user() with the ABI filename length and validate its terminating NUL before opening it.

Replace hexagon_read_memory() with get_user_*() for semihosting argument accesses.

This is doing two things; it really ought to be two patches, I think.

Okay - will split them up.

Quoted 2 lines

thanks
-- PMM

author
#4 lore raw

PATCH v3 2/4 target/hexagon: fix semihosting STAT filename handling

In reply to Brian Cain

HEX_SYS_STAT could pass an unterminated local filename buffer to stat() when the guest string filled it. Use lock_user_string() to map the guest string safely.

---
 target/hexagon/hexswi.c | 15 +++++++--------
 1 file changed, 7 insertions(+), 8 deletions(-)
target/hexagon/hexswi.c +7 -8
index 6a4c42914e1..9e885344a73 100644
@@ -564,7 +564,7 @@ static void sim_handle_trap0(CPUHexagonState *env)
         struct stat st_buf;
         uint8_t *st_bufptr = (uint8_t *)&sys_stat;
         int rc, err = 0;
-        char filename[BUFSIZ];
+        char *filename;
         target_ulong physical_filename_addr;
         target_ulong statBufferAddr;
         if (get_user_u32(physical_filename_addr, swi_info) ||
@@ -573,15 +573,14 @@ static void sim_handle_trap0(CPUHexagonState *env)
         }
 
         if (what_swi == HEX_SYS_STAT) {
-            int i = 0;
-            do {
-                if (get_user_u8(filename[i], physical_filename_addr + i)) {
-                    goto do_fault;
-                }
-                i++;
-            } while ((i < BUFSIZ) && filename[i - 1]);
+            filename = lock_user_string(physical_filename_addr);
+            if (!filename) {
+                semi_cb(cs, -1, EFAULT);
+                break;
+            }
             rc = stat(filename, &st_buf);
             err = errno;
+            unlock_user(filename, physical_filename_addr, 0);
         } else {
             int fd = physical_filename_addr;
             GuestFD *gf = get_guestfd(fd);
Signature · 1 line
2.34.1
author
#5 lore raw

PATCH v3 3/4 target/hexagon: fix semihosting ACCESS filename handling

In reply to Brian Cain

HEX_SYS_ACCESS wrote a NUL byte past its fixed-size filename buffer when the guest string filled it. Use lock_user_string() to avoid the out-of-bounds write.

Fixes 7711fdba88b ("target/hexagon: add main arch-specific semihosting operations")

Resolves: Coverity CID 1685942

---
 target/hexagon/hexswi.c | 22 ++++++++++------------
 1 file changed, 10 insertions(+), 12 deletions(-)
target/hexagon/hexswi.c +10 -12
index 9e885344a73..a18e675aec9 100644
@@ -626,26 +626,24 @@ static void sim_handle_trap0(CPUHexagonState *env)
 
     case HEX_SYS_ACCESS:
     {
-        char filename[BUFSIZ];
+        char *filename;
         uint32_t FileNameAddr;
         uint32_t BufferMode;
-        int rc;
-
-        int i = 0;
+        int rc, err;
 
         if (get_user_u32(FileNameAddr, swi_info) ||
             get_user_u32(BufferMode, swi_info + 4)) {
             goto do_fault;
         }
-        do {
-            if (get_user_u8(filename[i], FileNameAddr + i)) {
-                goto do_fault;
-            }
-            i++;
-        } while ((i < BUFSIZ) && (filename[i - 1]));
-        filename[i] = 0;
+        filename = lock_user_string(FileNameAddr);
+        if (!filename) {
+            semi_cb(cs, -1, EFAULT);
+            break;
+        }
         rc = access(filename, BufferMode);
-        semi_cb(cs, rc,  rc == 0 ? 0 : errno);
+        err = errno;
+        unlock_user(filename, FileNameAddr, 0);
+        semi_cb(cs, rc,  rc == 0 ? 0 : err);
     }
     break;
 
Signature · 1 line
2.34.1
author
#6 lore raw

PATCH v3 4/4 target/hexagon: add directory semihosting operations

In reply to Brian Cain

From: Matheus Tavares Bernardino <[email protected]>

Bare-metal Hexagon programs use OPENDIR, READDIR, and CLOSEDIR semihosting calls to enumerate host directories. Directory handles are shared by CPUs in a cluster, allowing guest indices to resolve across calls.

Use lock_user_string()/unlock_user() to read the OPENDIR path from guest memory instead of copying it into a fixed-size buffer.

CLOSEDIR clears its slot in the directory list, so a stale index reports EBADF instead of dereferencing a freed pointer.

Also add a functional test for the new semihosting operations.

---
 include/hw/hexagon/hexagon.h              |  14 ++-
 hw/hexagon/hex-subsys.c                   |  32 ++++---
 target/hexagon/hexswi.c                   | 108 ++++++++++++++++++++++
 tests/functional/hexagon/test_systests.py |  11 +++
 4 files changed, 153 insertions(+), 12 deletions(-)
include/hw/hexagon/hexagon.h +13 -1
index 62398eeb359..58bdcabe87e 100644
@@ -11,6 +11,7 @@
 
 #include "system/memory.h"
 #include "hw/core/boards.h"
+#include "hw/cpu/cluster.h"
 
 struct hexagon_board_boot_info {
     uint64_t ram_size;
@@ -159,6 +160,17 @@ struct hexagon_machine_config {
     union hexagon_config_table cfgtable;
 };
 
+#define TYPE_HEXAGON_CLUSTER_STATE "hexagon-cluster-state"
+OBJECT_DECLARE_SIMPLE_TYPE(HexagonClusterState, HEXAGON_CLUSTER_STATE)
+
+struct HexagonClusterState {
+    CPUClusterState parent_obj;
+
+    struct {
+        GList *dir_list;
+    } semihosting;
+};
+
 #define TYPE_HEXAGON_COMMON_MACHINE "hexagon-common-machine"
 OBJECT_DECLARE_SIMPLE_TYPE(HexagonCommonMachineState, HEXAGON_COMMON_MACHINE)
 
@@ -168,7 +180,7 @@ struct HexagonCommonMachineState {
     MemoryRegion ram;
     MemoryRegion cfgtable_rom;
     MemoryRegion vtcm;
-    DeviceState *cluster;
+    HexagonClusterState cluster;
     DeviceState *l2vic;
     DeviceState *qtimer;
     DeviceState *glob_regs;
hw/hexagon/hex-subsys.c +21 -11
index 4e3a418340e..f76f803dfb0 100644
@@ -98,14 +98,11 @@ static DeviceState *tlb_create(HexagonCommonMachineState *hms,
     return tlb;
 }
 
-static DeviceState *cluster_create(HexagonCommonMachineState *hms)
+static void cluster_create(HexagonCommonMachineState *hms)
 {
-    DeviceState *cluster = qdev_new(TYPE_CPU_CLUSTER);
-
-    object_property_add_child(OBJECT(hms), "cluster", OBJECT(cluster));
-    qdev_prop_set_uint32(cluster, "cluster-id", 0);
-
-    return cluster;
+    object_initialize_child(OBJECT(hms), "cluster", &hms->cluster,
+                            TYPE_HEXAGON_CLUSTER_STATE);
+    qdev_prop_set_uint32(DEVICE(&hms->cluster), "cluster-id", 0);
 }
 
 void hex_subsys_create(HexagonCommonMachineState *hms,
@@ -135,7 +132,7 @@ void hex_subsys_create(HexagonCommonMachineState *hms,
                                     &hms->vtcm);
     }
 
-    hms->cluster = cluster_create(hms);
+    cluster_create(hms);
     hms->l2vic = l2vic_create(hms, m_cfg);
     hms->qtimer = qtimer_create(hms, m_cfg);
     hms->glob_regs = globalreg_create(hms, m_cfg, rev);
@@ -144,7 +141,7 @@ void hex_subsys_create(HexagonCommonMachineState *hms,
 
 void hex_subsys_add_cpu(HexagonCommonMachineState *hms, DeviceState *cpu)
 {
-    object_property_add_child(OBJECT(hms->cluster), "cpu[*]", OBJECT(cpu));
+    object_property_add_child(OBJECT(&hms->cluster), "cpu[*]", OBJECT(cpu));
     object_property_set_link(OBJECT(cpu), "global-regs",
                              OBJECT(hms->glob_regs), &error_fatal);
     object_property_set_link(OBJECT(cpu), "tlb", OBJECT(hms->tlb),
@@ -158,10 +155,10 @@ void hex_subsys_realize_cluster(HexagonCommonMachineState *hms)
     /*
      * The cluster must be realized after its CPUs have been parented into it
      * (see hex_subsys_add_cpu()) but before any CPU is itself realized, since
-     * qdev_realize_and_unref() on a CPU latches cluster_index into the TCG
+     * qdev_realize() on a CPU latches cluster_index into the TCG
      * cflags at that point.
      */
-    qdev_realize_and_unref(hms->cluster, NULL, &error_fatal);
+    qdev_realize(DEVICE(&hms->cluster), NULL, &error_fatal);
 }
 
 void hex_subsys_realize_cpu(HexagonCommonMachineState *hms, DeviceState *cpu,
@@ -173,3 +170,16 @@ void hex_subsys_realize_cpu(HexagonCommonMachineState *hms, DeviceState *cpu,
         l2vic_connect_cpu(hms->l2vic, cpu);
     }
 }
+
+static const TypeInfo hexagon_cluster_type_info = {
+    .name = TYPE_HEXAGON_CLUSTER_STATE,
+    .parent = TYPE_CPU_CLUSTER,
+    .instance_size = sizeof(HexagonClusterState),
+};
+
+static void hexagon_cluster_register_types(void)
+{
+    type_register_static(&hexagon_cluster_type_info);
+}
+
+type_init(hexagon_cluster_register_types)
target/hexagon/hexswi.c +108 -0

132 lines not on this page · raw message

tests/functional/hexagon/test_systests.py +11 -0
index 2779efa9172..a1080f7b974 100755
@@ -7,6 +7,7 @@
 import re
 import time
 import unittest
+from pathlib import Path
 
 from qemu_test import QemuSystemTest, Asset, wait_for_console_pattern
 
@@ -99,5 +100,15 @@ def test_mmu_multi_tlb(self):
     def test_timer_reg(self):
         self.run_exit_zero("timer_reg")
 
+    def test_dirent(self):
+        testdir = Path(self.scratch_file("_testdir_dirent"))
+        testdir.mkdir()
+        files = ["file1", "file2"]
+        for f in files:
+            testdir.joinpath(f).touch()
+        expected = ". .. " + " ".join(files)
+        self.run_console_pattern("dirent", expected, "-append",
+                                 str(testdir))
+
 if __name__ == "__main__":
     QemuSystemTest.main()
Signature · 1 line
2.34.1
#7 lore raw

Re: [PATCH v3 4/4] target/hexagon: add directory semihosting operations

Quoted 40 lines · Brian Cain

From: Matheus Tavares Bernardino <[email protected]>

Bare-metal Hexagon programs use OPENDIR, READDIR, and CLOSEDIR semihosting calls to enumerate host directories. Directory handles are shared by CPUs in a cluster, allowing guest indices to resolve across calls.

Use lock_user_string()/unlock_user() to read the OPENDIR path from guest memory instead of copying it into a fixed-size buffer.

CLOSEDIR clears its slot in the directory list, so a stale index reports EBADF instead of dereferencing a freed pointer.

Also add a functional test for the new semihosting operations.

---
 include/hw/hexagon/hexagon.h              |  14 ++-
 hw/hexagon/hex-subsys.c                   |  32 ++++---
 target/hexagon/hexswi.c                   | 108 ++++++++++++++++++++++
 tests/functional/hexagon/test_systests.py |  11 +++
 4 files changed, 153 insertions(+), 12 deletions(-)
include/hw/hexagon/hexagon.h +1 -0
index 62398eeb359..58bdcabe87e 100644
@@ -11,6 +11,7 @@
 
 #include "system/memory.h"
 #include "hw/core/boards.h"
+#include "hw/cpu/cluster.h"
 
 struct hexagon_board_boot_info {
     uint64_t ram_size;
@@ -159,6 +160,17 @@ struct hexagon_machine_config {
     union hexagon_config_table cfgtable;
 };
 

include/hw/hexagon/hexagon.h struct hexagon_machine_config { · line 172

Quoted 10 lines
include/hw/hexagon/hexagon.h +10 -0
+#define TYPE_HEXAGON_CLUSTER_STATE "hexagon-cluster-state"
+OBJECT_DECLARE_SIMPLE_TYPE(HexagonClusterState, HEXAGON_CLUSTER_STATE)
+
+struct HexagonClusterState {
+    CPUClusterState parent_obj;
+
+    struct {
+        GList *dir_list;
+    } semihosting;
+};

I still don't think we should be holding this semihosting specific information in a struct in the hardware-emulation side of the code. File descriptors aren't per-cluster, they're shared across all of QEMU (i.e. you can open a file in one cluster and read it from another), so opendir handles also should have the same semantics. That also means the code for them can be in the semihosting related files, and not spill out into the hardawre-emulation files.

Compare semihosting/guestfd.c, where we handle filedescriptors for the guest by tracking them in a file-scoped global variable.

-- PMM

author
#8 lore raw

Re: [PATCH v3 4/4] target/hexagon: add directory semihosting operations

Quoted 40 lines · Peter Maydell
Quoted 39 lines · Brian Cain

From: Matheus Tavares Bernardino <[email protected]>

Bare-metal Hexagon programs use OPENDIR, READDIR, and CLOSEDIR semihosting calls to enumerate host directories. Directory handles are shared by CPUs in a cluster, allowing guest indices to resolve across calls.

Use lock_user_string()/unlock_user() to read the OPENDIR path from guest memory instead of copying it into a fixed-size buffer.

CLOSEDIR clears its slot in the directory list, so a stale index reports EBADF instead of dereferencing a freed pointer.

Also add a functional test for the new semihosting operations.

---
  include/hw/hexagon/hexagon.h              |  14 ++-
  hw/hexagon/hex-subsys.c                   |  32 ++++---
  target/hexagon/hexswi.c                   | 108 ++++++++++++++++++++++
  tests/functional/hexagon/test_systests.py |  11 +++
  4 files changed, 153 insertions(+), 12 deletions(-)
include/hw/hexagon/hexagon.h +1 -0
index 62398eeb359..58bdcabe87e 100644
@@ -11,6 +11,7 @@
 
  #include "system/memory.h"
  #include "hw/core/boards.h"
+#include "hw/cpu/cluster.h"
 
  struct hexagon_board_boot_info {
      uint64_t ram_size;
@@ -159,6 +160,17 @@ struct hexagon_machine_config {
      union hexagon_config_table cfgtable;
  };
 
Quoted 12 lines

include/hw/hexagon/hexagon.h struct hexagon_machine_config { · line 172

Quoted 10 lines
include/hw/hexagon/hexagon.h +10 -0
+#define TYPE_HEXAGON_CLUSTER_STATE "hexagon-cluster-state"
+OBJECT_DECLARE_SIMPLE_TYPE(HexagonClusterState, HEXAGON_CLUSTER_STATE)
+
+struct HexagonClusterState {
+    CPUClusterState parent_obj;
+
+    struct {
+        GList *dir_list;
+    } semihosting;
+};

I still don't think we should be holding this semihosting specific information in a struct in the hardware-emulation

I tossed this patch in to the series here, thinking it was fully-baked and ready-to-roll and relevant to the series.  But I agree with your assessment, it doesn't make sense to put this state here, even if Hexagon would be the only architecture to leverage it.

I'll drop this patch from future revisions of this series and revisit the design before sending it for review on its own.  For now, the remainder of the patches can proceed with review focused on the coverity issues reported.

Quoted 11 lines

side of the code. File descriptors aren't per-cluster, they're shared across all of QEMU (i.e. you can open a file in one cluster and read it from another), so opendir handles also should have the same semantics. That also means the code for them can be in the semihosting related files, and not spill out into the hardawre-emulation files.

Compare semihosting/guestfd.c, where we handle filedescriptors for the guest by tracking them in a file-scoped global variable.

-- PMM