Merge tag 'v9.0.0-rc3'
[qemu/ar7.git] / linux-user / uaccess.c
blob425cbf677f760351a5d70ac3d6fe9f8197c85694
1 /* User memory access */
2 #include "qemu/osdep.h"
3 #include "qemu/cutils.h"
5 #include "qemu.h"
6 #include "user-internals.h"
8 void *lock_user(int type, abi_ulong guest_addr, ssize_t len, bool copy)
10 void *host_addr;
12 guest_addr = cpu_untagged_addr(thread_cpu, guest_addr);
13 if (!access_ok_untagged(type, guest_addr, len)) {
14 return NULL;
16 host_addr = g2h_untagged(guest_addr);
17 #ifdef DEBUG_REMAP
18 if (copy) {
19 host_addr = g_memdup(host_addr, len);
20 } else {
21 host_addr = g_malloc0(len);
23 #endif
24 return host_addr;
27 #ifdef DEBUG_REMAP
28 void unlock_user(void *host_ptr, abi_ulong guest_addr, ssize_t len)
30 void *host_ptr_conv;
32 if (!host_ptr) {
33 return;
35 host_ptr_conv = g2h(thread_cpu, guest_addr);
36 if (host_ptr == host_ptr_conv) {
37 return;
39 if (len > 0) {
40 memcpy(host_ptr_conv, host_ptr, len);
42 g_free(host_ptr);
44 #endif
46 void *lock_user_string(abi_ulong guest_addr)
48 ssize_t len = target_strlen(guest_addr);
49 if (len < 0) {
50 return NULL;
52 return lock_user(VERIFY_READ, guest_addr, len + 1, 1);
55 /* copy_from_user() and copy_to_user() are usually used to copy data
56 * buffers between the target and host. These internally perform
57 * locking/unlocking of the memory.
59 int copy_from_user(void *hptr, abi_ulong gaddr, ssize_t len)
61 int ret = 0;
62 void *ghptr = lock_user(VERIFY_READ, gaddr, len, 1);
64 if (ghptr) {
65 memcpy(hptr, ghptr, len);
66 unlock_user(ghptr, gaddr, 0);
67 } else {
68 ret = -TARGET_EFAULT;
70 return ret;
73 int copy_to_user(abi_ulong gaddr, void *hptr, ssize_t len)
75 int ret = 0;
76 void *ghptr = lock_user(VERIFY_WRITE, gaddr, len, 0);
78 if (ghptr) {
79 memcpy(ghptr, hptr, len);
80 unlock_user(ghptr, gaddr, len);
81 } else {
82 ret = -TARGET_EFAULT;
85 return ret;
88 /* Return the length of a string in target memory or -TARGET_EFAULT if
89 access error */
90 ssize_t target_strlen(abi_ulong guest_addr1)
92 uint8_t *ptr;
93 abi_ulong guest_addr;
94 size_t max_len, len;
96 guest_addr = guest_addr1;
97 for(;;) {
98 max_len = TARGET_PAGE_SIZE - (guest_addr & ~TARGET_PAGE_MASK);
99 ptr = lock_user(VERIFY_READ, guest_addr, max_len, 1);
100 if (!ptr)
101 return -TARGET_EFAULT;
102 len = qemu_strnlen((const char *)ptr, max_len);
103 unlock_user(ptr, guest_addr, 0);
104 guest_addr += len;
105 /* we don't allow wrapping or integer overflow */
106 if (guest_addr == 0 || (guest_addr - guest_addr1) > 0x7fffffff) {
107 return -TARGET_EFAULT;
109 if (len != max_len) {
110 break;
113 return guest_addr - guest_addr1;