linux-user: Move lock_user et al out of line
[qemu/ar7.git] / linux-user / uaccess.c
blobbba012ed1599b09aafac570860b4b166c19258fe
1 /* User memory access */
2 #include "qemu/osdep.h"
3 #include "qemu/cutils.h"
5 #include "qemu.h"
7 void *lock_user(int type, abi_ulong guest_addr, long len, int copy)
9 if (!access_ok_untagged(type, guest_addr, len)) {
10 return NULL;
12 #ifdef DEBUG_REMAP
14 void *addr;
15 addr = g_malloc(len);
16 if (copy) {
17 memcpy(addr, g2h(guest_addr), len);
18 } else {
19 memset(addr, 0, len);
21 return addr;
23 #else
24 return g2h_untagged(guest_addr);
25 #endif
28 #ifdef DEBUG_REMAP
29 void unlock_user(void *host_ptr, abi_ulong guest_addr, long len);
31 if (!host_ptr) {
32 return;
34 if (host_ptr == g2h_untagged(guest_addr)) {
35 return;
37 if (len > 0) {
38 memcpy(g2h_untagged(guest_addr), host_ptr, len);
40 g_free(host_ptr);
42 #endif
44 void *lock_user_string(abi_ulong guest_addr)
46 abi_long len = target_strlen(guest_addr);
47 if (len < 0) {
48 return NULL;
50 return lock_user(VERIFY_READ, guest_addr, (long)(len + 1), 1);
53 /* copy_from_user() and copy_to_user() are usually used to copy data
54 * buffers between the target and host. These internally perform
55 * locking/unlocking of the memory.
57 abi_long copy_from_user(void *hptr, abi_ulong gaddr, size_t len)
59 abi_long ret = 0;
60 void *ghptr;
62 if ((ghptr = lock_user(VERIFY_READ, gaddr, len, 1))) {
63 memcpy(hptr, ghptr, len);
64 unlock_user(ghptr, gaddr, 0);
65 } else
66 ret = -TARGET_EFAULT;
68 return ret;
72 abi_long copy_to_user(abi_ulong gaddr, void *hptr, size_t len)
74 abi_long ret = 0;
75 void *ghptr;
77 if ((ghptr = lock_user(VERIFY_WRITE, gaddr, len, 0))) {
78 memcpy(ghptr, hptr, len);
79 unlock_user(ghptr, gaddr, len);
80 } else
81 ret = -TARGET_EFAULT;
83 return ret;
86 /* Return the length of a string in target memory or -TARGET_EFAULT if
87 access error */
88 abi_long target_strlen(abi_ulong guest_addr1)
90 uint8_t *ptr;
91 abi_ulong guest_addr;
92 int max_len, len;
94 guest_addr = guest_addr1;
95 for(;;) {
96 max_len = TARGET_PAGE_SIZE - (guest_addr & ~TARGET_PAGE_MASK);
97 ptr = lock_user(VERIFY_READ, guest_addr, max_len, 1);
98 if (!ptr)
99 return -TARGET_EFAULT;
100 len = qemu_strnlen((const char *)ptr, max_len);
101 unlock_user(ptr, guest_addr, 0);
102 guest_addr += len;
103 /* we don't allow wrapping or integer overflow */
104 if (guest_addr == 0 ||
105 (guest_addr - guest_addr1) > 0x7fffffff)
106 return -TARGET_EFAULT;
107 if (len != max_len)
108 break;
110 return guest_addr - guest_addr1;