]> Git Repo - qemu.git/blob - linux-user/syscall.c
linux-user: Fix conversion of sigevent argument to timer_create
[qemu.git] / linux-user / syscall.c
1 /*
2  *  Linux syscalls
3  *
4  *  Copyright (c) 2003 Fabrice Bellard
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
18  */
19 #define _ATFILE_SOURCE
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <stdarg.h>
23 #include <string.h>
24 #include <elf.h>
25 #include <endian.h>
26 #include <errno.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <time.h>
30 #include <limits.h>
31 #include <grp.h>
32 #include <sys/types.h>
33 #include <sys/ipc.h>
34 #include <sys/msg.h>
35 #include <sys/wait.h>
36 #include <sys/time.h>
37 #include <sys/stat.h>
38 #include <sys/mount.h>
39 #include <sys/file.h>
40 #include <sys/fsuid.h>
41 #include <sys/personality.h>
42 #include <sys/prctl.h>
43 #include <sys/resource.h>
44 #include <sys/mman.h>
45 #include <sys/swap.h>
46 #include <linux/capability.h>
47 #include <signal.h>
48 #include <sched.h>
49 #ifdef __ia64__
50 int __clone2(int (*fn)(void *), void *child_stack_base,
51              size_t stack_size, int flags, void *arg, ...);
52 #endif
53 #include <sys/socket.h>
54 #include <sys/un.h>
55 #include <sys/uio.h>
56 #include <sys/poll.h>
57 #include <sys/times.h>
58 #include <sys/shm.h>
59 #include <sys/sem.h>
60 #include <sys/statfs.h>
61 #include <utime.h>
62 #include <sys/sysinfo.h>
63 //#include <sys/user.h>
64 #include <netinet/ip.h>
65 #include <netinet/tcp.h>
66 #include <linux/wireless.h>
67 #include <linux/icmp.h>
68 #include "qemu-common.h"
69 #ifdef TARGET_GPROF
70 #include <sys/gmon.h>
71 #endif
72 #ifdef CONFIG_EVENTFD
73 #include <sys/eventfd.h>
74 #endif
75 #ifdef CONFIG_EPOLL
76 #include <sys/epoll.h>
77 #endif
78 #ifdef CONFIG_ATTR
79 #include "qemu/xattr.h"
80 #endif
81 #ifdef CONFIG_SENDFILE
82 #include <sys/sendfile.h>
83 #endif
84
85 #define termios host_termios
86 #define winsize host_winsize
87 #define termio host_termio
88 #define sgttyb host_sgttyb /* same as target */
89 #define tchars host_tchars /* same as target */
90 #define ltchars host_ltchars /* same as target */
91
92 #include <linux/termios.h>
93 #include <linux/unistd.h>
94 #include <linux/cdrom.h>
95 #include <linux/hdreg.h>
96 #include <linux/soundcard.h>
97 #include <linux/kd.h>
98 #include <linux/mtio.h>
99 #include <linux/fs.h>
100 #if defined(CONFIG_FIEMAP)
101 #include <linux/fiemap.h>
102 #endif
103 #include <linux/fb.h>
104 #include <linux/vt.h>
105 #include <linux/dm-ioctl.h>
106 #include <linux/reboot.h>
107 #include <linux/route.h>
108 #include <linux/filter.h>
109 #include <linux/blkpg.h>
110 #include "linux_loop.h"
111 #include "uname.h"
112
113 #include "qemu.h"
114
115 #define CLONE_NPTL_FLAGS2 (CLONE_SETTLS | \
116     CLONE_PARENT_SETTID | CLONE_CHILD_SETTID | CLONE_CHILD_CLEARTID)
117
118 //#define DEBUG
119
120 //#include <linux/msdos_fs.h>
121 #define VFAT_IOCTL_READDIR_BOTH         _IOR('r', 1, struct linux_dirent [2])
122 #define VFAT_IOCTL_READDIR_SHORT        _IOR('r', 2, struct linux_dirent [2])
123
124
125 #undef _syscall0
126 #undef _syscall1
127 #undef _syscall2
128 #undef _syscall3
129 #undef _syscall4
130 #undef _syscall5
131 #undef _syscall6
132
133 #define _syscall0(type,name)            \
134 static type name (void)                 \
135 {                                       \
136         return syscall(__NR_##name);    \
137 }
138
139 #define _syscall1(type,name,type1,arg1)         \
140 static type name (type1 arg1)                   \
141 {                                               \
142         return syscall(__NR_##name, arg1);      \
143 }
144
145 #define _syscall2(type,name,type1,arg1,type2,arg2)      \
146 static type name (type1 arg1,type2 arg2)                \
147 {                                                       \
148         return syscall(__NR_##name, arg1, arg2);        \
149 }
150
151 #define _syscall3(type,name,type1,arg1,type2,arg2,type3,arg3)   \
152 static type name (type1 arg1,type2 arg2,type3 arg3)             \
153 {                                                               \
154         return syscall(__NR_##name, arg1, arg2, arg3);          \
155 }
156
157 #define _syscall4(type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4)        \
158 static type name (type1 arg1,type2 arg2,type3 arg3,type4 arg4)                  \
159 {                                                                               \
160         return syscall(__NR_##name, arg1, arg2, arg3, arg4);                    \
161 }
162
163 #define _syscall5(type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4,        \
164                   type5,arg5)                                                   \
165 static type name (type1 arg1,type2 arg2,type3 arg3,type4 arg4,type5 arg5)       \
166 {                                                                               \
167         return syscall(__NR_##name, arg1, arg2, arg3, arg4, arg5);              \
168 }
169
170
171 #define _syscall6(type,name,type1,arg1,type2,arg2,type3,arg3,type4,arg4,        \
172                   type5,arg5,type6,arg6)                                        \
173 static type name (type1 arg1,type2 arg2,type3 arg3,type4 arg4,type5 arg5,       \
174                   type6 arg6)                                                   \
175 {                                                                               \
176         return syscall(__NR_##name, arg1, arg2, arg3, arg4, arg5, arg6);        \
177 }
178
179
180 #define __NR_sys_uname __NR_uname
181 #define __NR_sys_getcwd1 __NR_getcwd
182 #define __NR_sys_getdents __NR_getdents
183 #define __NR_sys_getdents64 __NR_getdents64
184 #define __NR_sys_getpriority __NR_getpriority
185 #define __NR_sys_rt_sigqueueinfo __NR_rt_sigqueueinfo
186 #define __NR_sys_syslog __NR_syslog
187 #define __NR_sys_tgkill __NR_tgkill
188 #define __NR_sys_tkill __NR_tkill
189 #define __NR_sys_futex __NR_futex
190 #define __NR_sys_inotify_init __NR_inotify_init
191 #define __NR_sys_inotify_add_watch __NR_inotify_add_watch
192 #define __NR_sys_inotify_rm_watch __NR_inotify_rm_watch
193
194 #if defined(__alpha__) || defined (__ia64__) || defined(__x86_64__) || \
195     defined(__s390x__)
196 #define __NR__llseek __NR_lseek
197 #endif
198
199 /* Newer kernel ports have llseek() instead of _llseek() */
200 #if defined(TARGET_NR_llseek) && !defined(TARGET_NR__llseek)
201 #define TARGET_NR__llseek TARGET_NR_llseek
202 #endif
203
204 #ifdef __NR_gettid
205 _syscall0(int, gettid)
206 #else
207 /* This is a replacement for the host gettid() and must return a host
208    errno. */
209 static int gettid(void) {
210     return -ENOSYS;
211 }
212 #endif
213 #ifdef __NR_getdents
214 _syscall3(int, sys_getdents, uint, fd, struct linux_dirent *, dirp, uint, count);
215 #endif
216 #if !defined(__NR_getdents) || \
217     (defined(TARGET_NR_getdents64) && defined(__NR_getdents64))
218 _syscall3(int, sys_getdents64, uint, fd, struct linux_dirent64 *, dirp, uint, count);
219 #endif
220 #if defined(TARGET_NR__llseek) && defined(__NR_llseek)
221 _syscall5(int, _llseek,  uint,  fd, ulong, hi, ulong, lo,
222           loff_t *, res, uint, wh);
223 #endif
224 _syscall3(int,sys_rt_sigqueueinfo,int,pid,int,sig,siginfo_t *,uinfo)
225 _syscall3(int,sys_syslog,int,type,char*,bufp,int,len)
226 #if defined(TARGET_NR_tgkill) && defined(__NR_tgkill)
227 _syscall3(int,sys_tgkill,int,tgid,int,pid,int,sig)
228 #endif
229 #if defined(TARGET_NR_tkill) && defined(__NR_tkill)
230 _syscall2(int,sys_tkill,int,tid,int,sig)
231 #endif
232 #ifdef __NR_exit_group
233 _syscall1(int,exit_group,int,error_code)
234 #endif
235 #if defined(TARGET_NR_set_tid_address) && defined(__NR_set_tid_address)
236 _syscall1(int,set_tid_address,int *,tidptr)
237 #endif
238 #if defined(TARGET_NR_futex) && defined(__NR_futex)
239 _syscall6(int,sys_futex,int *,uaddr,int,op,int,val,
240           const struct timespec *,timeout,int *,uaddr2,int,val3)
241 #endif
242 #define __NR_sys_sched_getaffinity __NR_sched_getaffinity
243 _syscall3(int, sys_sched_getaffinity, pid_t, pid, unsigned int, len,
244           unsigned long *, user_mask_ptr);
245 #define __NR_sys_sched_setaffinity __NR_sched_setaffinity
246 _syscall3(int, sys_sched_setaffinity, pid_t, pid, unsigned int, len,
247           unsigned long *, user_mask_ptr);
248 _syscall4(int, reboot, int, magic1, int, magic2, unsigned int, cmd,
249           void *, arg);
250 _syscall2(int, capget, struct __user_cap_header_struct *, header,
251           struct __user_cap_data_struct *, data);
252 _syscall2(int, capset, struct __user_cap_header_struct *, header,
253           struct __user_cap_data_struct *, data);
254
255 static bitmask_transtbl fcntl_flags_tbl[] = {
256   { TARGET_O_ACCMODE,   TARGET_O_WRONLY,    O_ACCMODE,   O_WRONLY,    },
257   { TARGET_O_ACCMODE,   TARGET_O_RDWR,      O_ACCMODE,   O_RDWR,      },
258   { TARGET_O_CREAT,     TARGET_O_CREAT,     O_CREAT,     O_CREAT,     },
259   { TARGET_O_EXCL,      TARGET_O_EXCL,      O_EXCL,      O_EXCL,      },
260   { TARGET_O_NOCTTY,    TARGET_O_NOCTTY,    O_NOCTTY,    O_NOCTTY,    },
261   { TARGET_O_TRUNC,     TARGET_O_TRUNC,     O_TRUNC,     O_TRUNC,     },
262   { TARGET_O_APPEND,    TARGET_O_APPEND,    O_APPEND,    O_APPEND,    },
263   { TARGET_O_NONBLOCK,  TARGET_O_NONBLOCK,  O_NONBLOCK,  O_NONBLOCK,  },
264   { TARGET_O_SYNC,      TARGET_O_DSYNC,     O_SYNC,      O_DSYNC,     },
265   { TARGET_O_SYNC,      TARGET_O_SYNC,      O_SYNC,      O_SYNC,      },
266   { TARGET_FASYNC,      TARGET_FASYNC,      FASYNC,      FASYNC,      },
267   { TARGET_O_DIRECTORY, TARGET_O_DIRECTORY, O_DIRECTORY, O_DIRECTORY, },
268   { TARGET_O_NOFOLLOW,  TARGET_O_NOFOLLOW,  O_NOFOLLOW,  O_NOFOLLOW,  },
269 #if defined(O_DIRECT)
270   { TARGET_O_DIRECT,    TARGET_O_DIRECT,    O_DIRECT,    O_DIRECT,    },
271 #endif
272 #if defined(O_NOATIME)
273   { TARGET_O_NOATIME,   TARGET_O_NOATIME,   O_NOATIME,   O_NOATIME    },
274 #endif
275 #if defined(O_CLOEXEC)
276   { TARGET_O_CLOEXEC,   TARGET_O_CLOEXEC,   O_CLOEXEC,   O_CLOEXEC    },
277 #endif
278 #if defined(O_PATH)
279   { TARGET_O_PATH,      TARGET_O_PATH,      O_PATH,      O_PATH       },
280 #endif
281   /* Don't terminate the list prematurely on 64-bit host+guest.  */
282 #if TARGET_O_LARGEFILE != 0 || O_LARGEFILE != 0
283   { TARGET_O_LARGEFILE, TARGET_O_LARGEFILE, O_LARGEFILE, O_LARGEFILE, },
284 #endif
285   { 0, 0, 0, 0 }
286 };
287
288 static int sys_getcwd1(char *buf, size_t size)
289 {
290   if (getcwd(buf, size) == NULL) {
291       /* getcwd() sets errno */
292       return (-1);
293   }
294   return strlen(buf)+1;
295 }
296
297 static int sys_openat(int dirfd, const char *pathname, int flags, mode_t mode)
298 {
299   /*
300    * open(2) has extra parameter 'mode' when called with
301    * flag O_CREAT.
302    */
303   if ((flags & O_CREAT) != 0) {
304       return (openat(dirfd, pathname, flags, mode));
305   }
306   return (openat(dirfd, pathname, flags));
307 }
308
309 #ifdef TARGET_NR_utimensat
310 #ifdef CONFIG_UTIMENSAT
311 static int sys_utimensat(int dirfd, const char *pathname,
312     const struct timespec times[2], int flags)
313 {
314     if (pathname == NULL)
315         return futimens(dirfd, times);
316     else
317         return utimensat(dirfd, pathname, times, flags);
318 }
319 #elif defined(__NR_utimensat)
320 #define __NR_sys_utimensat __NR_utimensat
321 _syscall4(int,sys_utimensat,int,dirfd,const char *,pathname,
322           const struct timespec *,tsp,int,flags)
323 #else
324 static int sys_utimensat(int dirfd, const char *pathname,
325                          const struct timespec times[2], int flags)
326 {
327     errno = ENOSYS;
328     return -1;
329 }
330 #endif
331 #endif /* TARGET_NR_utimensat */
332
333 #ifdef CONFIG_INOTIFY
334 #include <sys/inotify.h>
335
336 #if defined(TARGET_NR_inotify_init) && defined(__NR_inotify_init)
337 static int sys_inotify_init(void)
338 {
339   return (inotify_init());
340 }
341 #endif
342 #if defined(TARGET_NR_inotify_add_watch) && defined(__NR_inotify_add_watch)
343 static int sys_inotify_add_watch(int fd,const char *pathname, int32_t mask)
344 {
345   return (inotify_add_watch(fd, pathname, mask));
346 }
347 #endif
348 #if defined(TARGET_NR_inotify_rm_watch) && defined(__NR_inotify_rm_watch)
349 static int sys_inotify_rm_watch(int fd, int32_t wd)
350 {
351   return (inotify_rm_watch(fd, wd));
352 }
353 #endif
354 #ifdef CONFIG_INOTIFY1
355 #if defined(TARGET_NR_inotify_init1) && defined(__NR_inotify_init1)
356 static int sys_inotify_init1(int flags)
357 {
358   return (inotify_init1(flags));
359 }
360 #endif
361 #endif
362 #else
363 /* Userspace can usually survive runtime without inotify */
364 #undef TARGET_NR_inotify_init
365 #undef TARGET_NR_inotify_init1
366 #undef TARGET_NR_inotify_add_watch
367 #undef TARGET_NR_inotify_rm_watch
368 #endif /* CONFIG_INOTIFY  */
369
370 #if defined(TARGET_NR_ppoll)
371 #ifndef __NR_ppoll
372 # define __NR_ppoll -1
373 #endif
374 #define __NR_sys_ppoll __NR_ppoll
375 _syscall5(int, sys_ppoll, struct pollfd *, fds, nfds_t, nfds,
376           struct timespec *, timeout, const sigset_t *, sigmask,
377           size_t, sigsetsize)
378 #endif
379
380 #if defined(TARGET_NR_pselect6)
381 #ifndef __NR_pselect6
382 # define __NR_pselect6 -1
383 #endif
384 #define __NR_sys_pselect6 __NR_pselect6
385 _syscall6(int, sys_pselect6, int, nfds, fd_set *, readfds, fd_set *, writefds,
386           fd_set *, exceptfds, struct timespec *, timeout, void *, sig);
387 #endif
388
389 #if defined(TARGET_NR_prlimit64)
390 #ifndef __NR_prlimit64
391 # define __NR_prlimit64 -1
392 #endif
393 #define __NR_sys_prlimit64 __NR_prlimit64
394 /* The glibc rlimit structure may not be that used by the underlying syscall */
395 struct host_rlimit64 {
396     uint64_t rlim_cur;
397     uint64_t rlim_max;
398 };
399 _syscall4(int, sys_prlimit64, pid_t, pid, int, resource,
400           const struct host_rlimit64 *, new_limit,
401           struct host_rlimit64 *, old_limit)
402 #endif
403
404
405 #if defined(TARGET_NR_timer_create)
406 /* Maxiumum of 32 active POSIX timers allowed at any one time. */
407 static timer_t g_posix_timers[32] = { 0, } ;
408
409 static inline int next_free_host_timer(void)
410 {
411     int k ;
412     /* FIXME: Does finding the next free slot require a lock? */
413     for (k = 0; k < ARRAY_SIZE(g_posix_timers); k++) {
414         if (g_posix_timers[k] == 0) {
415             g_posix_timers[k] = (timer_t) 1;
416             return k;
417         }
418     }
419     return -1;
420 }
421 #endif
422
423 /* ARM EABI and MIPS expect 64bit types aligned even on pairs or registers */
424 #ifdef TARGET_ARM
425 static inline int regpairs_aligned(void *cpu_env) {
426     return ((((CPUARMState *)cpu_env)->eabi) == 1) ;
427 }
428 #elif defined(TARGET_MIPS)
429 static inline int regpairs_aligned(void *cpu_env) { return 1; }
430 #elif defined(TARGET_PPC) && !defined(TARGET_PPC64)
431 /* SysV AVI for PPC32 expects 64bit parameters to be passed on odd/even pairs
432  * of registers which translates to the same as ARM/MIPS, because we start with
433  * r3 as arg1 */
434 static inline int regpairs_aligned(void *cpu_env) { return 1; }
435 #else
436 static inline int regpairs_aligned(void *cpu_env) { return 0; }
437 #endif
438
439 #define ERRNO_TABLE_SIZE 1200
440
441 /* target_to_host_errno_table[] is initialized from
442  * host_to_target_errno_table[] in syscall_init(). */
443 static uint16_t target_to_host_errno_table[ERRNO_TABLE_SIZE] = {
444 };
445
446 /*
447  * This list is the union of errno values overridden in asm-<arch>/errno.h
448  * minus the errnos that are not actually generic to all archs.
449  */
450 static uint16_t host_to_target_errno_table[ERRNO_TABLE_SIZE] = {
451     [EIDRM]             = TARGET_EIDRM,
452     [ECHRNG]            = TARGET_ECHRNG,
453     [EL2NSYNC]          = TARGET_EL2NSYNC,
454     [EL3HLT]            = TARGET_EL3HLT,
455     [EL3RST]            = TARGET_EL3RST,
456     [ELNRNG]            = TARGET_ELNRNG,
457     [EUNATCH]           = TARGET_EUNATCH,
458     [ENOCSI]            = TARGET_ENOCSI,
459     [EL2HLT]            = TARGET_EL2HLT,
460     [EDEADLK]           = TARGET_EDEADLK,
461     [ENOLCK]            = TARGET_ENOLCK,
462     [EBADE]             = TARGET_EBADE,
463     [EBADR]             = TARGET_EBADR,
464     [EXFULL]            = TARGET_EXFULL,
465     [ENOANO]            = TARGET_ENOANO,
466     [EBADRQC]           = TARGET_EBADRQC,
467     [EBADSLT]           = TARGET_EBADSLT,
468     [EBFONT]            = TARGET_EBFONT,
469     [ENOSTR]            = TARGET_ENOSTR,
470     [ENODATA]           = TARGET_ENODATA,
471     [ETIME]             = TARGET_ETIME,
472     [ENOSR]             = TARGET_ENOSR,
473     [ENONET]            = TARGET_ENONET,
474     [ENOPKG]            = TARGET_ENOPKG,
475     [EREMOTE]           = TARGET_EREMOTE,
476     [ENOLINK]           = TARGET_ENOLINK,
477     [EADV]              = TARGET_EADV,
478     [ESRMNT]            = TARGET_ESRMNT,
479     [ECOMM]             = TARGET_ECOMM,
480     [EPROTO]            = TARGET_EPROTO,
481     [EDOTDOT]           = TARGET_EDOTDOT,
482     [EMULTIHOP]         = TARGET_EMULTIHOP,
483     [EBADMSG]           = TARGET_EBADMSG,
484     [ENAMETOOLONG]      = TARGET_ENAMETOOLONG,
485     [EOVERFLOW]         = TARGET_EOVERFLOW,
486     [ENOTUNIQ]          = TARGET_ENOTUNIQ,
487     [EBADFD]            = TARGET_EBADFD,
488     [EREMCHG]           = TARGET_EREMCHG,
489     [ELIBACC]           = TARGET_ELIBACC,
490     [ELIBBAD]           = TARGET_ELIBBAD,
491     [ELIBSCN]           = TARGET_ELIBSCN,
492     [ELIBMAX]           = TARGET_ELIBMAX,
493     [ELIBEXEC]          = TARGET_ELIBEXEC,
494     [EILSEQ]            = TARGET_EILSEQ,
495     [ENOSYS]            = TARGET_ENOSYS,
496     [ELOOP]             = TARGET_ELOOP,
497     [ERESTART]          = TARGET_ERESTART,
498     [ESTRPIPE]          = TARGET_ESTRPIPE,
499     [ENOTEMPTY]         = TARGET_ENOTEMPTY,
500     [EUSERS]            = TARGET_EUSERS,
501     [ENOTSOCK]          = TARGET_ENOTSOCK,
502     [EDESTADDRREQ]      = TARGET_EDESTADDRREQ,
503     [EMSGSIZE]          = TARGET_EMSGSIZE,
504     [EPROTOTYPE]        = TARGET_EPROTOTYPE,
505     [ENOPROTOOPT]       = TARGET_ENOPROTOOPT,
506     [EPROTONOSUPPORT]   = TARGET_EPROTONOSUPPORT,
507     [ESOCKTNOSUPPORT]   = TARGET_ESOCKTNOSUPPORT,
508     [EOPNOTSUPP]        = TARGET_EOPNOTSUPP,
509     [EPFNOSUPPORT]      = TARGET_EPFNOSUPPORT,
510     [EAFNOSUPPORT]      = TARGET_EAFNOSUPPORT,
511     [EADDRINUSE]        = TARGET_EADDRINUSE,
512     [EADDRNOTAVAIL]     = TARGET_EADDRNOTAVAIL,
513     [ENETDOWN]          = TARGET_ENETDOWN,
514     [ENETUNREACH]       = TARGET_ENETUNREACH,
515     [ENETRESET]         = TARGET_ENETRESET,
516     [ECONNABORTED]      = TARGET_ECONNABORTED,
517     [ECONNRESET]        = TARGET_ECONNRESET,
518     [ENOBUFS]           = TARGET_ENOBUFS,
519     [EISCONN]           = TARGET_EISCONN,
520     [ENOTCONN]          = TARGET_ENOTCONN,
521     [EUCLEAN]           = TARGET_EUCLEAN,
522     [ENOTNAM]           = TARGET_ENOTNAM,
523     [ENAVAIL]           = TARGET_ENAVAIL,
524     [EISNAM]            = TARGET_EISNAM,
525     [EREMOTEIO]         = TARGET_EREMOTEIO,
526     [ESHUTDOWN]         = TARGET_ESHUTDOWN,
527     [ETOOMANYREFS]      = TARGET_ETOOMANYREFS,
528     [ETIMEDOUT]         = TARGET_ETIMEDOUT,
529     [ECONNREFUSED]      = TARGET_ECONNREFUSED,
530     [EHOSTDOWN]         = TARGET_EHOSTDOWN,
531     [EHOSTUNREACH]      = TARGET_EHOSTUNREACH,
532     [EALREADY]          = TARGET_EALREADY,
533     [EINPROGRESS]       = TARGET_EINPROGRESS,
534     [ESTALE]            = TARGET_ESTALE,
535     [ECANCELED]         = TARGET_ECANCELED,
536     [ENOMEDIUM]         = TARGET_ENOMEDIUM,
537     [EMEDIUMTYPE]       = TARGET_EMEDIUMTYPE,
538 #ifdef ENOKEY
539     [ENOKEY]            = TARGET_ENOKEY,
540 #endif
541 #ifdef EKEYEXPIRED
542     [EKEYEXPIRED]       = TARGET_EKEYEXPIRED,
543 #endif
544 #ifdef EKEYREVOKED
545     [EKEYREVOKED]       = TARGET_EKEYREVOKED,
546 #endif
547 #ifdef EKEYREJECTED
548     [EKEYREJECTED]      = TARGET_EKEYREJECTED,
549 #endif
550 #ifdef EOWNERDEAD
551     [EOWNERDEAD]        = TARGET_EOWNERDEAD,
552 #endif
553 #ifdef ENOTRECOVERABLE
554     [ENOTRECOVERABLE]   = TARGET_ENOTRECOVERABLE,
555 #endif
556 };
557
558 static inline int host_to_target_errno(int err)
559 {
560     if(host_to_target_errno_table[err])
561         return host_to_target_errno_table[err];
562     return err;
563 }
564
565 static inline int target_to_host_errno(int err)
566 {
567     if (target_to_host_errno_table[err])
568         return target_to_host_errno_table[err];
569     return err;
570 }
571
572 static inline abi_long get_errno(abi_long ret)
573 {
574     if (ret == -1)
575         return -host_to_target_errno(errno);
576     else
577         return ret;
578 }
579
580 static inline int is_error(abi_long ret)
581 {
582     return (abi_ulong)ret >= (abi_ulong)(-4096);
583 }
584
585 char *target_strerror(int err)
586 {
587     if ((err >= ERRNO_TABLE_SIZE) || (err < 0)) {
588         return NULL;
589     }
590     return strerror(target_to_host_errno(err));
591 }
592
593 static inline int host_to_target_sock_type(int host_type)
594 {
595     int target_type;
596
597     switch (host_type & 0xf /* SOCK_TYPE_MASK */) {
598     case SOCK_DGRAM:
599         target_type = TARGET_SOCK_DGRAM;
600         break;
601     case SOCK_STREAM:
602         target_type = TARGET_SOCK_STREAM;
603         break;
604     default:
605         target_type = host_type & 0xf /* SOCK_TYPE_MASK */;
606         break;
607     }
608
609 #if defined(SOCK_CLOEXEC)
610     if (host_type & SOCK_CLOEXEC) {
611         target_type |= TARGET_SOCK_CLOEXEC;
612     }
613 #endif
614
615 #if defined(SOCK_NONBLOCK)
616     if (host_type & SOCK_NONBLOCK) {
617         target_type |= TARGET_SOCK_NONBLOCK;
618     }
619 #endif
620
621     return target_type;
622 }
623
624 static abi_ulong target_brk;
625 static abi_ulong target_original_brk;
626 static abi_ulong brk_page;
627
628 void target_set_brk(abi_ulong new_brk)
629 {
630     target_original_brk = target_brk = HOST_PAGE_ALIGN(new_brk);
631     brk_page = HOST_PAGE_ALIGN(target_brk);
632 }
633
634 //#define DEBUGF_BRK(message, args...) do { fprintf(stderr, (message), ## args); } while (0)
635 #define DEBUGF_BRK(message, args...)
636
637 /* do_brk() must return target values and target errnos. */
638 abi_long do_brk(abi_ulong new_brk)
639 {
640     abi_long mapped_addr;
641     int new_alloc_size;
642
643     DEBUGF_BRK("do_brk(" TARGET_ABI_FMT_lx ") -> ", new_brk);
644
645     if (!new_brk) {
646         DEBUGF_BRK(TARGET_ABI_FMT_lx " (!new_brk)\n", target_brk);
647         return target_brk;
648     }
649     if (new_brk < target_original_brk) {
650         DEBUGF_BRK(TARGET_ABI_FMT_lx " (new_brk < target_original_brk)\n",
651                    target_brk);
652         return target_brk;
653     }
654
655     /* If the new brk is less than the highest page reserved to the
656      * target heap allocation, set it and we're almost done...  */
657     if (new_brk <= brk_page) {
658         /* Heap contents are initialized to zero, as for anonymous
659          * mapped pages.  */
660         if (new_brk > target_brk) {
661             memset(g2h(target_brk), 0, new_brk - target_brk);
662         }
663         target_brk = new_brk;
664         DEBUGF_BRK(TARGET_ABI_FMT_lx " (new_brk <= brk_page)\n", target_brk);
665         return target_brk;
666     }
667
668     /* We need to allocate more memory after the brk... Note that
669      * we don't use MAP_FIXED because that will map over the top of
670      * any existing mapping (like the one with the host libc or qemu
671      * itself); instead we treat "mapped but at wrong address" as
672      * a failure and unmap again.
673      */
674     new_alloc_size = HOST_PAGE_ALIGN(new_brk - brk_page);
675     mapped_addr = get_errno(target_mmap(brk_page, new_alloc_size,
676                                         PROT_READ|PROT_WRITE,
677                                         MAP_ANON|MAP_PRIVATE, 0, 0));
678
679     if (mapped_addr == brk_page) {
680         /* Heap contents are initialized to zero, as for anonymous
681          * mapped pages.  Technically the new pages are already
682          * initialized to zero since they *are* anonymous mapped
683          * pages, however we have to take care with the contents that
684          * come from the remaining part of the previous page: it may
685          * contains garbage data due to a previous heap usage (grown
686          * then shrunken).  */
687         memset(g2h(target_brk), 0, brk_page - target_brk);
688
689         target_brk = new_brk;
690         brk_page = HOST_PAGE_ALIGN(target_brk);
691         DEBUGF_BRK(TARGET_ABI_FMT_lx " (mapped_addr == brk_page)\n",
692             target_brk);
693         return target_brk;
694     } else if (mapped_addr != -1) {
695         /* Mapped but at wrong address, meaning there wasn't actually
696          * enough space for this brk.
697          */
698         target_munmap(mapped_addr, new_alloc_size);
699         mapped_addr = -1;
700         DEBUGF_BRK(TARGET_ABI_FMT_lx " (mapped_addr != -1)\n", target_brk);
701     }
702     else {
703         DEBUGF_BRK(TARGET_ABI_FMT_lx " (otherwise)\n", target_brk);
704     }
705
706 #if defined(TARGET_ALPHA)
707     /* We (partially) emulate OSF/1 on Alpha, which requires we
708        return a proper errno, not an unchanged brk value.  */
709     return -TARGET_ENOMEM;
710 #endif
711     /* For everything else, return the previous break. */
712     return target_brk;
713 }
714
715 static inline abi_long copy_from_user_fdset(fd_set *fds,
716                                             abi_ulong target_fds_addr,
717                                             int n)
718 {
719     int i, nw, j, k;
720     abi_ulong b, *target_fds;
721
722     nw = (n + TARGET_ABI_BITS - 1) / TARGET_ABI_BITS;
723     if (!(target_fds = lock_user(VERIFY_READ,
724                                  target_fds_addr,
725                                  sizeof(abi_ulong) * nw,
726                                  1)))
727         return -TARGET_EFAULT;
728
729     FD_ZERO(fds);
730     k = 0;
731     for (i = 0; i < nw; i++) {
732         /* grab the abi_ulong */
733         __get_user(b, &target_fds[i]);
734         for (j = 0; j < TARGET_ABI_BITS; j++) {
735             /* check the bit inside the abi_ulong */
736             if ((b >> j) & 1)
737                 FD_SET(k, fds);
738             k++;
739         }
740     }
741
742     unlock_user(target_fds, target_fds_addr, 0);
743
744     return 0;
745 }
746
747 static inline abi_ulong copy_from_user_fdset_ptr(fd_set *fds, fd_set **fds_ptr,
748                                                  abi_ulong target_fds_addr,
749                                                  int n)
750 {
751     if (target_fds_addr) {
752         if (copy_from_user_fdset(fds, target_fds_addr, n))
753             return -TARGET_EFAULT;
754         *fds_ptr = fds;
755     } else {
756         *fds_ptr = NULL;
757     }
758     return 0;
759 }
760
761 static inline abi_long copy_to_user_fdset(abi_ulong target_fds_addr,
762                                           const fd_set *fds,
763                                           int n)
764 {
765     int i, nw, j, k;
766     abi_long v;
767     abi_ulong *target_fds;
768
769     nw = (n + TARGET_ABI_BITS - 1) / TARGET_ABI_BITS;
770     if (!(target_fds = lock_user(VERIFY_WRITE,
771                                  target_fds_addr,
772                                  sizeof(abi_ulong) * nw,
773                                  0)))
774         return -TARGET_EFAULT;
775
776     k = 0;
777     for (i = 0; i < nw; i++) {
778         v = 0;
779         for (j = 0; j < TARGET_ABI_BITS; j++) {
780             v |= ((abi_ulong)(FD_ISSET(k, fds) != 0) << j);
781             k++;
782         }
783         __put_user(v, &target_fds[i]);
784     }
785
786     unlock_user(target_fds, target_fds_addr, sizeof(abi_ulong) * nw);
787
788     return 0;
789 }
790
791 #if defined(__alpha__)
792 #define HOST_HZ 1024
793 #else
794 #define HOST_HZ 100
795 #endif
796
797 static inline abi_long host_to_target_clock_t(long ticks)
798 {
799 #if HOST_HZ == TARGET_HZ
800     return ticks;
801 #else
802     return ((int64_t)ticks * TARGET_HZ) / HOST_HZ;
803 #endif
804 }
805
806 static inline abi_long host_to_target_rusage(abi_ulong target_addr,
807                                              const struct rusage *rusage)
808 {
809     struct target_rusage *target_rusage;
810
811     if (!lock_user_struct(VERIFY_WRITE, target_rusage, target_addr, 0))
812         return -TARGET_EFAULT;
813     target_rusage->ru_utime.tv_sec = tswapal(rusage->ru_utime.tv_sec);
814     target_rusage->ru_utime.tv_usec = tswapal(rusage->ru_utime.tv_usec);
815     target_rusage->ru_stime.tv_sec = tswapal(rusage->ru_stime.tv_sec);
816     target_rusage->ru_stime.tv_usec = tswapal(rusage->ru_stime.tv_usec);
817     target_rusage->ru_maxrss = tswapal(rusage->ru_maxrss);
818     target_rusage->ru_ixrss = tswapal(rusage->ru_ixrss);
819     target_rusage->ru_idrss = tswapal(rusage->ru_idrss);
820     target_rusage->ru_isrss = tswapal(rusage->ru_isrss);
821     target_rusage->ru_minflt = tswapal(rusage->ru_minflt);
822     target_rusage->ru_majflt = tswapal(rusage->ru_majflt);
823     target_rusage->ru_nswap = tswapal(rusage->ru_nswap);
824     target_rusage->ru_inblock = tswapal(rusage->ru_inblock);
825     target_rusage->ru_oublock = tswapal(rusage->ru_oublock);
826     target_rusage->ru_msgsnd = tswapal(rusage->ru_msgsnd);
827     target_rusage->ru_msgrcv = tswapal(rusage->ru_msgrcv);
828     target_rusage->ru_nsignals = tswapal(rusage->ru_nsignals);
829     target_rusage->ru_nvcsw = tswapal(rusage->ru_nvcsw);
830     target_rusage->ru_nivcsw = tswapal(rusage->ru_nivcsw);
831     unlock_user_struct(target_rusage, target_addr, 1);
832
833     return 0;
834 }
835
836 static inline rlim_t target_to_host_rlim(abi_ulong target_rlim)
837 {
838     abi_ulong target_rlim_swap;
839     rlim_t result;
840     
841     target_rlim_swap = tswapal(target_rlim);
842     if (target_rlim_swap == TARGET_RLIM_INFINITY)
843         return RLIM_INFINITY;
844
845     result = target_rlim_swap;
846     if (target_rlim_swap != (rlim_t)result)
847         return RLIM_INFINITY;
848     
849     return result;
850 }
851
852 static inline abi_ulong host_to_target_rlim(rlim_t rlim)
853 {
854     abi_ulong target_rlim_swap;
855     abi_ulong result;
856     
857     if (rlim == RLIM_INFINITY || rlim != (abi_long)rlim)
858         target_rlim_swap = TARGET_RLIM_INFINITY;
859     else
860         target_rlim_swap = rlim;
861     result = tswapal(target_rlim_swap);
862     
863     return result;
864 }
865
866 static inline int target_to_host_resource(int code)
867 {
868     switch (code) {
869     case TARGET_RLIMIT_AS:
870         return RLIMIT_AS;
871     case TARGET_RLIMIT_CORE:
872         return RLIMIT_CORE;
873     case TARGET_RLIMIT_CPU:
874         return RLIMIT_CPU;
875     case TARGET_RLIMIT_DATA:
876         return RLIMIT_DATA;
877     case TARGET_RLIMIT_FSIZE:
878         return RLIMIT_FSIZE;
879     case TARGET_RLIMIT_LOCKS:
880         return RLIMIT_LOCKS;
881     case TARGET_RLIMIT_MEMLOCK:
882         return RLIMIT_MEMLOCK;
883     case TARGET_RLIMIT_MSGQUEUE:
884         return RLIMIT_MSGQUEUE;
885     case TARGET_RLIMIT_NICE:
886         return RLIMIT_NICE;
887     case TARGET_RLIMIT_NOFILE:
888         return RLIMIT_NOFILE;
889     case TARGET_RLIMIT_NPROC:
890         return RLIMIT_NPROC;
891     case TARGET_RLIMIT_RSS:
892         return RLIMIT_RSS;
893     case TARGET_RLIMIT_RTPRIO:
894         return RLIMIT_RTPRIO;
895     case TARGET_RLIMIT_SIGPENDING:
896         return RLIMIT_SIGPENDING;
897     case TARGET_RLIMIT_STACK:
898         return RLIMIT_STACK;
899     default:
900         return code;
901     }
902 }
903
904 static inline abi_long copy_from_user_timeval(struct timeval *tv,
905                                               abi_ulong target_tv_addr)
906 {
907     struct target_timeval *target_tv;
908
909     if (!lock_user_struct(VERIFY_READ, target_tv, target_tv_addr, 1))
910         return -TARGET_EFAULT;
911
912     __get_user(tv->tv_sec, &target_tv->tv_sec);
913     __get_user(tv->tv_usec, &target_tv->tv_usec);
914
915     unlock_user_struct(target_tv, target_tv_addr, 0);
916
917     return 0;
918 }
919
920 static inline abi_long copy_to_user_timeval(abi_ulong target_tv_addr,
921                                             const struct timeval *tv)
922 {
923     struct target_timeval *target_tv;
924
925     if (!lock_user_struct(VERIFY_WRITE, target_tv, target_tv_addr, 0))
926         return -TARGET_EFAULT;
927
928     __put_user(tv->tv_sec, &target_tv->tv_sec);
929     __put_user(tv->tv_usec, &target_tv->tv_usec);
930
931     unlock_user_struct(target_tv, target_tv_addr, 1);
932
933     return 0;
934 }
935
936 static inline abi_long copy_from_user_timezone(struct timezone *tz,
937                                                abi_ulong target_tz_addr)
938 {
939     struct target_timezone *target_tz;
940
941     if (!lock_user_struct(VERIFY_READ, target_tz, target_tz_addr, 1)) {
942         return -TARGET_EFAULT;
943     }
944
945     __get_user(tz->tz_minuteswest, &target_tz->tz_minuteswest);
946     __get_user(tz->tz_dsttime, &target_tz->tz_dsttime);
947
948     unlock_user_struct(target_tz, target_tz_addr, 0);
949
950     return 0;
951 }
952
953 #if defined(TARGET_NR_mq_open) && defined(__NR_mq_open)
954 #include <mqueue.h>
955
956 static inline abi_long copy_from_user_mq_attr(struct mq_attr *attr,
957                                               abi_ulong target_mq_attr_addr)
958 {
959     struct target_mq_attr *target_mq_attr;
960
961     if (!lock_user_struct(VERIFY_READ, target_mq_attr,
962                           target_mq_attr_addr, 1))
963         return -TARGET_EFAULT;
964
965     __get_user(attr->mq_flags, &target_mq_attr->mq_flags);
966     __get_user(attr->mq_maxmsg, &target_mq_attr->mq_maxmsg);
967     __get_user(attr->mq_msgsize, &target_mq_attr->mq_msgsize);
968     __get_user(attr->mq_curmsgs, &target_mq_attr->mq_curmsgs);
969
970     unlock_user_struct(target_mq_attr, target_mq_attr_addr, 0);
971
972     return 0;
973 }
974
975 static inline abi_long copy_to_user_mq_attr(abi_ulong target_mq_attr_addr,
976                                             const struct mq_attr *attr)
977 {
978     struct target_mq_attr *target_mq_attr;
979
980     if (!lock_user_struct(VERIFY_WRITE, target_mq_attr,
981                           target_mq_attr_addr, 0))
982         return -TARGET_EFAULT;
983
984     __put_user(attr->mq_flags, &target_mq_attr->mq_flags);
985     __put_user(attr->mq_maxmsg, &target_mq_attr->mq_maxmsg);
986     __put_user(attr->mq_msgsize, &target_mq_attr->mq_msgsize);
987     __put_user(attr->mq_curmsgs, &target_mq_attr->mq_curmsgs);
988
989     unlock_user_struct(target_mq_attr, target_mq_attr_addr, 1);
990
991     return 0;
992 }
993 #endif
994
995 #if defined(TARGET_NR_select) || defined(TARGET_NR__newselect)
996 /* do_select() must return target values and target errnos. */
997 static abi_long do_select(int n,
998                           abi_ulong rfd_addr, abi_ulong wfd_addr,
999                           abi_ulong efd_addr, abi_ulong target_tv_addr)
1000 {
1001     fd_set rfds, wfds, efds;
1002     fd_set *rfds_ptr, *wfds_ptr, *efds_ptr;
1003     struct timeval tv, *tv_ptr;
1004     abi_long ret;
1005
1006     ret = copy_from_user_fdset_ptr(&rfds, &rfds_ptr, rfd_addr, n);
1007     if (ret) {
1008         return ret;
1009     }
1010     ret = copy_from_user_fdset_ptr(&wfds, &wfds_ptr, wfd_addr, n);
1011     if (ret) {
1012         return ret;
1013     }
1014     ret = copy_from_user_fdset_ptr(&efds, &efds_ptr, efd_addr, n);
1015     if (ret) {
1016         return ret;
1017     }
1018
1019     if (target_tv_addr) {
1020         if (copy_from_user_timeval(&tv, target_tv_addr))
1021             return -TARGET_EFAULT;
1022         tv_ptr = &tv;
1023     } else {
1024         tv_ptr = NULL;
1025     }
1026
1027     ret = get_errno(select(n, rfds_ptr, wfds_ptr, efds_ptr, tv_ptr));
1028
1029     if (!is_error(ret)) {
1030         if (rfd_addr && copy_to_user_fdset(rfd_addr, &rfds, n))
1031             return -TARGET_EFAULT;
1032         if (wfd_addr && copy_to_user_fdset(wfd_addr, &wfds, n))
1033             return -TARGET_EFAULT;
1034         if (efd_addr && copy_to_user_fdset(efd_addr, &efds, n))
1035             return -TARGET_EFAULT;
1036
1037         if (target_tv_addr && copy_to_user_timeval(target_tv_addr, &tv))
1038             return -TARGET_EFAULT;
1039     }
1040
1041     return ret;
1042 }
1043 #endif
1044
1045 static abi_long do_pipe2(int host_pipe[], int flags)
1046 {
1047 #ifdef CONFIG_PIPE2
1048     return pipe2(host_pipe, flags);
1049 #else
1050     return -ENOSYS;
1051 #endif
1052 }
1053
1054 static abi_long do_pipe(void *cpu_env, abi_ulong pipedes,
1055                         int flags, int is_pipe2)
1056 {
1057     int host_pipe[2];
1058     abi_long ret;
1059     ret = flags ? do_pipe2(host_pipe, flags) : pipe(host_pipe);
1060
1061     if (is_error(ret))
1062         return get_errno(ret);
1063
1064     /* Several targets have special calling conventions for the original
1065        pipe syscall, but didn't replicate this into the pipe2 syscall.  */
1066     if (!is_pipe2) {
1067 #if defined(TARGET_ALPHA)
1068         ((CPUAlphaState *)cpu_env)->ir[IR_A4] = host_pipe[1];
1069         return host_pipe[0];
1070 #elif defined(TARGET_MIPS)
1071         ((CPUMIPSState*)cpu_env)->active_tc.gpr[3] = host_pipe[1];
1072         return host_pipe[0];
1073 #elif defined(TARGET_SH4)
1074         ((CPUSH4State*)cpu_env)->gregs[1] = host_pipe[1];
1075         return host_pipe[0];
1076 #elif defined(TARGET_SPARC)
1077         ((CPUSPARCState*)cpu_env)->regwptr[1] = host_pipe[1];
1078         return host_pipe[0];
1079 #endif
1080     }
1081
1082     if (put_user_s32(host_pipe[0], pipedes)
1083         || put_user_s32(host_pipe[1], pipedes + sizeof(host_pipe[0])))
1084         return -TARGET_EFAULT;
1085     return get_errno(ret);
1086 }
1087
1088 static inline abi_long target_to_host_ip_mreq(struct ip_mreqn *mreqn,
1089                                               abi_ulong target_addr,
1090                                               socklen_t len)
1091 {
1092     struct target_ip_mreqn *target_smreqn;
1093
1094     target_smreqn = lock_user(VERIFY_READ, target_addr, len, 1);
1095     if (!target_smreqn)
1096         return -TARGET_EFAULT;
1097     mreqn->imr_multiaddr.s_addr = target_smreqn->imr_multiaddr.s_addr;
1098     mreqn->imr_address.s_addr = target_smreqn->imr_address.s_addr;
1099     if (len == sizeof(struct target_ip_mreqn))
1100         mreqn->imr_ifindex = tswapal(target_smreqn->imr_ifindex);
1101     unlock_user(target_smreqn, target_addr, 0);
1102
1103     return 0;
1104 }
1105
1106 static inline abi_long target_to_host_sockaddr(struct sockaddr *addr,
1107                                                abi_ulong target_addr,
1108                                                socklen_t len)
1109 {
1110     const socklen_t unix_maxlen = sizeof (struct sockaddr_un);
1111     sa_family_t sa_family;
1112     struct target_sockaddr *target_saddr;
1113
1114     target_saddr = lock_user(VERIFY_READ, target_addr, len, 1);
1115     if (!target_saddr)
1116         return -TARGET_EFAULT;
1117
1118     sa_family = tswap16(target_saddr->sa_family);
1119
1120     /* Oops. The caller might send a incomplete sun_path; sun_path
1121      * must be terminated by \0 (see the manual page), but
1122      * unfortunately it is quite common to specify sockaddr_un
1123      * length as "strlen(x->sun_path)" while it should be
1124      * "strlen(...) + 1". We'll fix that here if needed.
1125      * Linux kernel has a similar feature.
1126      */
1127
1128     if (sa_family == AF_UNIX) {
1129         if (len < unix_maxlen && len > 0) {
1130             char *cp = (char*)target_saddr;
1131
1132             if ( cp[len-1] && !cp[len] )
1133                 len++;
1134         }
1135         if (len > unix_maxlen)
1136             len = unix_maxlen;
1137     }
1138
1139     memcpy(addr, target_saddr, len);
1140     addr->sa_family = sa_family;
1141     if (sa_family == AF_PACKET) {
1142         struct target_sockaddr_ll *lladdr;
1143
1144         lladdr = (struct target_sockaddr_ll *)addr;
1145         lladdr->sll_ifindex = tswap32(lladdr->sll_ifindex);
1146         lladdr->sll_hatype = tswap16(lladdr->sll_hatype);
1147     }
1148     unlock_user(target_saddr, target_addr, 0);
1149
1150     return 0;
1151 }
1152
1153 static inline abi_long host_to_target_sockaddr(abi_ulong target_addr,
1154                                                struct sockaddr *addr,
1155                                                socklen_t len)
1156 {
1157     struct target_sockaddr *target_saddr;
1158
1159     target_saddr = lock_user(VERIFY_WRITE, target_addr, len, 0);
1160     if (!target_saddr)
1161         return -TARGET_EFAULT;
1162     memcpy(target_saddr, addr, len);
1163     target_saddr->sa_family = tswap16(addr->sa_family);
1164     unlock_user(target_saddr, target_addr, len);
1165
1166     return 0;
1167 }
1168
1169 static inline abi_long target_to_host_cmsg(struct msghdr *msgh,
1170                                            struct target_msghdr *target_msgh)
1171 {
1172     struct cmsghdr *cmsg = CMSG_FIRSTHDR(msgh);
1173     abi_long msg_controllen;
1174     abi_ulong target_cmsg_addr;
1175     struct target_cmsghdr *target_cmsg;
1176     socklen_t space = 0;
1177     
1178     msg_controllen = tswapal(target_msgh->msg_controllen);
1179     if (msg_controllen < sizeof (struct target_cmsghdr)) 
1180         goto the_end;
1181     target_cmsg_addr = tswapal(target_msgh->msg_control);
1182     target_cmsg = lock_user(VERIFY_READ, target_cmsg_addr, msg_controllen, 1);
1183     if (!target_cmsg)
1184         return -TARGET_EFAULT;
1185
1186     while (cmsg && target_cmsg) {
1187         void *data = CMSG_DATA(cmsg);
1188         void *target_data = TARGET_CMSG_DATA(target_cmsg);
1189
1190         int len = tswapal(target_cmsg->cmsg_len)
1191                   - TARGET_CMSG_ALIGN(sizeof (struct target_cmsghdr));
1192
1193         space += CMSG_SPACE(len);
1194         if (space > msgh->msg_controllen) {
1195             space -= CMSG_SPACE(len);
1196             gemu_log("Host cmsg overflow\n");
1197             break;
1198         }
1199
1200         if (tswap32(target_cmsg->cmsg_level) == TARGET_SOL_SOCKET) {
1201             cmsg->cmsg_level = SOL_SOCKET;
1202         } else {
1203             cmsg->cmsg_level = tswap32(target_cmsg->cmsg_level);
1204         }
1205         cmsg->cmsg_type = tswap32(target_cmsg->cmsg_type);
1206         cmsg->cmsg_len = CMSG_LEN(len);
1207
1208         if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) {
1209             gemu_log("Unsupported ancillary data: %d/%d\n", cmsg->cmsg_level, cmsg->cmsg_type);
1210             memcpy(data, target_data, len);
1211         } else {
1212             int *fd = (int *)data;
1213             int *target_fd = (int *)target_data;
1214             int i, numfds = len / sizeof(int);
1215
1216             for (i = 0; i < numfds; i++)
1217                 fd[i] = tswap32(target_fd[i]);
1218         }
1219
1220         cmsg = CMSG_NXTHDR(msgh, cmsg);
1221         target_cmsg = TARGET_CMSG_NXTHDR(target_msgh, target_cmsg);
1222     }
1223     unlock_user(target_cmsg, target_cmsg_addr, 0);
1224  the_end:
1225     msgh->msg_controllen = space;
1226     return 0;
1227 }
1228
1229 static inline abi_long host_to_target_cmsg(struct target_msghdr *target_msgh,
1230                                            struct msghdr *msgh)
1231 {
1232     struct cmsghdr *cmsg = CMSG_FIRSTHDR(msgh);
1233     abi_long msg_controllen;
1234     abi_ulong target_cmsg_addr;
1235     struct target_cmsghdr *target_cmsg;
1236     socklen_t space = 0;
1237
1238     msg_controllen = tswapal(target_msgh->msg_controllen);
1239     if (msg_controllen < sizeof (struct target_cmsghdr)) 
1240         goto the_end;
1241     target_cmsg_addr = tswapal(target_msgh->msg_control);
1242     target_cmsg = lock_user(VERIFY_WRITE, target_cmsg_addr, msg_controllen, 0);
1243     if (!target_cmsg)
1244         return -TARGET_EFAULT;
1245
1246     while (cmsg && target_cmsg) {
1247         void *data = CMSG_DATA(cmsg);
1248         void *target_data = TARGET_CMSG_DATA(target_cmsg);
1249
1250         int len = cmsg->cmsg_len - CMSG_ALIGN(sizeof (struct cmsghdr));
1251
1252         space += TARGET_CMSG_SPACE(len);
1253         if (space > msg_controllen) {
1254             space -= TARGET_CMSG_SPACE(len);
1255             gemu_log("Target cmsg overflow\n");
1256             break;
1257         }
1258
1259         if (cmsg->cmsg_level == SOL_SOCKET) {
1260             target_cmsg->cmsg_level = tswap32(TARGET_SOL_SOCKET);
1261         } else {
1262             target_cmsg->cmsg_level = tswap32(cmsg->cmsg_level);
1263         }
1264         target_cmsg->cmsg_type = tswap32(cmsg->cmsg_type);
1265         target_cmsg->cmsg_len = tswapal(TARGET_CMSG_LEN(len));
1266
1267         switch (cmsg->cmsg_level) {
1268         case SOL_SOCKET:
1269             switch (cmsg->cmsg_type) {
1270             case SCM_RIGHTS:
1271             {
1272                 int *fd = (int *)data;
1273                 int *target_fd = (int *)target_data;
1274                 int i, numfds = len / sizeof(int);
1275
1276                 for (i = 0; i < numfds; i++)
1277                     target_fd[i] = tswap32(fd[i]);
1278                 break;
1279             }
1280             case SO_TIMESTAMP:
1281             {
1282                 struct timeval *tv = (struct timeval *)data;
1283                 struct target_timeval *target_tv =
1284                     (struct target_timeval *)target_data;
1285
1286                 if (len != sizeof(struct timeval))
1287                     goto unimplemented;
1288
1289                 /* copy struct timeval to target */
1290                 target_tv->tv_sec = tswapal(tv->tv_sec);
1291                 target_tv->tv_usec = tswapal(tv->tv_usec);
1292                 break;
1293             }
1294             case SCM_CREDENTIALS:
1295             {
1296                 struct ucred *cred = (struct ucred *)data;
1297                 struct target_ucred *target_cred =
1298                     (struct target_ucred *)target_data;
1299
1300                 __put_user(cred->pid, &target_cred->pid);
1301                 __put_user(cred->uid, &target_cred->uid);
1302                 __put_user(cred->gid, &target_cred->gid);
1303                 break;
1304             }
1305             default:
1306                 goto unimplemented;
1307             }
1308             break;
1309
1310         default:
1311         unimplemented:
1312             gemu_log("Unsupported ancillary data: %d/%d\n",
1313                                         cmsg->cmsg_level, cmsg->cmsg_type);
1314             memcpy(target_data, data, len);
1315         }
1316
1317         cmsg = CMSG_NXTHDR(msgh, cmsg);
1318         target_cmsg = TARGET_CMSG_NXTHDR(target_msgh, target_cmsg);
1319     }
1320     unlock_user(target_cmsg, target_cmsg_addr, space);
1321  the_end:
1322     target_msgh->msg_controllen = tswapal(space);
1323     return 0;
1324 }
1325
1326 /* do_setsockopt() Must return target values and target errnos. */
1327 static abi_long do_setsockopt(int sockfd, int level, int optname,
1328                               abi_ulong optval_addr, socklen_t optlen)
1329 {
1330     abi_long ret;
1331     int val;
1332     struct ip_mreqn *ip_mreq;
1333     struct ip_mreq_source *ip_mreq_source;
1334
1335     switch(level) {
1336     case SOL_TCP:
1337         /* TCP options all take an 'int' value.  */
1338         if (optlen < sizeof(uint32_t))
1339             return -TARGET_EINVAL;
1340
1341         if (get_user_u32(val, optval_addr))
1342             return -TARGET_EFAULT;
1343         ret = get_errno(setsockopt(sockfd, level, optname, &val, sizeof(val)));
1344         break;
1345     case SOL_IP:
1346         switch(optname) {
1347         case IP_TOS:
1348         case IP_TTL:
1349         case IP_HDRINCL:
1350         case IP_ROUTER_ALERT:
1351         case IP_RECVOPTS:
1352         case IP_RETOPTS:
1353         case IP_PKTINFO:
1354         case IP_MTU_DISCOVER:
1355         case IP_RECVERR:
1356         case IP_RECVTOS:
1357 #ifdef IP_FREEBIND
1358         case IP_FREEBIND:
1359 #endif
1360         case IP_MULTICAST_TTL:
1361         case IP_MULTICAST_LOOP:
1362             val = 0;
1363             if (optlen >= sizeof(uint32_t)) {
1364                 if (get_user_u32(val, optval_addr))
1365                     return -TARGET_EFAULT;
1366             } else if (optlen >= 1) {
1367                 if (get_user_u8(val, optval_addr))
1368                     return -TARGET_EFAULT;
1369             }
1370             ret = get_errno(setsockopt(sockfd, level, optname, &val, sizeof(val)));
1371             break;
1372         case IP_ADD_MEMBERSHIP:
1373         case IP_DROP_MEMBERSHIP:
1374             if (optlen < sizeof (struct target_ip_mreq) ||
1375                 optlen > sizeof (struct target_ip_mreqn))
1376                 return -TARGET_EINVAL;
1377
1378             ip_mreq = (struct ip_mreqn *) alloca(optlen);
1379             target_to_host_ip_mreq(ip_mreq, optval_addr, optlen);
1380             ret = get_errno(setsockopt(sockfd, level, optname, ip_mreq, optlen));
1381             break;
1382
1383         case IP_BLOCK_SOURCE:
1384         case IP_UNBLOCK_SOURCE:
1385         case IP_ADD_SOURCE_MEMBERSHIP:
1386         case IP_DROP_SOURCE_MEMBERSHIP:
1387             if (optlen != sizeof (struct target_ip_mreq_source))
1388                 return -TARGET_EINVAL;
1389
1390             ip_mreq_source = lock_user(VERIFY_READ, optval_addr, optlen, 1);
1391             ret = get_errno(setsockopt(sockfd, level, optname, ip_mreq_source, optlen));
1392             unlock_user (ip_mreq_source, optval_addr, 0);
1393             break;
1394
1395         default:
1396             goto unimplemented;
1397         }
1398         break;
1399     case SOL_IPV6:
1400         switch (optname) {
1401         case IPV6_MTU_DISCOVER:
1402         case IPV6_MTU:
1403         case IPV6_V6ONLY:
1404         case IPV6_RECVPKTINFO:
1405             val = 0;
1406             if (optlen < sizeof(uint32_t)) {
1407                 return -TARGET_EINVAL;
1408             }
1409             if (get_user_u32(val, optval_addr)) {
1410                 return -TARGET_EFAULT;
1411             }
1412             ret = get_errno(setsockopt(sockfd, level, optname,
1413                                        &val, sizeof(val)));
1414             break;
1415         default:
1416             goto unimplemented;
1417         }
1418         break;
1419     case SOL_RAW:
1420         switch (optname) {
1421         case ICMP_FILTER:
1422             /* struct icmp_filter takes an u32 value */
1423             if (optlen < sizeof(uint32_t)) {
1424                 return -TARGET_EINVAL;
1425             }
1426
1427             if (get_user_u32(val, optval_addr)) {
1428                 return -TARGET_EFAULT;
1429             }
1430             ret = get_errno(setsockopt(sockfd, level, optname,
1431                                        &val, sizeof(val)));
1432             break;
1433
1434         default:
1435             goto unimplemented;
1436         }
1437         break;
1438     case TARGET_SOL_SOCKET:
1439         switch (optname) {
1440         case TARGET_SO_RCVTIMEO:
1441         {
1442                 struct timeval tv;
1443
1444                 optname = SO_RCVTIMEO;
1445
1446 set_timeout:
1447                 if (optlen != sizeof(struct target_timeval)) {
1448                     return -TARGET_EINVAL;
1449                 }
1450
1451                 if (copy_from_user_timeval(&tv, optval_addr)) {
1452                     return -TARGET_EFAULT;
1453                 }
1454
1455                 ret = get_errno(setsockopt(sockfd, SOL_SOCKET, optname,
1456                                 &tv, sizeof(tv)));
1457                 return ret;
1458         }
1459         case TARGET_SO_SNDTIMEO:
1460                 optname = SO_SNDTIMEO;
1461                 goto set_timeout;
1462         case TARGET_SO_ATTACH_FILTER:
1463         {
1464                 struct target_sock_fprog *tfprog;
1465                 struct target_sock_filter *tfilter;
1466                 struct sock_fprog fprog;
1467                 struct sock_filter *filter;
1468                 int i;
1469
1470                 if (optlen != sizeof(*tfprog)) {
1471                     return -TARGET_EINVAL;
1472                 }
1473                 if (!lock_user_struct(VERIFY_READ, tfprog, optval_addr, 0)) {
1474                     return -TARGET_EFAULT;
1475                 }
1476                 if (!lock_user_struct(VERIFY_READ, tfilter,
1477                                       tswapal(tfprog->filter), 0)) {
1478                     unlock_user_struct(tfprog, optval_addr, 1);
1479                     return -TARGET_EFAULT;
1480                 }
1481
1482                 fprog.len = tswap16(tfprog->len);
1483                 filter = malloc(fprog.len * sizeof(*filter));
1484                 if (filter == NULL) {
1485                     unlock_user_struct(tfilter, tfprog->filter, 1);
1486                     unlock_user_struct(tfprog, optval_addr, 1);
1487                     return -TARGET_ENOMEM;
1488                 }
1489                 for (i = 0; i < fprog.len; i++) {
1490                     filter[i].code = tswap16(tfilter[i].code);
1491                     filter[i].jt = tfilter[i].jt;
1492                     filter[i].jf = tfilter[i].jf;
1493                     filter[i].k = tswap32(tfilter[i].k);
1494                 }
1495                 fprog.filter = filter;
1496
1497                 ret = get_errno(setsockopt(sockfd, SOL_SOCKET,
1498                                 SO_ATTACH_FILTER, &fprog, sizeof(fprog)));
1499                 free(filter);
1500
1501                 unlock_user_struct(tfilter, tfprog->filter, 1);
1502                 unlock_user_struct(tfprog, optval_addr, 1);
1503                 return ret;
1504         }
1505         case TARGET_SO_BINDTODEVICE:
1506         {
1507                 char *dev_ifname, *addr_ifname;
1508
1509                 if (optlen > IFNAMSIZ - 1) {
1510                     optlen = IFNAMSIZ - 1;
1511                 }
1512                 dev_ifname = lock_user(VERIFY_READ, optval_addr, optlen, 1);
1513                 if (!dev_ifname) {
1514                     return -TARGET_EFAULT;
1515                 }
1516                 optname = SO_BINDTODEVICE;
1517                 addr_ifname = alloca(IFNAMSIZ);
1518                 memcpy(addr_ifname, dev_ifname, optlen);
1519                 addr_ifname[optlen] = 0;
1520                 ret = get_errno(setsockopt(sockfd, level, optname, addr_ifname, optlen));
1521                 unlock_user (dev_ifname, optval_addr, 0);
1522                 return ret;
1523         }
1524             /* Options with 'int' argument.  */
1525         case TARGET_SO_DEBUG:
1526                 optname = SO_DEBUG;
1527                 break;
1528         case TARGET_SO_REUSEADDR:
1529                 optname = SO_REUSEADDR;
1530                 break;
1531         case TARGET_SO_TYPE:
1532                 optname = SO_TYPE;
1533                 break;
1534         case TARGET_SO_ERROR:
1535                 optname = SO_ERROR;
1536                 break;
1537         case TARGET_SO_DONTROUTE:
1538                 optname = SO_DONTROUTE;
1539                 break;
1540         case TARGET_SO_BROADCAST:
1541                 optname = SO_BROADCAST;
1542                 break;
1543         case TARGET_SO_SNDBUF:
1544                 optname = SO_SNDBUF;
1545                 break;
1546         case TARGET_SO_SNDBUFFORCE:
1547                 optname = SO_SNDBUFFORCE;
1548                 break;
1549         case TARGET_SO_RCVBUF:
1550                 optname = SO_RCVBUF;
1551                 break;
1552         case TARGET_SO_RCVBUFFORCE:
1553                 optname = SO_RCVBUFFORCE;
1554                 break;
1555         case TARGET_SO_KEEPALIVE:
1556                 optname = SO_KEEPALIVE;
1557                 break;
1558         case TARGET_SO_OOBINLINE:
1559                 optname = SO_OOBINLINE;
1560                 break;
1561         case TARGET_SO_NO_CHECK:
1562                 optname = SO_NO_CHECK;
1563                 break;
1564         case TARGET_SO_PRIORITY:
1565                 optname = SO_PRIORITY;
1566                 break;
1567 #ifdef SO_BSDCOMPAT
1568         case TARGET_SO_BSDCOMPAT:
1569                 optname = SO_BSDCOMPAT;
1570                 break;
1571 #endif
1572         case TARGET_SO_PASSCRED:
1573                 optname = SO_PASSCRED;
1574                 break;
1575         case TARGET_SO_PASSSEC:
1576                 optname = SO_PASSSEC;
1577                 break;
1578         case TARGET_SO_TIMESTAMP:
1579                 optname = SO_TIMESTAMP;
1580                 break;
1581         case TARGET_SO_RCVLOWAT:
1582                 optname = SO_RCVLOWAT;
1583                 break;
1584             break;
1585         default:
1586             goto unimplemented;
1587         }
1588         if (optlen < sizeof(uint32_t))
1589             return -TARGET_EINVAL;
1590
1591         if (get_user_u32(val, optval_addr))
1592             return -TARGET_EFAULT;
1593         ret = get_errno(setsockopt(sockfd, SOL_SOCKET, optname, &val, sizeof(val)));
1594         break;
1595     default:
1596     unimplemented:
1597         gemu_log("Unsupported setsockopt level=%d optname=%d\n", level, optname);
1598         ret = -TARGET_ENOPROTOOPT;
1599     }
1600     return ret;
1601 }
1602
1603 /* do_getsockopt() Must return target values and target errnos. */
1604 static abi_long do_getsockopt(int sockfd, int level, int optname,
1605                               abi_ulong optval_addr, abi_ulong optlen)
1606 {
1607     abi_long ret;
1608     int len, val;
1609     socklen_t lv;
1610
1611     switch(level) {
1612     case TARGET_SOL_SOCKET:
1613         level = SOL_SOCKET;
1614         switch (optname) {
1615         /* These don't just return a single integer */
1616         case TARGET_SO_LINGER:
1617         case TARGET_SO_RCVTIMEO:
1618         case TARGET_SO_SNDTIMEO:
1619         case TARGET_SO_PEERNAME:
1620             goto unimplemented;
1621         case TARGET_SO_PEERCRED: {
1622             struct ucred cr;
1623             socklen_t crlen;
1624             struct target_ucred *tcr;
1625
1626             if (get_user_u32(len, optlen)) {
1627                 return -TARGET_EFAULT;
1628             }
1629             if (len < 0) {
1630                 return -TARGET_EINVAL;
1631             }
1632
1633             crlen = sizeof(cr);
1634             ret = get_errno(getsockopt(sockfd, level, SO_PEERCRED,
1635                                        &cr, &crlen));
1636             if (ret < 0) {
1637                 return ret;
1638             }
1639             if (len > crlen) {
1640                 len = crlen;
1641             }
1642             if (!lock_user_struct(VERIFY_WRITE, tcr, optval_addr, 0)) {
1643                 return -TARGET_EFAULT;
1644             }
1645             __put_user(cr.pid, &tcr->pid);
1646             __put_user(cr.uid, &tcr->uid);
1647             __put_user(cr.gid, &tcr->gid);
1648             unlock_user_struct(tcr, optval_addr, 1);
1649             if (put_user_u32(len, optlen)) {
1650                 return -TARGET_EFAULT;
1651             }
1652             break;
1653         }
1654         /* Options with 'int' argument.  */
1655         case TARGET_SO_DEBUG:
1656             optname = SO_DEBUG;
1657             goto int_case;
1658         case TARGET_SO_REUSEADDR:
1659             optname = SO_REUSEADDR;
1660             goto int_case;
1661         case TARGET_SO_TYPE:
1662             optname = SO_TYPE;
1663             goto int_case;
1664         case TARGET_SO_ERROR:
1665             optname = SO_ERROR;
1666             goto int_case;
1667         case TARGET_SO_DONTROUTE:
1668             optname = SO_DONTROUTE;
1669             goto int_case;
1670         case TARGET_SO_BROADCAST:
1671             optname = SO_BROADCAST;
1672             goto int_case;
1673         case TARGET_SO_SNDBUF:
1674             optname = SO_SNDBUF;
1675             goto int_case;
1676         case TARGET_SO_RCVBUF:
1677             optname = SO_RCVBUF;
1678             goto int_case;
1679         case TARGET_SO_KEEPALIVE:
1680             optname = SO_KEEPALIVE;
1681             goto int_case;
1682         case TARGET_SO_OOBINLINE:
1683             optname = SO_OOBINLINE;
1684             goto int_case;
1685         case TARGET_SO_NO_CHECK:
1686             optname = SO_NO_CHECK;
1687             goto int_case;
1688         case TARGET_SO_PRIORITY:
1689             optname = SO_PRIORITY;
1690             goto int_case;
1691 #ifdef SO_BSDCOMPAT
1692         case TARGET_SO_BSDCOMPAT:
1693             optname = SO_BSDCOMPAT;
1694             goto int_case;
1695 #endif
1696         case TARGET_SO_PASSCRED:
1697             optname = SO_PASSCRED;
1698             goto int_case;
1699         case TARGET_SO_TIMESTAMP:
1700             optname = SO_TIMESTAMP;
1701             goto int_case;
1702         case TARGET_SO_RCVLOWAT:
1703             optname = SO_RCVLOWAT;
1704             goto int_case;
1705         case TARGET_SO_ACCEPTCONN:
1706             optname = SO_ACCEPTCONN;
1707             goto int_case;
1708         default:
1709             goto int_case;
1710         }
1711         break;
1712     case SOL_TCP:
1713         /* TCP options all take an 'int' value.  */
1714     int_case:
1715         if (get_user_u32(len, optlen))
1716             return -TARGET_EFAULT;
1717         if (len < 0)
1718             return -TARGET_EINVAL;
1719         lv = sizeof(lv);
1720         ret = get_errno(getsockopt(sockfd, level, optname, &val, &lv));
1721         if (ret < 0)
1722             return ret;
1723         if (optname == SO_TYPE) {
1724             val = host_to_target_sock_type(val);
1725         }
1726         if (len > lv)
1727             len = lv;
1728         if (len == 4) {
1729             if (put_user_u32(val, optval_addr))
1730                 return -TARGET_EFAULT;
1731         } else {
1732             if (put_user_u8(val, optval_addr))
1733                 return -TARGET_EFAULT;
1734         }
1735         if (put_user_u32(len, optlen))
1736             return -TARGET_EFAULT;
1737         break;
1738     case SOL_IP:
1739         switch(optname) {
1740         case IP_TOS:
1741         case IP_TTL:
1742         case IP_HDRINCL:
1743         case IP_ROUTER_ALERT:
1744         case IP_RECVOPTS:
1745         case IP_RETOPTS:
1746         case IP_PKTINFO:
1747         case IP_MTU_DISCOVER:
1748         case IP_RECVERR:
1749         case IP_RECVTOS:
1750 #ifdef IP_FREEBIND
1751         case IP_FREEBIND:
1752 #endif
1753         case IP_MULTICAST_TTL:
1754         case IP_MULTICAST_LOOP:
1755             if (get_user_u32(len, optlen))
1756                 return -TARGET_EFAULT;
1757             if (len < 0)
1758                 return -TARGET_EINVAL;
1759             lv = sizeof(lv);
1760             ret = get_errno(getsockopt(sockfd, level, optname, &val, &lv));
1761             if (ret < 0)
1762                 return ret;
1763             if (len < sizeof(int) && len > 0 && val >= 0 && val < 255) {
1764                 len = 1;
1765                 if (put_user_u32(len, optlen)
1766                     || put_user_u8(val, optval_addr))
1767                     return -TARGET_EFAULT;
1768             } else {
1769                 if (len > sizeof(int))
1770                     len = sizeof(int);
1771                 if (put_user_u32(len, optlen)
1772                     || put_user_u32(val, optval_addr))
1773                     return -TARGET_EFAULT;
1774             }
1775             break;
1776         default:
1777             ret = -TARGET_ENOPROTOOPT;
1778             break;
1779         }
1780         break;
1781     default:
1782     unimplemented:
1783         gemu_log("getsockopt level=%d optname=%d not yet supported\n",
1784                  level, optname);
1785         ret = -TARGET_EOPNOTSUPP;
1786         break;
1787     }
1788     return ret;
1789 }
1790
1791 static struct iovec *lock_iovec(int type, abi_ulong target_addr,
1792                                 int count, int copy)
1793 {
1794     struct target_iovec *target_vec;
1795     struct iovec *vec;
1796     abi_ulong total_len, max_len;
1797     int i;
1798     int err = 0;
1799
1800     if (count == 0) {
1801         errno = 0;
1802         return NULL;
1803     }
1804     if (count < 0 || count > IOV_MAX) {
1805         errno = EINVAL;
1806         return NULL;
1807     }
1808
1809     vec = calloc(count, sizeof(struct iovec));
1810     if (vec == NULL) {
1811         errno = ENOMEM;
1812         return NULL;
1813     }
1814
1815     target_vec = lock_user(VERIFY_READ, target_addr,
1816                            count * sizeof(struct target_iovec), 1);
1817     if (target_vec == NULL) {
1818         err = EFAULT;
1819         goto fail2;
1820     }
1821
1822     /* ??? If host page size > target page size, this will result in a
1823        value larger than what we can actually support.  */
1824     max_len = 0x7fffffff & TARGET_PAGE_MASK;
1825     total_len = 0;
1826
1827     for (i = 0; i < count; i++) {
1828         abi_ulong base = tswapal(target_vec[i].iov_base);
1829         abi_long len = tswapal(target_vec[i].iov_len);
1830
1831         if (len < 0) {
1832             err = EINVAL;
1833             goto fail;
1834         } else if (len == 0) {
1835             /* Zero length pointer is ignored.  */
1836             vec[i].iov_base = 0;
1837         } else {
1838             vec[i].iov_base = lock_user(type, base, len, copy);
1839             if (!vec[i].iov_base) {
1840                 err = EFAULT;
1841                 goto fail;
1842             }
1843             if (len > max_len - total_len) {
1844                 len = max_len - total_len;
1845             }
1846         }
1847         vec[i].iov_len = len;
1848         total_len += len;
1849     }
1850
1851     unlock_user(target_vec, target_addr, 0);
1852     return vec;
1853
1854  fail:
1855     unlock_user(target_vec, target_addr, 0);
1856  fail2:
1857     free(vec);
1858     errno = err;
1859     return NULL;
1860 }
1861
1862 static void unlock_iovec(struct iovec *vec, abi_ulong target_addr,
1863                          int count, int copy)
1864 {
1865     struct target_iovec *target_vec;
1866     int i;
1867
1868     target_vec = lock_user(VERIFY_READ, target_addr,
1869                            count * sizeof(struct target_iovec), 1);
1870     if (target_vec) {
1871         for (i = 0; i < count; i++) {
1872             abi_ulong base = tswapal(target_vec[i].iov_base);
1873             abi_long len = tswapal(target_vec[i].iov_base);
1874             if (len < 0) {
1875                 break;
1876             }
1877             unlock_user(vec[i].iov_base, base, copy ? vec[i].iov_len : 0);
1878         }
1879         unlock_user(target_vec, target_addr, 0);
1880     }
1881
1882     free(vec);
1883 }
1884
1885 static inline int target_to_host_sock_type(int *type)
1886 {
1887     int host_type = 0;
1888     int target_type = *type;
1889
1890     switch (target_type & TARGET_SOCK_TYPE_MASK) {
1891     case TARGET_SOCK_DGRAM:
1892         host_type = SOCK_DGRAM;
1893         break;
1894     case TARGET_SOCK_STREAM:
1895         host_type = SOCK_STREAM;
1896         break;
1897     default:
1898         host_type = target_type & TARGET_SOCK_TYPE_MASK;
1899         break;
1900     }
1901     if (target_type & TARGET_SOCK_CLOEXEC) {
1902 #if defined(SOCK_CLOEXEC)
1903         host_type |= SOCK_CLOEXEC;
1904 #else
1905         return -TARGET_EINVAL;
1906 #endif
1907     }
1908     if (target_type & TARGET_SOCK_NONBLOCK) {
1909 #if defined(SOCK_NONBLOCK)
1910         host_type |= SOCK_NONBLOCK;
1911 #elif !defined(O_NONBLOCK)
1912         return -TARGET_EINVAL;
1913 #endif
1914     }
1915     *type = host_type;
1916     return 0;
1917 }
1918
1919 /* Try to emulate socket type flags after socket creation.  */
1920 static int sock_flags_fixup(int fd, int target_type)
1921 {
1922 #if !defined(SOCK_NONBLOCK) && defined(O_NONBLOCK)
1923     if (target_type & TARGET_SOCK_NONBLOCK) {
1924         int flags = fcntl(fd, F_GETFL);
1925         if (fcntl(fd, F_SETFL, O_NONBLOCK | flags) == -1) {
1926             close(fd);
1927             return -TARGET_EINVAL;
1928         }
1929     }
1930 #endif
1931     return fd;
1932 }
1933
1934 /* do_socket() Must return target values and target errnos. */
1935 static abi_long do_socket(int domain, int type, int protocol)
1936 {
1937     int target_type = type;
1938     int ret;
1939
1940     ret = target_to_host_sock_type(&type);
1941     if (ret) {
1942         return ret;
1943     }
1944
1945     if (domain == PF_NETLINK)
1946         return -TARGET_EAFNOSUPPORT;
1947     ret = get_errno(socket(domain, type, protocol));
1948     if (ret >= 0) {
1949         ret = sock_flags_fixup(ret, target_type);
1950     }
1951     return ret;
1952 }
1953
1954 /* do_bind() Must return target values and target errnos. */
1955 static abi_long do_bind(int sockfd, abi_ulong target_addr,
1956                         socklen_t addrlen)
1957 {
1958     void *addr;
1959     abi_long ret;
1960
1961     if ((int)addrlen < 0) {
1962         return -TARGET_EINVAL;
1963     }
1964
1965     addr = alloca(addrlen+1);
1966
1967     ret = target_to_host_sockaddr(addr, target_addr, addrlen);
1968     if (ret)
1969         return ret;
1970
1971     return get_errno(bind(sockfd, addr, addrlen));
1972 }
1973
1974 /* do_connect() Must return target values and target errnos. */
1975 static abi_long do_connect(int sockfd, abi_ulong target_addr,
1976                            socklen_t addrlen)
1977 {
1978     void *addr;
1979     abi_long ret;
1980
1981     if ((int)addrlen < 0) {
1982         return -TARGET_EINVAL;
1983     }
1984
1985     addr = alloca(addrlen+1);
1986
1987     ret = target_to_host_sockaddr(addr, target_addr, addrlen);
1988     if (ret)
1989         return ret;
1990
1991     return get_errno(connect(sockfd, addr, addrlen));
1992 }
1993
1994 /* do_sendrecvmsg_locked() Must return target values and target errnos. */
1995 static abi_long do_sendrecvmsg_locked(int fd, struct target_msghdr *msgp,
1996                                       int flags, int send)
1997 {
1998     abi_long ret, len;
1999     struct msghdr msg;
2000     int count;
2001     struct iovec *vec;
2002     abi_ulong target_vec;
2003
2004     if (msgp->msg_name) {
2005         msg.msg_namelen = tswap32(msgp->msg_namelen);
2006         msg.msg_name = alloca(msg.msg_namelen+1);
2007         ret = target_to_host_sockaddr(msg.msg_name, tswapal(msgp->msg_name),
2008                                 msg.msg_namelen);
2009         if (ret) {
2010             goto out2;
2011         }
2012     } else {
2013         msg.msg_name = NULL;
2014         msg.msg_namelen = 0;
2015     }
2016     msg.msg_controllen = 2 * tswapal(msgp->msg_controllen);
2017     msg.msg_control = alloca(msg.msg_controllen);
2018     msg.msg_flags = tswap32(msgp->msg_flags);
2019
2020     count = tswapal(msgp->msg_iovlen);
2021     target_vec = tswapal(msgp->msg_iov);
2022     vec = lock_iovec(send ? VERIFY_READ : VERIFY_WRITE,
2023                      target_vec, count, send);
2024     if (vec == NULL) {
2025         ret = -host_to_target_errno(errno);
2026         goto out2;
2027     }
2028     msg.msg_iovlen = count;
2029     msg.msg_iov = vec;
2030
2031     if (send) {
2032         ret = target_to_host_cmsg(&msg, msgp);
2033         if (ret == 0)
2034             ret = get_errno(sendmsg(fd, &msg, flags));
2035     } else {
2036         ret = get_errno(recvmsg(fd, &msg, flags));
2037         if (!is_error(ret)) {
2038             len = ret;
2039             ret = host_to_target_cmsg(msgp, &msg);
2040             if (!is_error(ret)) {
2041                 msgp->msg_namelen = tswap32(msg.msg_namelen);
2042                 if (msg.msg_name != NULL) {
2043                     ret = host_to_target_sockaddr(tswapal(msgp->msg_name),
2044                                     msg.msg_name, msg.msg_namelen);
2045                     if (ret) {
2046                         goto out;
2047                     }
2048                 }
2049
2050                 ret = len;
2051             }
2052         }
2053     }
2054
2055 out:
2056     unlock_iovec(vec, target_vec, count, !send);
2057 out2:
2058     return ret;
2059 }
2060
2061 static abi_long do_sendrecvmsg(int fd, abi_ulong target_msg,
2062                                int flags, int send)
2063 {
2064     abi_long ret;
2065     struct target_msghdr *msgp;
2066
2067     if (!lock_user_struct(send ? VERIFY_READ : VERIFY_WRITE,
2068                           msgp,
2069                           target_msg,
2070                           send ? 1 : 0)) {
2071         return -TARGET_EFAULT;
2072     }
2073     ret = do_sendrecvmsg_locked(fd, msgp, flags, send);
2074     unlock_user_struct(msgp, target_msg, send ? 0 : 1);
2075     return ret;
2076 }
2077
2078 #ifdef TARGET_NR_sendmmsg
2079 /* We don't rely on the C library to have sendmmsg/recvmmsg support,
2080  * so it might not have this *mmsg-specific flag either.
2081  */
2082 #ifndef MSG_WAITFORONE
2083 #define MSG_WAITFORONE 0x10000
2084 #endif
2085
2086 static abi_long do_sendrecvmmsg(int fd, abi_ulong target_msgvec,
2087                                 unsigned int vlen, unsigned int flags,
2088                                 int send)
2089 {
2090     struct target_mmsghdr *mmsgp;
2091     abi_long ret = 0;
2092     int i;
2093
2094     if (vlen > UIO_MAXIOV) {
2095         vlen = UIO_MAXIOV;
2096     }
2097
2098     mmsgp = lock_user(VERIFY_WRITE, target_msgvec, sizeof(*mmsgp) * vlen, 1);
2099     if (!mmsgp) {
2100         return -TARGET_EFAULT;
2101     }
2102
2103     for (i = 0; i < vlen; i++) {
2104         ret = do_sendrecvmsg_locked(fd, &mmsgp[i].msg_hdr, flags, send);
2105         if (is_error(ret)) {
2106             break;
2107         }
2108         mmsgp[i].msg_len = tswap32(ret);
2109         /* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */
2110         if (flags & MSG_WAITFORONE) {
2111             flags |= MSG_DONTWAIT;
2112         }
2113     }
2114
2115     unlock_user(mmsgp, target_msgvec, sizeof(*mmsgp) * i);
2116
2117     /* Return number of datagrams sent if we sent any at all;
2118      * otherwise return the error.
2119      */
2120     if (i) {
2121         return i;
2122     }
2123     return ret;
2124 }
2125 #endif
2126
2127 /* If we don't have a system accept4() then just call accept.
2128  * The callsites to do_accept4() will ensure that they don't
2129  * pass a non-zero flags argument in this config.
2130  */
2131 #ifndef CONFIG_ACCEPT4
2132 static inline int accept4(int sockfd, struct sockaddr *addr,
2133                           socklen_t *addrlen, int flags)
2134 {
2135     assert(flags == 0);
2136     return accept(sockfd, addr, addrlen);
2137 }
2138 #endif
2139
2140 /* do_accept4() Must return target values and target errnos. */
2141 static abi_long do_accept4(int fd, abi_ulong target_addr,
2142                            abi_ulong target_addrlen_addr, int flags)
2143 {
2144     socklen_t addrlen;
2145     void *addr;
2146     abi_long ret;
2147     int host_flags;
2148
2149     host_flags = target_to_host_bitmask(flags, fcntl_flags_tbl);
2150
2151     if (target_addr == 0) {
2152         return get_errno(accept4(fd, NULL, NULL, host_flags));
2153     }
2154
2155     /* linux returns EINVAL if addrlen pointer is invalid */
2156     if (get_user_u32(addrlen, target_addrlen_addr))
2157         return -TARGET_EINVAL;
2158
2159     if ((int)addrlen < 0) {
2160         return -TARGET_EINVAL;
2161     }
2162
2163     if (!access_ok(VERIFY_WRITE, target_addr, addrlen))
2164         return -TARGET_EINVAL;
2165
2166     addr = alloca(addrlen);
2167
2168     ret = get_errno(accept4(fd, addr, &addrlen, host_flags));
2169     if (!is_error(ret)) {
2170         host_to_target_sockaddr(target_addr, addr, addrlen);
2171         if (put_user_u32(addrlen, target_addrlen_addr))
2172             ret = -TARGET_EFAULT;
2173     }
2174     return ret;
2175 }
2176
2177 /* do_getpeername() Must return target values and target errnos. */
2178 static abi_long do_getpeername(int fd, abi_ulong target_addr,
2179                                abi_ulong target_addrlen_addr)
2180 {
2181     socklen_t addrlen;
2182     void *addr;
2183     abi_long ret;
2184
2185     if (get_user_u32(addrlen, target_addrlen_addr))
2186         return -TARGET_EFAULT;
2187
2188     if ((int)addrlen < 0) {
2189         return -TARGET_EINVAL;
2190     }
2191
2192     if (!access_ok(VERIFY_WRITE, target_addr, addrlen))
2193         return -TARGET_EFAULT;
2194
2195     addr = alloca(addrlen);
2196
2197     ret = get_errno(getpeername(fd, addr, &addrlen));
2198     if (!is_error(ret)) {
2199         host_to_target_sockaddr(target_addr, addr, addrlen);
2200         if (put_user_u32(addrlen, target_addrlen_addr))
2201             ret = -TARGET_EFAULT;
2202     }
2203     return ret;
2204 }
2205
2206 /* do_getsockname() Must return target values and target errnos. */
2207 static abi_long do_getsockname(int fd, abi_ulong target_addr,
2208                                abi_ulong target_addrlen_addr)
2209 {
2210     socklen_t addrlen;
2211     void *addr;
2212     abi_long ret;
2213
2214     if (get_user_u32(addrlen, target_addrlen_addr))
2215         return -TARGET_EFAULT;
2216
2217     if ((int)addrlen < 0) {
2218         return -TARGET_EINVAL;
2219     }
2220
2221     if (!access_ok(VERIFY_WRITE, target_addr, addrlen))
2222         return -TARGET_EFAULT;
2223
2224     addr = alloca(addrlen);
2225
2226     ret = get_errno(getsockname(fd, addr, &addrlen));
2227     if (!is_error(ret)) {
2228         host_to_target_sockaddr(target_addr, addr, addrlen);
2229         if (put_user_u32(addrlen, target_addrlen_addr))
2230             ret = -TARGET_EFAULT;
2231     }
2232     return ret;
2233 }
2234
2235 /* do_socketpair() Must return target values and target errnos. */
2236 static abi_long do_socketpair(int domain, int type, int protocol,
2237                               abi_ulong target_tab_addr)
2238 {
2239     int tab[2];
2240     abi_long ret;
2241
2242     target_to_host_sock_type(&type);
2243
2244     ret = get_errno(socketpair(domain, type, protocol, tab));
2245     if (!is_error(ret)) {
2246         if (put_user_s32(tab[0], target_tab_addr)
2247             || put_user_s32(tab[1], target_tab_addr + sizeof(tab[0])))
2248             ret = -TARGET_EFAULT;
2249     }
2250     return ret;
2251 }
2252
2253 /* do_sendto() Must return target values and target errnos. */
2254 static abi_long do_sendto(int fd, abi_ulong msg, size_t len, int flags,
2255                           abi_ulong target_addr, socklen_t addrlen)
2256 {
2257     void *addr;
2258     void *host_msg;
2259     abi_long ret;
2260
2261     if ((int)addrlen < 0) {
2262         return -TARGET_EINVAL;
2263     }
2264
2265     host_msg = lock_user(VERIFY_READ, msg, len, 1);
2266     if (!host_msg)
2267         return -TARGET_EFAULT;
2268     if (target_addr) {
2269         addr = alloca(addrlen+1);
2270         ret = target_to_host_sockaddr(addr, target_addr, addrlen);
2271         if (ret) {
2272             unlock_user(host_msg, msg, 0);
2273             return ret;
2274         }
2275         ret = get_errno(sendto(fd, host_msg, len, flags, addr, addrlen));
2276     } else {
2277         ret = get_errno(send(fd, host_msg, len, flags));
2278     }
2279     unlock_user(host_msg, msg, 0);
2280     return ret;
2281 }
2282
2283 /* do_recvfrom() Must return target values and target errnos. */
2284 static abi_long do_recvfrom(int fd, abi_ulong msg, size_t len, int flags,
2285                             abi_ulong target_addr,
2286                             abi_ulong target_addrlen)
2287 {
2288     socklen_t addrlen;
2289     void *addr;
2290     void *host_msg;
2291     abi_long ret;
2292
2293     host_msg = lock_user(VERIFY_WRITE, msg, len, 0);
2294     if (!host_msg)
2295         return -TARGET_EFAULT;
2296     if (target_addr) {
2297         if (get_user_u32(addrlen, target_addrlen)) {
2298             ret = -TARGET_EFAULT;
2299             goto fail;
2300         }
2301         if ((int)addrlen < 0) {
2302             ret = -TARGET_EINVAL;
2303             goto fail;
2304         }
2305         addr = alloca(addrlen);
2306         ret = get_errno(recvfrom(fd, host_msg, len, flags, addr, &addrlen));
2307     } else {
2308         addr = NULL; /* To keep compiler quiet.  */
2309         ret = get_errno(qemu_recv(fd, host_msg, len, flags));
2310     }
2311     if (!is_error(ret)) {
2312         if (target_addr) {
2313             host_to_target_sockaddr(target_addr, addr, addrlen);
2314             if (put_user_u32(addrlen, target_addrlen)) {
2315                 ret = -TARGET_EFAULT;
2316                 goto fail;
2317             }
2318         }
2319         unlock_user(host_msg, msg, len);
2320     } else {
2321 fail:
2322         unlock_user(host_msg, msg, 0);
2323     }
2324     return ret;
2325 }
2326
2327 #ifdef TARGET_NR_socketcall
2328 /* do_socketcall() Must return target values and target errnos. */
2329 static abi_long do_socketcall(int num, abi_ulong vptr)
2330 {
2331     static const unsigned ac[] = { /* number of arguments per call */
2332         [SOCKOP_socket] = 3,      /* domain, type, protocol */
2333         [SOCKOP_bind] = 3,        /* sockfd, addr, addrlen */
2334         [SOCKOP_connect] = 3,     /* sockfd, addr, addrlen */
2335         [SOCKOP_listen] = 2,      /* sockfd, backlog */
2336         [SOCKOP_accept] = 3,      /* sockfd, addr, addrlen */
2337         [SOCKOP_accept4] = 4,     /* sockfd, addr, addrlen, flags */
2338         [SOCKOP_getsockname] = 3, /* sockfd, addr, addrlen */
2339         [SOCKOP_getpeername] = 3, /* sockfd, addr, addrlen */
2340         [SOCKOP_socketpair] = 4,  /* domain, type, protocol, tab */
2341         [SOCKOP_send] = 4,        /* sockfd, msg, len, flags */
2342         [SOCKOP_recv] = 4,        /* sockfd, msg, len, flags */
2343         [SOCKOP_sendto] = 6,      /* sockfd, msg, len, flags, addr, addrlen */
2344         [SOCKOP_recvfrom] = 6,    /* sockfd, msg, len, flags, addr, addrlen */
2345         [SOCKOP_shutdown] = 2,    /* sockfd, how */
2346         [SOCKOP_sendmsg] = 3,     /* sockfd, msg, flags */
2347         [SOCKOP_recvmsg] = 3,     /* sockfd, msg, flags */
2348         [SOCKOP_setsockopt] = 5,  /* sockfd, level, optname, optval, optlen */
2349         [SOCKOP_getsockopt] = 5,  /* sockfd, level, optname, optval, optlen */
2350     };
2351     abi_long a[6]; /* max 6 args */
2352
2353     /* first, collect the arguments in a[] according to ac[] */
2354     if (num >= 0 && num < ARRAY_SIZE(ac)) {
2355         unsigned i;
2356         assert(ARRAY_SIZE(a) >= ac[num]); /* ensure we have space for args */
2357         for (i = 0; i < ac[num]; ++i) {
2358             if (get_user_ual(a[i], vptr + i * sizeof(abi_long)) != 0) {
2359                 return -TARGET_EFAULT;
2360             }
2361         }
2362     }
2363
2364     /* now when we have the args, actually handle the call */
2365     switch (num) {
2366     case SOCKOP_socket: /* domain, type, protocol */
2367         return do_socket(a[0], a[1], a[2]);
2368     case SOCKOP_bind: /* sockfd, addr, addrlen */
2369         return do_bind(a[0], a[1], a[2]);
2370     case SOCKOP_connect: /* sockfd, addr, addrlen */
2371         return do_connect(a[0], a[1], a[2]);
2372     case SOCKOP_listen: /* sockfd, backlog */
2373         return get_errno(listen(a[0], a[1]));
2374     case SOCKOP_accept: /* sockfd, addr, addrlen */
2375         return do_accept4(a[0], a[1], a[2], 0);
2376     case SOCKOP_accept4: /* sockfd, addr, addrlen, flags */
2377         return do_accept4(a[0], a[1], a[2], a[3]);
2378     case SOCKOP_getsockname: /* sockfd, addr, addrlen */
2379         return do_getsockname(a[0], a[1], a[2]);
2380     case SOCKOP_getpeername: /* sockfd, addr, addrlen */
2381         return do_getpeername(a[0], a[1], a[2]);
2382     case SOCKOP_socketpair: /* domain, type, protocol, tab */
2383         return do_socketpair(a[0], a[1], a[2], a[3]);
2384     case SOCKOP_send: /* sockfd, msg, len, flags */
2385         return do_sendto(a[0], a[1], a[2], a[3], 0, 0);
2386     case SOCKOP_recv: /* sockfd, msg, len, flags */
2387         return do_recvfrom(a[0], a[1], a[2], a[3], 0, 0);
2388     case SOCKOP_sendto: /* sockfd, msg, len, flags, addr, addrlen */
2389         return do_sendto(a[0], a[1], a[2], a[3], a[4], a[5]);
2390     case SOCKOP_recvfrom: /* sockfd, msg, len, flags, addr, addrlen */
2391         return do_recvfrom(a[0], a[1], a[2], a[3], a[4], a[5]);
2392     case SOCKOP_shutdown: /* sockfd, how */
2393         return get_errno(shutdown(a[0], a[1]));
2394     case SOCKOP_sendmsg: /* sockfd, msg, flags */
2395         return do_sendrecvmsg(a[0], a[1], a[2], 1);
2396     case SOCKOP_recvmsg: /* sockfd, msg, flags */
2397         return do_sendrecvmsg(a[0], a[1], a[2], 0);
2398     case SOCKOP_setsockopt: /* sockfd, level, optname, optval, optlen */
2399         return do_setsockopt(a[0], a[1], a[2], a[3], a[4]);
2400     case SOCKOP_getsockopt: /* sockfd, level, optname, optval, optlen */
2401         return do_getsockopt(a[0], a[1], a[2], a[3], a[4]);
2402     default:
2403         gemu_log("Unsupported socketcall: %d\n", num);
2404         return -TARGET_ENOSYS;
2405     }
2406 }
2407 #endif
2408
2409 #define N_SHM_REGIONS   32
2410
2411 static struct shm_region {
2412     abi_ulong   start;
2413     abi_ulong   size;
2414 } shm_regions[N_SHM_REGIONS];
2415
2416 struct target_semid_ds
2417 {
2418   struct target_ipc_perm sem_perm;
2419   abi_ulong sem_otime;
2420   abi_ulong __unused1;
2421   abi_ulong sem_ctime;
2422   abi_ulong __unused2;
2423   abi_ulong sem_nsems;
2424   abi_ulong __unused3;
2425   abi_ulong __unused4;
2426 };
2427
2428 static inline abi_long target_to_host_ipc_perm(struct ipc_perm *host_ip,
2429                                                abi_ulong target_addr)
2430 {
2431     struct target_ipc_perm *target_ip;
2432     struct target_semid_ds *target_sd;
2433
2434     if (!lock_user_struct(VERIFY_READ, target_sd, target_addr, 1))
2435         return -TARGET_EFAULT;
2436     target_ip = &(target_sd->sem_perm);
2437     host_ip->__key = tswap32(target_ip->__key);
2438     host_ip->uid = tswap32(target_ip->uid);
2439     host_ip->gid = tswap32(target_ip->gid);
2440     host_ip->cuid = tswap32(target_ip->cuid);
2441     host_ip->cgid = tswap32(target_ip->cgid);
2442 #if defined(TARGET_ALPHA) || defined(TARGET_MIPS) || defined(TARGET_PPC)
2443     host_ip->mode = tswap32(target_ip->mode);
2444 #else
2445     host_ip->mode = tswap16(target_ip->mode);
2446 #endif
2447 #if defined(TARGET_PPC)
2448     host_ip->__seq = tswap32(target_ip->__seq);
2449 #else
2450     host_ip->__seq = tswap16(target_ip->__seq);
2451 #endif
2452     unlock_user_struct(target_sd, target_addr, 0);
2453     return 0;
2454 }
2455
2456 static inline abi_long host_to_target_ipc_perm(abi_ulong target_addr,
2457                                                struct ipc_perm *host_ip)
2458 {
2459     struct target_ipc_perm *target_ip;
2460     struct target_semid_ds *target_sd;
2461
2462     if (!lock_user_struct(VERIFY_WRITE, target_sd, target_addr, 0))
2463         return -TARGET_EFAULT;
2464     target_ip = &(target_sd->sem_perm);
2465     target_ip->__key = tswap32(host_ip->__key);
2466     target_ip->uid = tswap32(host_ip->uid);
2467     target_ip->gid = tswap32(host_ip->gid);
2468     target_ip->cuid = tswap32(host_ip->cuid);
2469     target_ip->cgid = tswap32(host_ip->cgid);
2470 #if defined(TARGET_ALPHA) || defined(TARGET_MIPS) || defined(TARGET_PPC)
2471     target_ip->mode = tswap32(host_ip->mode);
2472 #else
2473     target_ip->mode = tswap16(host_ip->mode);
2474 #endif
2475 #if defined(TARGET_PPC)
2476     target_ip->__seq = tswap32(host_ip->__seq);
2477 #else
2478     target_ip->__seq = tswap16(host_ip->__seq);
2479 #endif
2480     unlock_user_struct(target_sd, target_addr, 1);
2481     return 0;
2482 }
2483
2484 static inline abi_long target_to_host_semid_ds(struct semid_ds *host_sd,
2485                                                abi_ulong target_addr)
2486 {
2487     struct target_semid_ds *target_sd;
2488
2489     if (!lock_user_struct(VERIFY_READ, target_sd, target_addr, 1))
2490         return -TARGET_EFAULT;
2491     if (target_to_host_ipc_perm(&(host_sd->sem_perm),target_addr))
2492         return -TARGET_EFAULT;
2493     host_sd->sem_nsems = tswapal(target_sd->sem_nsems);
2494     host_sd->sem_otime = tswapal(target_sd->sem_otime);
2495     host_sd->sem_ctime = tswapal(target_sd->sem_ctime);
2496     unlock_user_struct(target_sd, target_addr, 0);
2497     return 0;
2498 }
2499
2500 static inline abi_long host_to_target_semid_ds(abi_ulong target_addr,
2501                                                struct semid_ds *host_sd)
2502 {
2503     struct target_semid_ds *target_sd;
2504
2505     if (!lock_user_struct(VERIFY_WRITE, target_sd, target_addr, 0))
2506         return -TARGET_EFAULT;
2507     if (host_to_target_ipc_perm(target_addr,&(host_sd->sem_perm)))
2508         return -TARGET_EFAULT;
2509     target_sd->sem_nsems = tswapal(host_sd->sem_nsems);
2510     target_sd->sem_otime = tswapal(host_sd->sem_otime);
2511     target_sd->sem_ctime = tswapal(host_sd->sem_ctime);
2512     unlock_user_struct(target_sd, target_addr, 1);
2513     return 0;
2514 }
2515
2516 struct target_seminfo {
2517     int semmap;
2518     int semmni;
2519     int semmns;
2520     int semmnu;
2521     int semmsl;
2522     int semopm;
2523     int semume;
2524     int semusz;
2525     int semvmx;
2526     int semaem;
2527 };
2528
2529 static inline abi_long host_to_target_seminfo(abi_ulong target_addr,
2530                                               struct seminfo *host_seminfo)
2531 {
2532     struct target_seminfo *target_seminfo;
2533     if (!lock_user_struct(VERIFY_WRITE, target_seminfo, target_addr, 0))
2534         return -TARGET_EFAULT;
2535     __put_user(host_seminfo->semmap, &target_seminfo->semmap);
2536     __put_user(host_seminfo->semmni, &target_seminfo->semmni);
2537     __put_user(host_seminfo->semmns, &target_seminfo->semmns);
2538     __put_user(host_seminfo->semmnu, &target_seminfo->semmnu);
2539     __put_user(host_seminfo->semmsl, &target_seminfo->semmsl);
2540     __put_user(host_seminfo->semopm, &target_seminfo->semopm);
2541     __put_user(host_seminfo->semume, &target_seminfo->semume);
2542     __put_user(host_seminfo->semusz, &target_seminfo->semusz);
2543     __put_user(host_seminfo->semvmx, &target_seminfo->semvmx);
2544     __put_user(host_seminfo->semaem, &target_seminfo->semaem);
2545     unlock_user_struct(target_seminfo, target_addr, 1);
2546     return 0;
2547 }
2548
2549 union semun {
2550         int val;
2551         struct semid_ds *buf;
2552         unsigned short *array;
2553         struct seminfo *__buf;
2554 };
2555
2556 union target_semun {
2557         int val;
2558         abi_ulong buf;
2559         abi_ulong array;
2560         abi_ulong __buf;
2561 };
2562
2563 static inline abi_long target_to_host_semarray(int semid, unsigned short **host_array,
2564                                                abi_ulong target_addr)
2565 {
2566     int nsems;
2567     unsigned short *array;
2568     union semun semun;
2569     struct semid_ds semid_ds;
2570     int i, ret;
2571
2572     semun.buf = &semid_ds;
2573
2574     ret = semctl(semid, 0, IPC_STAT, semun);
2575     if (ret == -1)
2576         return get_errno(ret);
2577
2578     nsems = semid_ds.sem_nsems;
2579
2580     *host_array = malloc(nsems*sizeof(unsigned short));
2581     if (!*host_array) {
2582         return -TARGET_ENOMEM;
2583     }
2584     array = lock_user(VERIFY_READ, target_addr,
2585                       nsems*sizeof(unsigned short), 1);
2586     if (!array) {
2587         free(*host_array);
2588         return -TARGET_EFAULT;
2589     }
2590
2591     for(i=0; i<nsems; i++) {
2592         __get_user((*host_array)[i], &array[i]);
2593     }
2594     unlock_user(array, target_addr, 0);
2595
2596     return 0;
2597 }
2598
2599 static inline abi_long host_to_target_semarray(int semid, abi_ulong target_addr,
2600                                                unsigned short **host_array)
2601 {
2602     int nsems;
2603     unsigned short *array;
2604     union semun semun;
2605     struct semid_ds semid_ds;
2606     int i, ret;
2607
2608     semun.buf = &semid_ds;
2609
2610     ret = semctl(semid, 0, IPC_STAT, semun);
2611     if (ret == -1)
2612         return get_errno(ret);
2613
2614     nsems = semid_ds.sem_nsems;
2615
2616     array = lock_user(VERIFY_WRITE, target_addr,
2617                       nsems*sizeof(unsigned short), 0);
2618     if (!array)
2619         return -TARGET_EFAULT;
2620
2621     for(i=0; i<nsems; i++) {
2622         __put_user((*host_array)[i], &array[i]);
2623     }
2624     free(*host_array);
2625     unlock_user(array, target_addr, 1);
2626
2627     return 0;
2628 }
2629
2630 static inline abi_long do_semctl(int semid, int semnum, int cmd,
2631                                  union target_semun target_su)
2632 {
2633     union semun arg;
2634     struct semid_ds dsarg;
2635     unsigned short *array = NULL;
2636     struct seminfo seminfo;
2637     abi_long ret = -TARGET_EINVAL;
2638     abi_long err;
2639     cmd &= 0xff;
2640
2641     switch( cmd ) {
2642         case GETVAL:
2643         case SETVAL:
2644             arg.val = tswap32(target_su.val);
2645             ret = get_errno(semctl(semid, semnum, cmd, arg));
2646             target_su.val = tswap32(arg.val);
2647             break;
2648         case GETALL:
2649         case SETALL:
2650             err = target_to_host_semarray(semid, &array, target_su.array);
2651             if (err)
2652                 return err;
2653             arg.array = array;
2654             ret = get_errno(semctl(semid, semnum, cmd, arg));
2655             err = host_to_target_semarray(semid, target_su.array, &array);
2656             if (err)
2657                 return err;
2658             break;
2659         case IPC_STAT:
2660         case IPC_SET:
2661         case SEM_STAT:
2662             err = target_to_host_semid_ds(&dsarg, target_su.buf);
2663             if (err)
2664                 return err;
2665             arg.buf = &dsarg;
2666             ret = get_errno(semctl(semid, semnum, cmd, arg));
2667             err = host_to_target_semid_ds(target_su.buf, &dsarg);
2668             if (err)
2669                 return err;
2670             break;
2671         case IPC_INFO:
2672         case SEM_INFO:
2673             arg.__buf = &seminfo;
2674             ret = get_errno(semctl(semid, semnum, cmd, arg));
2675             err = host_to_target_seminfo(target_su.__buf, &seminfo);
2676             if (err)
2677                 return err;
2678             break;
2679         case IPC_RMID:
2680         case GETPID:
2681         case GETNCNT:
2682         case GETZCNT:
2683             ret = get_errno(semctl(semid, semnum, cmd, NULL));
2684             break;
2685     }
2686
2687     return ret;
2688 }
2689
2690 struct target_sembuf {
2691     unsigned short sem_num;
2692     short sem_op;
2693     short sem_flg;
2694 };
2695
2696 static inline abi_long target_to_host_sembuf(struct sembuf *host_sembuf,
2697                                              abi_ulong target_addr,
2698                                              unsigned nsops)
2699 {
2700     struct target_sembuf *target_sembuf;
2701     int i;
2702
2703     target_sembuf = lock_user(VERIFY_READ, target_addr,
2704                               nsops*sizeof(struct target_sembuf), 1);
2705     if (!target_sembuf)
2706         return -TARGET_EFAULT;
2707
2708     for(i=0; i<nsops; i++) {
2709         __get_user(host_sembuf[i].sem_num, &target_sembuf[i].sem_num);
2710         __get_user(host_sembuf[i].sem_op, &target_sembuf[i].sem_op);
2711         __get_user(host_sembuf[i].sem_flg, &target_sembuf[i].sem_flg);
2712     }
2713
2714     unlock_user(target_sembuf, target_addr, 0);
2715
2716     return 0;
2717 }
2718
2719 static inline abi_long do_semop(int semid, abi_long ptr, unsigned nsops)
2720 {
2721     struct sembuf sops[nsops];
2722
2723     if (target_to_host_sembuf(sops, ptr, nsops))
2724         return -TARGET_EFAULT;
2725
2726     return get_errno(semop(semid, sops, nsops));
2727 }
2728
2729 struct target_msqid_ds
2730 {
2731     struct target_ipc_perm msg_perm;
2732     abi_ulong msg_stime;
2733 #if TARGET_ABI_BITS == 32
2734     abi_ulong __unused1;
2735 #endif
2736     abi_ulong msg_rtime;
2737 #if TARGET_ABI_BITS == 32
2738     abi_ulong __unused2;
2739 #endif
2740     abi_ulong msg_ctime;
2741 #if TARGET_ABI_BITS == 32
2742     abi_ulong __unused3;
2743 #endif
2744     abi_ulong __msg_cbytes;
2745     abi_ulong msg_qnum;
2746     abi_ulong msg_qbytes;
2747     abi_ulong msg_lspid;
2748     abi_ulong msg_lrpid;
2749     abi_ulong __unused4;
2750     abi_ulong __unused5;
2751 };
2752
2753 static inline abi_long target_to_host_msqid_ds(struct msqid_ds *host_md,
2754                                                abi_ulong target_addr)
2755 {
2756     struct target_msqid_ds *target_md;
2757
2758     if (!lock_user_struct(VERIFY_READ, target_md, target_addr, 1))
2759         return -TARGET_EFAULT;
2760     if (target_to_host_ipc_perm(&(host_md->msg_perm),target_addr))
2761         return -TARGET_EFAULT;
2762     host_md->msg_stime = tswapal(target_md->msg_stime);
2763     host_md->msg_rtime = tswapal(target_md->msg_rtime);
2764     host_md->msg_ctime = tswapal(target_md->msg_ctime);
2765     host_md->__msg_cbytes = tswapal(target_md->__msg_cbytes);
2766     host_md->msg_qnum = tswapal(target_md->msg_qnum);
2767     host_md->msg_qbytes = tswapal(target_md->msg_qbytes);
2768     host_md->msg_lspid = tswapal(target_md->msg_lspid);
2769     host_md->msg_lrpid = tswapal(target_md->msg_lrpid);
2770     unlock_user_struct(target_md, target_addr, 0);
2771     return 0;
2772 }
2773
2774 static inline abi_long host_to_target_msqid_ds(abi_ulong target_addr,
2775                                                struct msqid_ds *host_md)
2776 {
2777     struct target_msqid_ds *target_md;
2778
2779     if (!lock_user_struct(VERIFY_WRITE, target_md, target_addr, 0))
2780         return -TARGET_EFAULT;
2781     if (host_to_target_ipc_perm(target_addr,&(host_md->msg_perm)))
2782         return -TARGET_EFAULT;
2783     target_md->msg_stime = tswapal(host_md->msg_stime);
2784     target_md->msg_rtime = tswapal(host_md->msg_rtime);
2785     target_md->msg_ctime = tswapal(host_md->msg_ctime);
2786     target_md->__msg_cbytes = tswapal(host_md->__msg_cbytes);
2787     target_md->msg_qnum = tswapal(host_md->msg_qnum);
2788     target_md->msg_qbytes = tswapal(host_md->msg_qbytes);
2789     target_md->msg_lspid = tswapal(host_md->msg_lspid);
2790     target_md->msg_lrpid = tswapal(host_md->msg_lrpid);
2791     unlock_user_struct(target_md, target_addr, 1);
2792     return 0;
2793 }
2794
2795 struct target_msginfo {
2796     int msgpool;
2797     int msgmap;
2798     int msgmax;
2799     int msgmnb;
2800     int msgmni;
2801     int msgssz;
2802     int msgtql;
2803     unsigned short int msgseg;
2804 };
2805
2806 static inline abi_long host_to_target_msginfo(abi_ulong target_addr,
2807                                               struct msginfo *host_msginfo)
2808 {
2809     struct target_msginfo *target_msginfo;
2810     if (!lock_user_struct(VERIFY_WRITE, target_msginfo, target_addr, 0))
2811         return -TARGET_EFAULT;
2812     __put_user(host_msginfo->msgpool, &target_msginfo->msgpool);
2813     __put_user(host_msginfo->msgmap, &target_msginfo->msgmap);
2814     __put_user(host_msginfo->msgmax, &target_msginfo->msgmax);
2815     __put_user(host_msginfo->msgmnb, &target_msginfo->msgmnb);
2816     __put_user(host_msginfo->msgmni, &target_msginfo->msgmni);
2817     __put_user(host_msginfo->msgssz, &target_msginfo->msgssz);
2818     __put_user(host_msginfo->msgtql, &target_msginfo->msgtql);
2819     __put_user(host_msginfo->msgseg, &target_msginfo->msgseg);
2820     unlock_user_struct(target_msginfo, target_addr, 1);
2821     return 0;
2822 }
2823
2824 static inline abi_long do_msgctl(int msgid, int cmd, abi_long ptr)
2825 {
2826     struct msqid_ds dsarg;
2827     struct msginfo msginfo;
2828     abi_long ret = -TARGET_EINVAL;
2829
2830     cmd &= 0xff;
2831
2832     switch (cmd) {
2833     case IPC_STAT:
2834     case IPC_SET:
2835     case MSG_STAT:
2836         if (target_to_host_msqid_ds(&dsarg,ptr))
2837             return -TARGET_EFAULT;
2838         ret = get_errno(msgctl(msgid, cmd, &dsarg));
2839         if (host_to_target_msqid_ds(ptr,&dsarg))
2840             return -TARGET_EFAULT;
2841         break;
2842     case IPC_RMID:
2843         ret = get_errno(msgctl(msgid, cmd, NULL));
2844         break;
2845     case IPC_INFO:
2846     case MSG_INFO:
2847         ret = get_errno(msgctl(msgid, cmd, (struct msqid_ds *)&msginfo));
2848         if (host_to_target_msginfo(ptr, &msginfo))
2849             return -TARGET_EFAULT;
2850         break;
2851     }
2852
2853     return ret;
2854 }
2855
2856 struct target_msgbuf {
2857     abi_long mtype;
2858     char        mtext[1];
2859 };
2860
2861 static inline abi_long do_msgsnd(int msqid, abi_long msgp,
2862                                  unsigned int msgsz, int msgflg)
2863 {
2864     struct target_msgbuf *target_mb;
2865     struct msgbuf *host_mb;
2866     abi_long ret = 0;
2867
2868     if (!lock_user_struct(VERIFY_READ, target_mb, msgp, 0))
2869         return -TARGET_EFAULT;
2870     host_mb = malloc(msgsz+sizeof(long));
2871     host_mb->mtype = (abi_long) tswapal(target_mb->mtype);
2872     memcpy(host_mb->mtext, target_mb->mtext, msgsz);
2873     ret = get_errno(msgsnd(msqid, host_mb, msgsz, msgflg));
2874     free(host_mb);
2875     unlock_user_struct(target_mb, msgp, 0);
2876
2877     return ret;
2878 }
2879
2880 static inline abi_long do_msgrcv(int msqid, abi_long msgp,
2881                                  unsigned int msgsz, abi_long msgtyp,
2882                                  int msgflg)
2883 {
2884     struct target_msgbuf *target_mb;
2885     char *target_mtext;
2886     struct msgbuf *host_mb;
2887     abi_long ret = 0;
2888
2889     if (!lock_user_struct(VERIFY_WRITE, target_mb, msgp, 0))
2890         return -TARGET_EFAULT;
2891
2892     host_mb = g_malloc(msgsz+sizeof(long));
2893     ret = get_errno(msgrcv(msqid, host_mb, msgsz, msgtyp, msgflg));
2894
2895     if (ret > 0) {
2896         abi_ulong target_mtext_addr = msgp + sizeof(abi_ulong);
2897         target_mtext = lock_user(VERIFY_WRITE, target_mtext_addr, ret, 0);
2898         if (!target_mtext) {
2899             ret = -TARGET_EFAULT;
2900             goto end;
2901         }
2902         memcpy(target_mb->mtext, host_mb->mtext, ret);
2903         unlock_user(target_mtext, target_mtext_addr, ret);
2904     }
2905
2906     target_mb->mtype = tswapal(host_mb->mtype);
2907
2908 end:
2909     if (target_mb)
2910         unlock_user_struct(target_mb, msgp, 1);
2911     g_free(host_mb);
2912     return ret;
2913 }
2914
2915 static inline abi_long target_to_host_shmid_ds(struct shmid_ds *host_sd,
2916                                                abi_ulong target_addr)
2917 {
2918     struct target_shmid_ds *target_sd;
2919
2920     if (!lock_user_struct(VERIFY_READ, target_sd, target_addr, 1))
2921         return -TARGET_EFAULT;
2922     if (target_to_host_ipc_perm(&(host_sd->shm_perm), target_addr))
2923         return -TARGET_EFAULT;
2924     __get_user(host_sd->shm_segsz, &target_sd->shm_segsz);
2925     __get_user(host_sd->shm_atime, &target_sd->shm_atime);
2926     __get_user(host_sd->shm_dtime, &target_sd->shm_dtime);
2927     __get_user(host_sd->shm_ctime, &target_sd->shm_ctime);
2928     __get_user(host_sd->shm_cpid, &target_sd->shm_cpid);
2929     __get_user(host_sd->shm_lpid, &target_sd->shm_lpid);
2930     __get_user(host_sd->shm_nattch, &target_sd->shm_nattch);
2931     unlock_user_struct(target_sd, target_addr, 0);
2932     return 0;
2933 }
2934
2935 static inline abi_long host_to_target_shmid_ds(abi_ulong target_addr,
2936                                                struct shmid_ds *host_sd)
2937 {
2938     struct target_shmid_ds *target_sd;
2939
2940     if (!lock_user_struct(VERIFY_WRITE, target_sd, target_addr, 0))
2941         return -TARGET_EFAULT;
2942     if (host_to_target_ipc_perm(target_addr, &(host_sd->shm_perm)))
2943         return -TARGET_EFAULT;
2944     __put_user(host_sd->shm_segsz, &target_sd->shm_segsz);
2945     __put_user(host_sd->shm_atime, &target_sd->shm_atime);
2946     __put_user(host_sd->shm_dtime, &target_sd->shm_dtime);
2947     __put_user(host_sd->shm_ctime, &target_sd->shm_ctime);
2948     __put_user(host_sd->shm_cpid, &target_sd->shm_cpid);
2949     __put_user(host_sd->shm_lpid, &target_sd->shm_lpid);
2950     __put_user(host_sd->shm_nattch, &target_sd->shm_nattch);
2951     unlock_user_struct(target_sd, target_addr, 1);
2952     return 0;
2953 }
2954
2955 struct  target_shminfo {
2956     abi_ulong shmmax;
2957     abi_ulong shmmin;
2958     abi_ulong shmmni;
2959     abi_ulong shmseg;
2960     abi_ulong shmall;
2961 };
2962
2963 static inline abi_long host_to_target_shminfo(abi_ulong target_addr,
2964                                               struct shminfo *host_shminfo)
2965 {
2966     struct target_shminfo *target_shminfo;
2967     if (!lock_user_struct(VERIFY_WRITE, target_shminfo, target_addr, 0))
2968         return -TARGET_EFAULT;
2969     __put_user(host_shminfo->shmmax, &target_shminfo->shmmax);
2970     __put_user(host_shminfo->shmmin, &target_shminfo->shmmin);
2971     __put_user(host_shminfo->shmmni, &target_shminfo->shmmni);
2972     __put_user(host_shminfo->shmseg, &target_shminfo->shmseg);
2973     __put_user(host_shminfo->shmall, &target_shminfo->shmall);
2974     unlock_user_struct(target_shminfo, target_addr, 1);
2975     return 0;
2976 }
2977
2978 struct target_shm_info {
2979     int used_ids;
2980     abi_ulong shm_tot;
2981     abi_ulong shm_rss;
2982     abi_ulong shm_swp;
2983     abi_ulong swap_attempts;
2984     abi_ulong swap_successes;
2985 };
2986
2987 static inline abi_long host_to_target_shm_info(abi_ulong target_addr,
2988                                                struct shm_info *host_shm_info)
2989 {
2990     struct target_shm_info *target_shm_info;
2991     if (!lock_user_struct(VERIFY_WRITE, target_shm_info, target_addr, 0))
2992         return -TARGET_EFAULT;
2993     __put_user(host_shm_info->used_ids, &target_shm_info->used_ids);
2994     __put_user(host_shm_info->shm_tot, &target_shm_info->shm_tot);
2995     __put_user(host_shm_info->shm_rss, &target_shm_info->shm_rss);
2996     __put_user(host_shm_info->shm_swp, &target_shm_info->shm_swp);
2997     __put_user(host_shm_info->swap_attempts, &target_shm_info->swap_attempts);
2998     __put_user(host_shm_info->swap_successes, &target_shm_info->swap_successes);
2999     unlock_user_struct(target_shm_info, target_addr, 1);
3000     return 0;
3001 }
3002
3003 static inline abi_long do_shmctl(int shmid, int cmd, abi_long buf)
3004 {
3005     struct shmid_ds dsarg;
3006     struct shminfo shminfo;
3007     struct shm_info shm_info;
3008     abi_long ret = -TARGET_EINVAL;
3009
3010     cmd &= 0xff;
3011
3012     switch(cmd) {
3013     case IPC_STAT:
3014     case IPC_SET:
3015     case SHM_STAT:
3016         if (target_to_host_shmid_ds(&dsarg, buf))
3017             return -TARGET_EFAULT;
3018         ret = get_errno(shmctl(shmid, cmd, &dsarg));
3019         if (host_to_target_shmid_ds(buf, &dsarg))
3020             return -TARGET_EFAULT;
3021         break;
3022     case IPC_INFO:
3023         ret = get_errno(shmctl(shmid, cmd, (struct shmid_ds *)&shminfo));
3024         if (host_to_target_shminfo(buf, &shminfo))
3025             return -TARGET_EFAULT;
3026         break;
3027     case SHM_INFO:
3028         ret = get_errno(shmctl(shmid, cmd, (struct shmid_ds *)&shm_info));
3029         if (host_to_target_shm_info(buf, &shm_info))
3030             return -TARGET_EFAULT;
3031         break;
3032     case IPC_RMID:
3033     case SHM_LOCK:
3034     case SHM_UNLOCK:
3035         ret = get_errno(shmctl(shmid, cmd, NULL));
3036         break;
3037     }
3038
3039     return ret;
3040 }
3041
3042 static inline abi_ulong do_shmat(int shmid, abi_ulong shmaddr, int shmflg)
3043 {
3044     abi_long raddr;
3045     void *host_raddr;
3046     struct shmid_ds shm_info;
3047     int i,ret;
3048
3049     /* find out the length of the shared memory segment */
3050     ret = get_errno(shmctl(shmid, IPC_STAT, &shm_info));
3051     if (is_error(ret)) {
3052         /* can't get length, bail out */
3053         return ret;
3054     }
3055
3056     mmap_lock();
3057
3058     if (shmaddr)
3059         host_raddr = shmat(shmid, (void *)g2h(shmaddr), shmflg);
3060     else {
3061         abi_ulong mmap_start;
3062
3063         mmap_start = mmap_find_vma(0, shm_info.shm_segsz);
3064
3065         if (mmap_start == -1) {
3066             errno = ENOMEM;
3067             host_raddr = (void *)-1;
3068         } else
3069             host_raddr = shmat(shmid, g2h(mmap_start), shmflg | SHM_REMAP);
3070     }
3071
3072     if (host_raddr == (void *)-1) {
3073         mmap_unlock();
3074         return get_errno((long)host_raddr);
3075     }
3076     raddr=h2g((unsigned long)host_raddr);
3077
3078     page_set_flags(raddr, raddr + shm_info.shm_segsz,
3079                    PAGE_VALID | PAGE_READ |
3080                    ((shmflg & SHM_RDONLY)? 0 : PAGE_WRITE));
3081
3082     for (i = 0; i < N_SHM_REGIONS; i++) {
3083         if (shm_regions[i].start == 0) {
3084             shm_regions[i].start = raddr;
3085             shm_regions[i].size = shm_info.shm_segsz;
3086             break;
3087         }
3088     }
3089
3090     mmap_unlock();
3091     return raddr;
3092
3093 }
3094
3095 static inline abi_long do_shmdt(abi_ulong shmaddr)
3096 {
3097     int i;
3098
3099     for (i = 0; i < N_SHM_REGIONS; ++i) {
3100         if (shm_regions[i].start == shmaddr) {
3101             shm_regions[i].start = 0;
3102             page_set_flags(shmaddr, shmaddr + shm_regions[i].size, 0);
3103             break;
3104         }
3105     }
3106
3107     return get_errno(shmdt(g2h(shmaddr)));
3108 }
3109
3110 #ifdef TARGET_NR_ipc
3111 /* ??? This only works with linear mappings.  */
3112 /* do_ipc() must return target values and target errnos. */
3113 static abi_long do_ipc(unsigned int call, int first,
3114                        int second, int third,
3115                        abi_long ptr, abi_long fifth)
3116 {
3117     int version;
3118     abi_long ret = 0;
3119
3120     version = call >> 16;
3121     call &= 0xffff;
3122
3123     switch (call) {
3124     case IPCOP_semop:
3125         ret = do_semop(first, ptr, second);
3126         break;
3127
3128     case IPCOP_semget:
3129         ret = get_errno(semget(first, second, third));
3130         break;
3131
3132     case IPCOP_semctl:
3133         ret = do_semctl(first, second, third, (union target_semun)(abi_ulong) ptr);
3134         break;
3135
3136     case IPCOP_msgget:
3137         ret = get_errno(msgget(first, second));
3138         break;
3139
3140     case IPCOP_msgsnd:
3141         ret = do_msgsnd(first, ptr, second, third);
3142         break;
3143
3144     case IPCOP_msgctl:
3145         ret = do_msgctl(first, second, ptr);
3146         break;
3147
3148     case IPCOP_msgrcv:
3149         switch (version) {
3150         case 0:
3151             {
3152                 struct target_ipc_kludge {
3153                     abi_long msgp;
3154                     abi_long msgtyp;
3155                 } *tmp;
3156
3157                 if (!lock_user_struct(VERIFY_READ, tmp, ptr, 1)) {
3158                     ret = -TARGET_EFAULT;
3159                     break;
3160                 }
3161
3162                 ret = do_msgrcv(first, tswapal(tmp->msgp), second, tswapal(tmp->msgtyp), third);
3163
3164                 unlock_user_struct(tmp, ptr, 0);
3165                 break;
3166             }
3167         default:
3168             ret = do_msgrcv(first, ptr, second, fifth, third);
3169         }
3170         break;
3171
3172     case IPCOP_shmat:
3173         switch (version) {
3174         default:
3175         {
3176             abi_ulong raddr;
3177             raddr = do_shmat(first, ptr, second);
3178             if (is_error(raddr))
3179                 return get_errno(raddr);
3180             if (put_user_ual(raddr, third))
3181                 return -TARGET_EFAULT;
3182             break;
3183         }
3184         case 1:
3185             ret = -TARGET_EINVAL;
3186             break;
3187         }
3188         break;
3189     case IPCOP_shmdt:
3190         ret = do_shmdt(ptr);
3191         break;
3192
3193     case IPCOP_shmget:
3194         /* IPC_* flag values are the same on all linux platforms */
3195         ret = get_errno(shmget(first, second, third));
3196         break;
3197
3198         /* IPC_* and SHM_* command values are the same on all linux platforms */
3199     case IPCOP_shmctl:
3200         ret = do_shmctl(first, second, ptr);
3201         break;
3202     default:
3203         gemu_log("Unsupported ipc call: %d (version %d)\n", call, version);
3204         ret = -TARGET_ENOSYS;
3205         break;
3206     }
3207     return ret;
3208 }
3209 #endif
3210
3211 /* kernel structure types definitions */
3212
3213 #define STRUCT(name, ...) STRUCT_ ## name,
3214 #define STRUCT_SPECIAL(name) STRUCT_ ## name,
3215 enum {
3216 #include "syscall_types.h"
3217 };
3218 #undef STRUCT
3219 #undef STRUCT_SPECIAL
3220
3221 #define STRUCT(name, ...) static const argtype struct_ ## name ## _def[] = {  __VA_ARGS__, TYPE_NULL };
3222 #define STRUCT_SPECIAL(name)
3223 #include "syscall_types.h"
3224 #undef STRUCT
3225 #undef STRUCT_SPECIAL
3226
3227 typedef struct IOCTLEntry IOCTLEntry;
3228
3229 typedef abi_long do_ioctl_fn(const IOCTLEntry *ie, uint8_t *buf_temp,
3230                              int fd, abi_long cmd, abi_long arg);
3231
3232 struct IOCTLEntry {
3233     unsigned int target_cmd;
3234     unsigned int host_cmd;
3235     const char *name;
3236     int access;
3237     do_ioctl_fn *do_ioctl;
3238     const argtype arg_type[5];
3239 };
3240
3241 #define IOC_R 0x0001
3242 #define IOC_W 0x0002
3243 #define IOC_RW (IOC_R | IOC_W)
3244
3245 #define MAX_STRUCT_SIZE 4096
3246
3247 #ifdef CONFIG_FIEMAP
3248 /* So fiemap access checks don't overflow on 32 bit systems.
3249  * This is very slightly smaller than the limit imposed by
3250  * the underlying kernel.
3251  */
3252 #define FIEMAP_MAX_EXTENTS ((UINT_MAX - sizeof(struct fiemap))  \
3253                             / sizeof(struct fiemap_extent))
3254
3255 static abi_long do_ioctl_fs_ioc_fiemap(const IOCTLEntry *ie, uint8_t *buf_temp,
3256                                        int fd, abi_long cmd, abi_long arg)
3257 {
3258     /* The parameter for this ioctl is a struct fiemap followed
3259      * by an array of struct fiemap_extent whose size is set
3260      * in fiemap->fm_extent_count. The array is filled in by the
3261      * ioctl.
3262      */
3263     int target_size_in, target_size_out;
3264     struct fiemap *fm;
3265     const argtype *arg_type = ie->arg_type;
3266     const argtype extent_arg_type[] = { MK_STRUCT(STRUCT_fiemap_extent) };
3267     void *argptr, *p;
3268     abi_long ret;
3269     int i, extent_size = thunk_type_size(extent_arg_type, 0);
3270     uint32_t outbufsz;
3271     int free_fm = 0;
3272
3273     assert(arg_type[0] == TYPE_PTR);
3274     assert(ie->access == IOC_RW);
3275     arg_type++;
3276     target_size_in = thunk_type_size(arg_type, 0);
3277     argptr = lock_user(VERIFY_READ, arg, target_size_in, 1);
3278     if (!argptr) {
3279         return -TARGET_EFAULT;
3280     }
3281     thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
3282     unlock_user(argptr, arg, 0);
3283     fm = (struct fiemap *)buf_temp;
3284     if (fm->fm_extent_count > FIEMAP_MAX_EXTENTS) {
3285         return -TARGET_EINVAL;
3286     }
3287
3288     outbufsz = sizeof (*fm) +
3289         (sizeof(struct fiemap_extent) * fm->fm_extent_count);
3290
3291     if (outbufsz > MAX_STRUCT_SIZE) {
3292         /* We can't fit all the extents into the fixed size buffer.
3293          * Allocate one that is large enough and use it instead.
3294          */
3295         fm = malloc(outbufsz);
3296         if (!fm) {
3297             return -TARGET_ENOMEM;
3298         }
3299         memcpy(fm, buf_temp, sizeof(struct fiemap));
3300         free_fm = 1;
3301     }
3302     ret = get_errno(ioctl(fd, ie->host_cmd, fm));
3303     if (!is_error(ret)) {
3304         target_size_out = target_size_in;
3305         /* An extent_count of 0 means we were only counting the extents
3306          * so there are no structs to copy
3307          */
3308         if (fm->fm_extent_count != 0) {
3309             target_size_out += fm->fm_mapped_extents * extent_size;
3310         }
3311         argptr = lock_user(VERIFY_WRITE, arg, target_size_out, 0);
3312         if (!argptr) {
3313             ret = -TARGET_EFAULT;
3314         } else {
3315             /* Convert the struct fiemap */
3316             thunk_convert(argptr, fm, arg_type, THUNK_TARGET);
3317             if (fm->fm_extent_count != 0) {
3318                 p = argptr + target_size_in;
3319                 /* ...and then all the struct fiemap_extents */
3320                 for (i = 0; i < fm->fm_mapped_extents; i++) {
3321                     thunk_convert(p, &fm->fm_extents[i], extent_arg_type,
3322                                   THUNK_TARGET);
3323                     p += extent_size;
3324                 }
3325             }
3326             unlock_user(argptr, arg, target_size_out);
3327         }
3328     }
3329     if (free_fm) {
3330         free(fm);
3331     }
3332     return ret;
3333 }
3334 #endif
3335
3336 static abi_long do_ioctl_ifconf(const IOCTLEntry *ie, uint8_t *buf_temp,
3337                                 int fd, abi_long cmd, abi_long arg)
3338 {
3339     const argtype *arg_type = ie->arg_type;
3340     int target_size;
3341     void *argptr;
3342     int ret;
3343     struct ifconf *host_ifconf;
3344     uint32_t outbufsz;
3345     const argtype ifreq_arg_type[] = { MK_STRUCT(STRUCT_sockaddr_ifreq) };
3346     int target_ifreq_size;
3347     int nb_ifreq;
3348     int free_buf = 0;
3349     int i;
3350     int target_ifc_len;
3351     abi_long target_ifc_buf;
3352     int host_ifc_len;
3353     char *host_ifc_buf;
3354
3355     assert(arg_type[0] == TYPE_PTR);
3356     assert(ie->access == IOC_RW);
3357
3358     arg_type++;
3359     target_size = thunk_type_size(arg_type, 0);
3360
3361     argptr = lock_user(VERIFY_READ, arg, target_size, 1);
3362     if (!argptr)
3363         return -TARGET_EFAULT;
3364     thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
3365     unlock_user(argptr, arg, 0);
3366
3367     host_ifconf = (struct ifconf *)(unsigned long)buf_temp;
3368     target_ifc_len = host_ifconf->ifc_len;
3369     target_ifc_buf = (abi_long)(unsigned long)host_ifconf->ifc_buf;
3370
3371     target_ifreq_size = thunk_type_size(ifreq_arg_type, 0);
3372     nb_ifreq = target_ifc_len / target_ifreq_size;
3373     host_ifc_len = nb_ifreq * sizeof(struct ifreq);
3374
3375     outbufsz = sizeof(*host_ifconf) + host_ifc_len;
3376     if (outbufsz > MAX_STRUCT_SIZE) {
3377         /* We can't fit all the extents into the fixed size buffer.
3378          * Allocate one that is large enough and use it instead.
3379          */
3380         host_ifconf = malloc(outbufsz);
3381         if (!host_ifconf) {
3382             return -TARGET_ENOMEM;
3383         }
3384         memcpy(host_ifconf, buf_temp, sizeof(*host_ifconf));
3385         free_buf = 1;
3386     }
3387     host_ifc_buf = (char*)host_ifconf + sizeof(*host_ifconf);
3388
3389     host_ifconf->ifc_len = host_ifc_len;
3390     host_ifconf->ifc_buf = host_ifc_buf;
3391
3392     ret = get_errno(ioctl(fd, ie->host_cmd, host_ifconf));
3393     if (!is_error(ret)) {
3394         /* convert host ifc_len to target ifc_len */
3395
3396         nb_ifreq = host_ifconf->ifc_len / sizeof(struct ifreq);
3397         target_ifc_len = nb_ifreq * target_ifreq_size;
3398         host_ifconf->ifc_len = target_ifc_len;
3399
3400         /* restore target ifc_buf */
3401
3402         host_ifconf->ifc_buf = (char *)(unsigned long)target_ifc_buf;
3403
3404         /* copy struct ifconf to target user */
3405
3406         argptr = lock_user(VERIFY_WRITE, arg, target_size, 0);
3407         if (!argptr)
3408             return -TARGET_EFAULT;
3409         thunk_convert(argptr, host_ifconf, arg_type, THUNK_TARGET);
3410         unlock_user(argptr, arg, target_size);
3411
3412         /* copy ifreq[] to target user */
3413
3414         argptr = lock_user(VERIFY_WRITE, target_ifc_buf, target_ifc_len, 0);
3415         for (i = 0; i < nb_ifreq ; i++) {
3416             thunk_convert(argptr + i * target_ifreq_size,
3417                           host_ifc_buf + i * sizeof(struct ifreq),
3418                           ifreq_arg_type, THUNK_TARGET);
3419         }
3420         unlock_user(argptr, target_ifc_buf, target_ifc_len);
3421     }
3422
3423     if (free_buf) {
3424         free(host_ifconf);
3425     }
3426
3427     return ret;
3428 }
3429
3430 static abi_long do_ioctl_dm(const IOCTLEntry *ie, uint8_t *buf_temp, int fd,
3431                             abi_long cmd, abi_long arg)
3432 {
3433     void *argptr;
3434     struct dm_ioctl *host_dm;
3435     abi_long guest_data;
3436     uint32_t guest_data_size;
3437     int target_size;
3438     const argtype *arg_type = ie->arg_type;
3439     abi_long ret;
3440     void *big_buf = NULL;
3441     char *host_data;
3442
3443     arg_type++;
3444     target_size = thunk_type_size(arg_type, 0);
3445     argptr = lock_user(VERIFY_READ, arg, target_size, 1);
3446     if (!argptr) {
3447         ret = -TARGET_EFAULT;
3448         goto out;
3449     }
3450     thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
3451     unlock_user(argptr, arg, 0);
3452
3453     /* buf_temp is too small, so fetch things into a bigger buffer */
3454     big_buf = g_malloc0(((struct dm_ioctl*)buf_temp)->data_size * 2);
3455     memcpy(big_buf, buf_temp, target_size);
3456     buf_temp = big_buf;
3457     host_dm = big_buf;
3458
3459     guest_data = arg + host_dm->data_start;
3460     if ((guest_data - arg) < 0) {
3461         ret = -EINVAL;
3462         goto out;
3463     }
3464     guest_data_size = host_dm->data_size - host_dm->data_start;
3465     host_data = (char*)host_dm + host_dm->data_start;
3466
3467     argptr = lock_user(VERIFY_READ, guest_data, guest_data_size, 1);
3468     switch (ie->host_cmd) {
3469     case DM_REMOVE_ALL:
3470     case DM_LIST_DEVICES:
3471     case DM_DEV_CREATE:
3472     case DM_DEV_REMOVE:
3473     case DM_DEV_SUSPEND:
3474     case DM_DEV_STATUS:
3475     case DM_DEV_WAIT:
3476     case DM_TABLE_STATUS:
3477     case DM_TABLE_CLEAR:
3478     case DM_TABLE_DEPS:
3479     case DM_LIST_VERSIONS:
3480         /* no input data */
3481         break;
3482     case DM_DEV_RENAME:
3483     case DM_DEV_SET_GEOMETRY:
3484         /* data contains only strings */
3485         memcpy(host_data, argptr, guest_data_size);
3486         break;
3487     case DM_TARGET_MSG:
3488         memcpy(host_data, argptr, guest_data_size);
3489         *(uint64_t*)host_data = tswap64(*(uint64_t*)argptr);
3490         break;
3491     case DM_TABLE_LOAD:
3492     {
3493         void *gspec = argptr;
3494         void *cur_data = host_data;
3495         const argtype arg_type[] = { MK_STRUCT(STRUCT_dm_target_spec) };
3496         int spec_size = thunk_type_size(arg_type, 0);
3497         int i;
3498
3499         for (i = 0; i < host_dm->target_count; i++) {
3500             struct dm_target_spec *spec = cur_data;
3501             uint32_t next;
3502             int slen;
3503
3504             thunk_convert(spec, gspec, arg_type, THUNK_HOST);
3505             slen = strlen((char*)gspec + spec_size) + 1;
3506             next = spec->next;
3507             spec->next = sizeof(*spec) + slen;
3508             strcpy((char*)&spec[1], gspec + spec_size);
3509             gspec += next;
3510             cur_data += spec->next;
3511         }
3512         break;
3513     }
3514     default:
3515         ret = -TARGET_EINVAL;
3516         goto out;
3517     }
3518     unlock_user(argptr, guest_data, 0);
3519
3520     ret = get_errno(ioctl(fd, ie->host_cmd, buf_temp));
3521     if (!is_error(ret)) {
3522         guest_data = arg + host_dm->data_start;
3523         guest_data_size = host_dm->data_size - host_dm->data_start;
3524         argptr = lock_user(VERIFY_WRITE, guest_data, guest_data_size, 0);
3525         switch (ie->host_cmd) {
3526         case DM_REMOVE_ALL:
3527         case DM_DEV_CREATE:
3528         case DM_DEV_REMOVE:
3529         case DM_DEV_RENAME:
3530         case DM_DEV_SUSPEND:
3531         case DM_DEV_STATUS:
3532         case DM_TABLE_LOAD:
3533         case DM_TABLE_CLEAR:
3534         case DM_TARGET_MSG:
3535         case DM_DEV_SET_GEOMETRY:
3536             /* no return data */
3537             break;
3538         case DM_LIST_DEVICES:
3539         {
3540             struct dm_name_list *nl = (void*)host_dm + host_dm->data_start;
3541             uint32_t remaining_data = guest_data_size;
3542             void *cur_data = argptr;
3543             const argtype arg_type[] = { MK_STRUCT(STRUCT_dm_name_list) };
3544             int nl_size = 12; /* can't use thunk_size due to alignment */
3545
3546             while (1) {
3547                 uint32_t next = nl->next;
3548                 if (next) {
3549                     nl->next = nl_size + (strlen(nl->name) + 1);
3550                 }
3551                 if (remaining_data < nl->next) {
3552                     host_dm->flags |= DM_BUFFER_FULL_FLAG;
3553                     break;
3554                 }
3555                 thunk_convert(cur_data, nl, arg_type, THUNK_TARGET);
3556                 strcpy(cur_data + nl_size, nl->name);
3557                 cur_data += nl->next;
3558                 remaining_data -= nl->next;
3559                 if (!next) {
3560                     break;
3561                 }
3562                 nl = (void*)nl + next;
3563             }
3564             break;
3565         }
3566         case DM_DEV_WAIT:
3567         case DM_TABLE_STATUS:
3568         {
3569             struct dm_target_spec *spec = (void*)host_dm + host_dm->data_start;
3570             void *cur_data = argptr;
3571             const argtype arg_type[] = { MK_STRUCT(STRUCT_dm_target_spec) };
3572             int spec_size = thunk_type_size(arg_type, 0);
3573             int i;
3574
3575             for (i = 0; i < host_dm->target_count; i++) {
3576                 uint32_t next = spec->next;
3577                 int slen = strlen((char*)&spec[1]) + 1;
3578                 spec->next = (cur_data - argptr) + spec_size + slen;
3579                 if (guest_data_size < spec->next) {
3580                     host_dm->flags |= DM_BUFFER_FULL_FLAG;
3581                     break;
3582                 }
3583                 thunk_convert(cur_data, spec, arg_type, THUNK_TARGET);
3584                 strcpy(cur_data + spec_size, (char*)&spec[1]);
3585                 cur_data = argptr + spec->next;
3586                 spec = (void*)host_dm + host_dm->data_start + next;
3587             }
3588             break;
3589         }
3590         case DM_TABLE_DEPS:
3591         {
3592             void *hdata = (void*)host_dm + host_dm->data_start;
3593             int count = *(uint32_t*)hdata;
3594             uint64_t *hdev = hdata + 8;
3595             uint64_t *gdev = argptr + 8;
3596             int i;
3597
3598             *(uint32_t*)argptr = tswap32(count);
3599             for (i = 0; i < count; i++) {
3600                 *gdev = tswap64(*hdev);
3601                 gdev++;
3602                 hdev++;
3603             }
3604             break;
3605         }
3606         case DM_LIST_VERSIONS:
3607         {
3608             struct dm_target_versions *vers = (void*)host_dm + host_dm->data_start;
3609             uint32_t remaining_data = guest_data_size;
3610             void *cur_data = argptr;
3611             const argtype arg_type[] = { MK_STRUCT(STRUCT_dm_target_versions) };
3612             int vers_size = thunk_type_size(arg_type, 0);
3613
3614             while (1) {
3615                 uint32_t next = vers->next;
3616                 if (next) {
3617                     vers->next = vers_size + (strlen(vers->name) + 1);
3618                 }
3619                 if (remaining_data < vers->next) {
3620                     host_dm->flags |= DM_BUFFER_FULL_FLAG;
3621                     break;
3622                 }
3623                 thunk_convert(cur_data, vers, arg_type, THUNK_TARGET);
3624                 strcpy(cur_data + vers_size, vers->name);
3625                 cur_data += vers->next;
3626                 remaining_data -= vers->next;
3627                 if (!next) {
3628                     break;
3629                 }
3630                 vers = (void*)vers + next;
3631             }
3632             break;
3633         }
3634         default:
3635             ret = -TARGET_EINVAL;
3636             goto out;
3637         }
3638         unlock_user(argptr, guest_data, guest_data_size);
3639
3640         argptr = lock_user(VERIFY_WRITE, arg, target_size, 0);
3641         if (!argptr) {
3642             ret = -TARGET_EFAULT;
3643             goto out;
3644         }
3645         thunk_convert(argptr, buf_temp, arg_type, THUNK_TARGET);
3646         unlock_user(argptr, arg, target_size);
3647     }
3648 out:
3649     g_free(big_buf);
3650     return ret;
3651 }
3652
3653 static abi_long do_ioctl_rt(const IOCTLEntry *ie, uint8_t *buf_temp,
3654                                 int fd, abi_long cmd, abi_long arg)
3655 {
3656     const argtype *arg_type = ie->arg_type;
3657     const StructEntry *se;
3658     const argtype *field_types;
3659     const int *dst_offsets, *src_offsets;
3660     int target_size;
3661     void *argptr;
3662     abi_ulong *target_rt_dev_ptr;
3663     unsigned long *host_rt_dev_ptr;
3664     abi_long ret;
3665     int i;
3666
3667     assert(ie->access == IOC_W);
3668     assert(*arg_type == TYPE_PTR);
3669     arg_type++;
3670     assert(*arg_type == TYPE_STRUCT);
3671     target_size = thunk_type_size(arg_type, 0);
3672     argptr = lock_user(VERIFY_READ, arg, target_size, 1);
3673     if (!argptr) {
3674         return -TARGET_EFAULT;
3675     }
3676     arg_type++;
3677     assert(*arg_type == (int)STRUCT_rtentry);
3678     se = struct_entries + *arg_type++;
3679     assert(se->convert[0] == NULL);
3680     /* convert struct here to be able to catch rt_dev string */
3681     field_types = se->field_types;
3682     dst_offsets = se->field_offsets[THUNK_HOST];
3683     src_offsets = se->field_offsets[THUNK_TARGET];
3684     for (i = 0; i < se->nb_fields; i++) {
3685         if (dst_offsets[i] == offsetof(struct rtentry, rt_dev)) {
3686             assert(*field_types == TYPE_PTRVOID);
3687             target_rt_dev_ptr = (abi_ulong *)(argptr + src_offsets[i]);
3688             host_rt_dev_ptr = (unsigned long *)(buf_temp + dst_offsets[i]);
3689             if (*target_rt_dev_ptr != 0) {
3690                 *host_rt_dev_ptr = (unsigned long)lock_user_string(
3691                                                   tswapal(*target_rt_dev_ptr));
3692                 if (!*host_rt_dev_ptr) {
3693                     unlock_user(argptr, arg, 0);
3694                     return -TARGET_EFAULT;
3695                 }
3696             } else {
3697                 *host_rt_dev_ptr = 0;
3698             }
3699             field_types++;
3700             continue;
3701         }
3702         field_types = thunk_convert(buf_temp + dst_offsets[i],
3703                                     argptr + src_offsets[i],
3704                                     field_types, THUNK_HOST);
3705     }
3706     unlock_user(argptr, arg, 0);
3707
3708     ret = get_errno(ioctl(fd, ie->host_cmd, buf_temp));
3709     if (*host_rt_dev_ptr != 0) {
3710         unlock_user((void *)*host_rt_dev_ptr,
3711                     *target_rt_dev_ptr, 0);
3712     }
3713     return ret;
3714 }
3715
3716 static abi_long do_ioctl_kdsigaccept(const IOCTLEntry *ie, uint8_t *buf_temp,
3717                                      int fd, abi_long cmd, abi_long arg)
3718 {
3719     int sig = target_to_host_signal(arg);
3720     return get_errno(ioctl(fd, ie->host_cmd, sig));
3721 }
3722
3723 static IOCTLEntry ioctl_entries[] = {
3724 #define IOCTL(cmd, access, ...) \
3725     { TARGET_ ## cmd, cmd, #cmd, access, 0, {  __VA_ARGS__ } },
3726 #define IOCTL_SPECIAL(cmd, access, dofn, ...)                      \
3727     { TARGET_ ## cmd, cmd, #cmd, access, dofn, {  __VA_ARGS__ } },
3728 #include "ioctls.h"
3729     { 0, 0, },
3730 };
3731
3732 /* ??? Implement proper locking for ioctls.  */
3733 /* do_ioctl() Must return target values and target errnos. */
3734 static abi_long do_ioctl(int fd, abi_long cmd, abi_long arg)
3735 {
3736     const IOCTLEntry *ie;
3737     const argtype *arg_type;
3738     abi_long ret;
3739     uint8_t buf_temp[MAX_STRUCT_SIZE];
3740     int target_size;
3741     void *argptr;
3742
3743     ie = ioctl_entries;
3744     for(;;) {
3745         if (ie->target_cmd == 0) {
3746             gemu_log("Unsupported ioctl: cmd=0x%04lx\n", (long)cmd);
3747             return -TARGET_ENOSYS;
3748         }
3749         if (ie->target_cmd == cmd)
3750             break;
3751         ie++;
3752     }
3753     arg_type = ie->arg_type;
3754 #if defined(DEBUG)
3755     gemu_log("ioctl: cmd=0x%04lx (%s)\n", (long)cmd, ie->name);
3756 #endif
3757     if (ie->do_ioctl) {
3758         return ie->do_ioctl(ie, buf_temp, fd, cmd, arg);
3759     }
3760
3761     switch(arg_type[0]) {
3762     case TYPE_NULL:
3763         /* no argument */
3764         ret = get_errno(ioctl(fd, ie->host_cmd));
3765         break;
3766     case TYPE_PTRVOID:
3767     case TYPE_INT:
3768         /* int argment */
3769         ret = get_errno(ioctl(fd, ie->host_cmd, arg));
3770         break;
3771     case TYPE_PTR:
3772         arg_type++;
3773         target_size = thunk_type_size(arg_type, 0);
3774         switch(ie->access) {
3775         case IOC_R:
3776             ret = get_errno(ioctl(fd, ie->host_cmd, buf_temp));
3777             if (!is_error(ret)) {
3778                 argptr = lock_user(VERIFY_WRITE, arg, target_size, 0);
3779                 if (!argptr)
3780                     return -TARGET_EFAULT;
3781                 thunk_convert(argptr, buf_temp, arg_type, THUNK_TARGET);
3782                 unlock_user(argptr, arg, target_size);
3783             }
3784             break;
3785         case IOC_W:
3786             argptr = lock_user(VERIFY_READ, arg, target_size, 1);
3787             if (!argptr)
3788                 return -TARGET_EFAULT;
3789             thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
3790             unlock_user(argptr, arg, 0);
3791             ret = get_errno(ioctl(fd, ie->host_cmd, buf_temp));
3792             break;
3793         default:
3794         case IOC_RW:
3795             argptr = lock_user(VERIFY_READ, arg, target_size, 1);
3796             if (!argptr)
3797                 return -TARGET_EFAULT;
3798             thunk_convert(buf_temp, argptr, arg_type, THUNK_HOST);
3799             unlock_user(argptr, arg, 0);
3800             ret = get_errno(ioctl(fd, ie->host_cmd, buf_temp));
3801             if (!is_error(ret)) {
3802                 argptr = lock_user(VERIFY_WRITE, arg, target_size, 0);
3803                 if (!argptr)
3804                     return -TARGET_EFAULT;
3805                 thunk_convert(argptr, buf_temp, arg_type, THUNK_TARGET);
3806                 unlock_user(argptr, arg, target_size);
3807             }
3808             break;
3809         }
3810         break;
3811     default:
3812         gemu_log("Unsupported ioctl type: cmd=0x%04lx type=%d\n",
3813                  (long)cmd, arg_type[0]);
3814         ret = -TARGET_ENOSYS;
3815         break;
3816     }
3817     return ret;
3818 }
3819
3820 static const bitmask_transtbl iflag_tbl[] = {
3821         { TARGET_IGNBRK, TARGET_IGNBRK, IGNBRK, IGNBRK },
3822         { TARGET_BRKINT, TARGET_BRKINT, BRKINT, BRKINT },
3823         { TARGET_IGNPAR, TARGET_IGNPAR, IGNPAR, IGNPAR },
3824         { TARGET_PARMRK, TARGET_PARMRK, PARMRK, PARMRK },
3825         { TARGET_INPCK, TARGET_INPCK, INPCK, INPCK },
3826         { TARGET_ISTRIP, TARGET_ISTRIP, ISTRIP, ISTRIP },
3827         { TARGET_INLCR, TARGET_INLCR, INLCR, INLCR },
3828         { TARGET_IGNCR, TARGET_IGNCR, IGNCR, IGNCR },
3829         { TARGET_ICRNL, TARGET_ICRNL, ICRNL, ICRNL },
3830         { TARGET_IUCLC, TARGET_IUCLC, IUCLC, IUCLC },
3831         { TARGET_IXON, TARGET_IXON, IXON, IXON },
3832         { TARGET_IXANY, TARGET_IXANY, IXANY, IXANY },
3833         { TARGET_IXOFF, TARGET_IXOFF, IXOFF, IXOFF },
3834         { TARGET_IMAXBEL, TARGET_IMAXBEL, IMAXBEL, IMAXBEL },
3835         { 0, 0, 0, 0 }
3836 };
3837
3838 static const bitmask_transtbl oflag_tbl[] = {
3839         { TARGET_OPOST, TARGET_OPOST, OPOST, OPOST },
3840         { TARGET_OLCUC, TARGET_OLCUC, OLCUC, OLCUC },
3841         { TARGET_ONLCR, TARGET_ONLCR, ONLCR, ONLCR },
3842         { TARGET_OCRNL, TARGET_OCRNL, OCRNL, OCRNL },
3843         { TARGET_ONOCR, TARGET_ONOCR, ONOCR, ONOCR },
3844         { TARGET_ONLRET, TARGET_ONLRET, ONLRET, ONLRET },
3845         { TARGET_OFILL, TARGET_OFILL, OFILL, OFILL },
3846         { TARGET_OFDEL, TARGET_OFDEL, OFDEL, OFDEL },
3847         { TARGET_NLDLY, TARGET_NL0, NLDLY, NL0 },
3848         { TARGET_NLDLY, TARGET_NL1, NLDLY, NL1 },
3849         { TARGET_CRDLY, TARGET_CR0, CRDLY, CR0 },
3850         { TARGET_CRDLY, TARGET_CR1, CRDLY, CR1 },
3851         { TARGET_CRDLY, TARGET_CR2, CRDLY, CR2 },
3852         { TARGET_CRDLY, TARGET_CR3, CRDLY, CR3 },
3853         { TARGET_TABDLY, TARGET_TAB0, TABDLY, TAB0 },
3854         { TARGET_TABDLY, TARGET_TAB1, TABDLY, TAB1 },
3855         { TARGET_TABDLY, TARGET_TAB2, TABDLY, TAB2 },
3856         { TARGET_TABDLY, TARGET_TAB3, TABDLY, TAB3 },
3857         { TARGET_BSDLY, TARGET_BS0, BSDLY, BS0 },
3858         { TARGET_BSDLY, TARGET_BS1, BSDLY, BS1 },
3859         { TARGET_VTDLY, TARGET_VT0, VTDLY, VT0 },
3860         { TARGET_VTDLY, TARGET_VT1, VTDLY, VT1 },
3861         { TARGET_FFDLY, TARGET_FF0, FFDLY, FF0 },
3862         { TARGET_FFDLY, TARGET_FF1, FFDLY, FF1 },
3863         { 0, 0, 0, 0 }
3864 };
3865
3866 static const bitmask_transtbl cflag_tbl[] = {
3867         { TARGET_CBAUD, TARGET_B0, CBAUD, B0 },
3868         { TARGET_CBAUD, TARGET_B50, CBAUD, B50 },
3869         { TARGET_CBAUD, TARGET_B75, CBAUD, B75 },
3870         { TARGET_CBAUD, TARGET_B110, CBAUD, B110 },
3871         { TARGET_CBAUD, TARGET_B134, CBAUD, B134 },
3872         { TARGET_CBAUD, TARGET_B150, CBAUD, B150 },
3873         { TARGET_CBAUD, TARGET_B200, CBAUD, B200 },
3874         { TARGET_CBAUD, TARGET_B300, CBAUD, B300 },
3875         { TARGET_CBAUD, TARGET_B600, CBAUD, B600 },
3876         { TARGET_CBAUD, TARGET_B1200, CBAUD, B1200 },
3877         { TARGET_CBAUD, TARGET_B1800, CBAUD, B1800 },
3878         { TARGET_CBAUD, TARGET_B2400, CBAUD, B2400 },
3879         { TARGET_CBAUD, TARGET_B4800, CBAUD, B4800 },
3880         { TARGET_CBAUD, TARGET_B9600, CBAUD, B9600 },
3881         { TARGET_CBAUD, TARGET_B19200, CBAUD, B19200 },
3882         { TARGET_CBAUD, TARGET_B38400, CBAUD, B38400 },
3883         { TARGET_CBAUD, TARGET_B57600, CBAUD, B57600 },
3884         { TARGET_CBAUD, TARGET_B115200, CBAUD, B115200 },
3885         { TARGET_CBAUD, TARGET_B230400, CBAUD, B230400 },
3886         { TARGET_CBAUD, TARGET_B460800, CBAUD, B460800 },
3887         { TARGET_CSIZE, TARGET_CS5, CSIZE, CS5 },
3888         { TARGET_CSIZE, TARGET_CS6, CSIZE, CS6 },
3889         { TARGET_CSIZE, TARGET_CS7, CSIZE, CS7 },
3890         { TARGET_CSIZE, TARGET_CS8, CSIZE, CS8 },
3891         { TARGET_CSTOPB, TARGET_CSTOPB, CSTOPB, CSTOPB },
3892         { TARGET_CREAD, TARGET_CREAD, CREAD, CREAD },
3893         { TARGET_PARENB, TARGET_PARENB, PARENB, PARENB },
3894         { TARGET_PARODD, TARGET_PARODD, PARODD, PARODD },
3895         { TARGET_HUPCL, TARGET_HUPCL, HUPCL, HUPCL },
3896         { TARGET_CLOCAL, TARGET_CLOCAL, CLOCAL, CLOCAL },
3897         { TARGET_CRTSCTS, TARGET_CRTSCTS, CRTSCTS, CRTSCTS },
3898         { 0, 0, 0, 0 }
3899 };
3900
3901 static const bitmask_transtbl lflag_tbl[] = {
3902         { TARGET_ISIG, TARGET_ISIG, ISIG, ISIG },
3903         { TARGET_ICANON, TARGET_ICANON, ICANON, ICANON },
3904         { TARGET_XCASE, TARGET_XCASE, XCASE, XCASE },
3905         { TARGET_ECHO, TARGET_ECHO, ECHO, ECHO },
3906         { TARGET_ECHOE, TARGET_ECHOE, ECHOE, ECHOE },
3907         { TARGET_ECHOK, TARGET_ECHOK, ECHOK, ECHOK },
3908         { TARGET_ECHONL, TARGET_ECHONL, ECHONL, ECHONL },
3909         { TARGET_NOFLSH, TARGET_NOFLSH, NOFLSH, NOFLSH },
3910         { TARGET_TOSTOP, TARGET_TOSTOP, TOSTOP, TOSTOP },
3911         { TARGET_ECHOCTL, TARGET_ECHOCTL, ECHOCTL, ECHOCTL },
3912         { TARGET_ECHOPRT, TARGET_ECHOPRT, ECHOPRT, ECHOPRT },
3913         { TARGET_ECHOKE, TARGET_ECHOKE, ECHOKE, ECHOKE },
3914         { TARGET_FLUSHO, TARGET_FLUSHO, FLUSHO, FLUSHO },
3915         { TARGET_PENDIN, TARGET_PENDIN, PENDIN, PENDIN },
3916         { TARGET_IEXTEN, TARGET_IEXTEN, IEXTEN, IEXTEN },
3917         { 0, 0, 0, 0 }
3918 };
3919
3920 static void target_to_host_termios (void *dst, const void *src)
3921 {
3922     struct host_termios *host = dst;
3923     const struct target_termios *target = src;
3924
3925     host->c_iflag =
3926         target_to_host_bitmask(tswap32(target->c_iflag), iflag_tbl);
3927     host->c_oflag =
3928         target_to_host_bitmask(tswap32(target->c_oflag), oflag_tbl);
3929     host->c_cflag =
3930         target_to_host_bitmask(tswap32(target->c_cflag), cflag_tbl);
3931     host->c_lflag =
3932         target_to_host_bitmask(tswap32(target->c_lflag), lflag_tbl);
3933     host->c_line = target->c_line;
3934
3935     memset(host->c_cc, 0, sizeof(host->c_cc));
3936     host->c_cc[VINTR] = target->c_cc[TARGET_VINTR];
3937     host->c_cc[VQUIT] = target->c_cc[TARGET_VQUIT];
3938     host->c_cc[VERASE] = target->c_cc[TARGET_VERASE];
3939     host->c_cc[VKILL] = target->c_cc[TARGET_VKILL];
3940     host->c_cc[VEOF] = target->c_cc[TARGET_VEOF];
3941     host->c_cc[VTIME] = target->c_cc[TARGET_VTIME];
3942     host->c_cc[VMIN] = target->c_cc[TARGET_VMIN];
3943     host->c_cc[VSWTC] = target->c_cc[TARGET_VSWTC];
3944     host->c_cc[VSTART] = target->c_cc[TARGET_VSTART];
3945     host->c_cc[VSTOP] = target->c_cc[TARGET_VSTOP];
3946     host->c_cc[VSUSP] = target->c_cc[TARGET_VSUSP];
3947     host->c_cc[VEOL] = target->c_cc[TARGET_VEOL];
3948     host->c_cc[VREPRINT] = target->c_cc[TARGET_VREPRINT];
3949     host->c_cc[VDISCARD] = target->c_cc[TARGET_VDISCARD];
3950     host->c_cc[VWERASE] = target->c_cc[TARGET_VWERASE];
3951     host->c_cc[VLNEXT] = target->c_cc[TARGET_VLNEXT];
3952     host->c_cc[VEOL2] = target->c_cc[TARGET_VEOL2];
3953 }
3954
3955 static void host_to_target_termios (void *dst, const void *src)
3956 {
3957     struct target_termios *target = dst;
3958     const struct host_termios *host = src;
3959
3960     target->c_iflag =
3961         tswap32(host_to_target_bitmask(host->c_iflag, iflag_tbl));
3962     target->c_oflag =
3963         tswap32(host_to_target_bitmask(host->c_oflag, oflag_tbl));
3964     target->c_cflag =
3965         tswap32(host_to_target_bitmask(host->c_cflag, cflag_tbl));
3966     target->c_lflag =
3967         tswap32(host_to_target_bitmask(host->c_lflag, lflag_tbl));
3968     target->c_line = host->c_line;
3969
3970     memset(target->c_cc, 0, sizeof(target->c_cc));
3971     target->c_cc[TARGET_VINTR] = host->c_cc[VINTR];
3972     target->c_cc[TARGET_VQUIT] = host->c_cc[VQUIT];
3973     target->c_cc[TARGET_VERASE] = host->c_cc[VERASE];
3974     target->c_cc[TARGET_VKILL] = host->c_cc[VKILL];
3975     target->c_cc[TARGET_VEOF] = host->c_cc[VEOF];
3976     target->c_cc[TARGET_VTIME] = host->c_cc[VTIME];
3977     target->c_cc[TARGET_VMIN] = host->c_cc[VMIN];
3978     target->c_cc[TARGET_VSWTC] = host->c_cc[VSWTC];
3979     target->c_cc[TARGET_VSTART] = host->c_cc[VSTART];
3980     target->c_cc[TARGET_VSTOP] = host->c_cc[VSTOP];
3981     target->c_cc[TARGET_VSUSP] = host->c_cc[VSUSP];
3982     target->c_cc[TARGET_VEOL] = host->c_cc[VEOL];
3983     target->c_cc[TARGET_VREPRINT] = host->c_cc[VREPRINT];
3984     target->c_cc[TARGET_VDISCARD] = host->c_cc[VDISCARD];
3985     target->c_cc[TARGET_VWERASE] = host->c_cc[VWERASE];
3986     target->c_cc[TARGET_VLNEXT] = host->c_cc[VLNEXT];
3987     target->c_cc[TARGET_VEOL2] = host->c_cc[VEOL2];
3988 }
3989
3990 static const StructEntry struct_termios_def = {
3991     .convert = { host_to_target_termios, target_to_host_termios },
3992     .size = { sizeof(struct target_termios), sizeof(struct host_termios) },
3993     .align = { __alignof__(struct target_termios), __alignof__(struct host_termios) },
3994 };
3995
3996 static bitmask_transtbl mmap_flags_tbl[] = {
3997         { TARGET_MAP_SHARED, TARGET_MAP_SHARED, MAP_SHARED, MAP_SHARED },
3998         { TARGET_MAP_PRIVATE, TARGET_MAP_PRIVATE, MAP_PRIVATE, MAP_PRIVATE },
3999         { TARGET_MAP_FIXED, TARGET_MAP_FIXED, MAP_FIXED, MAP_FIXED },
4000         { TARGET_MAP_ANONYMOUS, TARGET_MAP_ANONYMOUS, MAP_ANONYMOUS, MAP_ANONYMOUS },
4001         { TARGET_MAP_GROWSDOWN, TARGET_MAP_GROWSDOWN, MAP_GROWSDOWN, MAP_GROWSDOWN },
4002         { TARGET_MAP_DENYWRITE, TARGET_MAP_DENYWRITE, MAP_DENYWRITE, MAP_DENYWRITE },
4003         { TARGET_MAP_EXECUTABLE, TARGET_MAP_EXECUTABLE, MAP_EXECUTABLE, MAP_EXECUTABLE },
4004         { TARGET_MAP_LOCKED, TARGET_MAP_LOCKED, MAP_LOCKED, MAP_LOCKED },
4005         { TARGET_MAP_NORESERVE, TARGET_MAP_NORESERVE, MAP_NORESERVE,
4006           MAP_NORESERVE },
4007         { 0, 0, 0, 0 }
4008 };
4009
4010 #if defined(TARGET_I386)
4011
4012 /* NOTE: there is really one LDT for all the threads */
4013 static uint8_t *ldt_table;
4014
4015 static abi_long read_ldt(abi_ulong ptr, unsigned long bytecount)
4016 {
4017     int size;
4018     void *p;
4019
4020     if (!ldt_table)
4021         return 0;
4022     size = TARGET_LDT_ENTRIES * TARGET_LDT_ENTRY_SIZE;
4023     if (size > bytecount)
4024         size = bytecount;
4025     p = lock_user(VERIFY_WRITE, ptr, size, 0);
4026     if (!p)
4027         return -TARGET_EFAULT;
4028     /* ??? Should this by byteswapped?  */
4029     memcpy(p, ldt_table, size);
4030     unlock_user(p, ptr, size);
4031     return size;
4032 }
4033
4034 /* XXX: add locking support */
4035 static abi_long write_ldt(CPUX86State *env,
4036                           abi_ulong ptr, unsigned long bytecount, int oldmode)
4037 {
4038     struct target_modify_ldt_ldt_s ldt_info;
4039     struct target_modify_ldt_ldt_s *target_ldt_info;
4040     int seg_32bit, contents, read_exec_only, limit_in_pages;
4041     int seg_not_present, useable, lm;
4042     uint32_t *lp, entry_1, entry_2;
4043
4044     if (bytecount != sizeof(ldt_info))
4045         return -TARGET_EINVAL;
4046     if (!lock_user_struct(VERIFY_READ, target_ldt_info, ptr, 1))
4047         return -TARGET_EFAULT;
4048     ldt_info.entry_number = tswap32(target_ldt_info->entry_number);
4049     ldt_info.base_addr = tswapal(target_ldt_info->base_addr);
4050     ldt_info.limit = tswap32(target_ldt_info->limit);
4051     ldt_info.flags = tswap32(target_ldt_info->flags);
4052     unlock_user_struct(target_ldt_info, ptr, 0);
4053
4054     if (ldt_info.entry_number >= TARGET_LDT_ENTRIES)
4055         return -TARGET_EINVAL;
4056     seg_32bit = ldt_info.flags & 1;
4057     contents = (ldt_info.flags >> 1) & 3;
4058     read_exec_only = (ldt_info.flags >> 3) & 1;
4059     limit_in_pages = (ldt_info.flags >> 4) & 1;
4060     seg_not_present = (ldt_info.flags >> 5) & 1;
4061     useable = (ldt_info.flags >> 6) & 1;
4062 #ifdef TARGET_ABI32
4063     lm = 0;
4064 #else
4065     lm = (ldt_info.flags >> 7) & 1;
4066 #endif
4067     if (contents == 3) {
4068         if (oldmode)
4069             return -TARGET_EINVAL;
4070         if (seg_not_present == 0)
4071             return -TARGET_EINVAL;
4072     }
4073     /* allocate the LDT */
4074     if (!ldt_table) {
4075         env->ldt.base = target_mmap(0,
4076                                     TARGET_LDT_ENTRIES * TARGET_LDT_ENTRY_SIZE,
4077                                     PROT_READ|PROT_WRITE,
4078                                     MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
4079         if (env->ldt.base == -1)
4080             return -TARGET_ENOMEM;
4081         memset(g2h(env->ldt.base), 0,
4082                TARGET_LDT_ENTRIES * TARGET_LDT_ENTRY_SIZE);
4083         env->ldt.limit = 0xffff;
4084         ldt_table = g2h(env->ldt.base);
4085     }
4086
4087     /* NOTE: same code as Linux kernel */
4088     /* Allow LDTs to be cleared by the user. */
4089     if (ldt_info.base_addr == 0 && ldt_info.limit == 0) {
4090         if (oldmode ||
4091             (contents == 0              &&
4092              read_exec_only == 1        &&
4093              seg_32bit == 0             &&
4094              limit_in_pages == 0        &&
4095              seg_not_present == 1       &&
4096              useable == 0 )) {
4097             entry_1 = 0;
4098             entry_2 = 0;
4099             goto install;
4100         }
4101     }
4102
4103     entry_1 = ((ldt_info.base_addr & 0x0000ffff) << 16) |
4104         (ldt_info.limit & 0x0ffff);
4105     entry_2 = (ldt_info.base_addr & 0xff000000) |
4106         ((ldt_info.base_addr & 0x00ff0000) >> 16) |
4107         (ldt_info.limit & 0xf0000) |
4108         ((read_exec_only ^ 1) << 9) |
4109         (contents << 10) |
4110         ((seg_not_present ^ 1) << 15) |
4111         (seg_32bit << 22) |
4112         (limit_in_pages << 23) |
4113         (lm << 21) |
4114         0x7000;
4115     if (!oldmode)
4116         entry_2 |= (useable << 20);
4117
4118     /* Install the new entry ...  */
4119 install:
4120     lp = (uint32_t *)(ldt_table + (ldt_info.entry_number << 3));
4121     lp[0] = tswap32(entry_1);
4122     lp[1] = tswap32(entry_2);
4123     return 0;
4124 }
4125
4126 /* specific and weird i386 syscalls */
4127 static abi_long do_modify_ldt(CPUX86State *env, int func, abi_ulong ptr,
4128                               unsigned long bytecount)
4129 {
4130     abi_long ret;
4131
4132     switch (func) {
4133     case 0:
4134         ret = read_ldt(ptr, bytecount);
4135         break;
4136     case 1:
4137         ret = write_ldt(env, ptr, bytecount, 1);
4138         break;
4139     case 0x11:
4140         ret = write_ldt(env, ptr, bytecount, 0);
4141         break;
4142     default:
4143         ret = -TARGET_ENOSYS;
4144         break;
4145     }
4146     return ret;
4147 }
4148
4149 #if defined(TARGET_I386) && defined(TARGET_ABI32)
4150 abi_long do_set_thread_area(CPUX86State *env, abi_ulong ptr)
4151 {
4152     uint64_t *gdt_table = g2h(env->gdt.base);
4153     struct target_modify_ldt_ldt_s ldt_info;
4154     struct target_modify_ldt_ldt_s *target_ldt_info;
4155     int seg_32bit, contents, read_exec_only, limit_in_pages;
4156     int seg_not_present, useable, lm;
4157     uint32_t *lp, entry_1, entry_2;
4158     int i;
4159
4160     lock_user_struct(VERIFY_WRITE, target_ldt_info, ptr, 1);
4161     if (!target_ldt_info)
4162         return -TARGET_EFAULT;
4163     ldt_info.entry_number = tswap32(target_ldt_info->entry_number);
4164     ldt_info.base_addr = tswapal(target_ldt_info->base_addr);
4165     ldt_info.limit = tswap32(target_ldt_info->limit);
4166     ldt_info.flags = tswap32(target_ldt_info->flags);
4167     if (ldt_info.entry_number == -1) {
4168         for (i=TARGET_GDT_ENTRY_TLS_MIN; i<=TARGET_GDT_ENTRY_TLS_MAX; i++) {
4169             if (gdt_table[i] == 0) {
4170                 ldt_info.entry_number = i;
4171                 target_ldt_info->entry_number = tswap32(i);
4172                 break;
4173             }
4174         }
4175     }
4176     unlock_user_struct(target_ldt_info, ptr, 1);
4177
4178     if (ldt_info.entry_number < TARGET_GDT_ENTRY_TLS_MIN || 
4179         ldt_info.entry_number > TARGET_GDT_ENTRY_TLS_MAX)
4180            return -TARGET_EINVAL;
4181     seg_32bit = ldt_info.flags & 1;
4182     contents = (ldt_info.flags >> 1) & 3;
4183     read_exec_only = (ldt_info.flags >> 3) & 1;
4184     limit_in_pages = (ldt_info.flags >> 4) & 1;
4185     seg_not_present = (ldt_info.flags >> 5) & 1;
4186     useable = (ldt_info.flags >> 6) & 1;
4187 #ifdef TARGET_ABI32
4188     lm = 0;
4189 #else
4190     lm = (ldt_info.flags >> 7) & 1;
4191 #endif
4192
4193     if (contents == 3) {
4194         if (seg_not_present == 0)
4195             return -TARGET_EINVAL;
4196     }
4197
4198     /* NOTE: same code as Linux kernel */
4199     /* Allow LDTs to be cleared by the user. */
4200     if (ldt_info.base_addr == 0 && ldt_info.limit == 0) {
4201         if ((contents == 0             &&
4202              read_exec_only == 1       &&
4203              seg_32bit == 0            &&
4204              limit_in_pages == 0       &&
4205              seg_not_present == 1      &&
4206              useable == 0 )) {
4207             entry_1 = 0;
4208             entry_2 = 0;
4209             goto install;
4210         }
4211     }
4212
4213     entry_1 = ((ldt_info.base_addr & 0x0000ffff) << 16) |
4214         (ldt_info.limit & 0x0ffff);
4215     entry_2 = (ldt_info.base_addr & 0xff000000) |
4216         ((ldt_info.base_addr & 0x00ff0000) >> 16) |
4217         (ldt_info.limit & 0xf0000) |
4218         ((read_exec_only ^ 1) << 9) |
4219         (contents << 10) |
4220         ((seg_not_present ^ 1) << 15) |
4221         (seg_32bit << 22) |
4222         (limit_in_pages << 23) |
4223         (useable << 20) |
4224         (lm << 21) |
4225         0x7000;
4226
4227     /* Install the new entry ...  */
4228 install:
4229     lp = (uint32_t *)(gdt_table + ldt_info.entry_number);
4230     lp[0] = tswap32(entry_1);
4231     lp[1] = tswap32(entry_2);
4232     return 0;
4233 }
4234
4235 static abi_long do_get_thread_area(CPUX86State *env, abi_ulong ptr)
4236 {
4237     struct target_modify_ldt_ldt_s *target_ldt_info;
4238     uint64_t *gdt_table = g2h(env->gdt.base);
4239     uint32_t base_addr, limit, flags;
4240     int seg_32bit, contents, read_exec_only, limit_in_pages, idx;
4241     int seg_not_present, useable, lm;
4242     uint32_t *lp, entry_1, entry_2;
4243
4244     lock_user_struct(VERIFY_WRITE, target_ldt_info, ptr, 1);
4245     if (!target_ldt_info)
4246         return -TARGET_EFAULT;
4247     idx = tswap32(target_ldt_info->entry_number);
4248     if (idx < TARGET_GDT_ENTRY_TLS_MIN ||
4249         idx > TARGET_GDT_ENTRY_TLS_MAX) {
4250         unlock_user_struct(target_ldt_info, ptr, 1);
4251         return -TARGET_EINVAL;
4252     }
4253     lp = (uint32_t *)(gdt_table + idx);
4254     entry_1 = tswap32(lp[0]);
4255     entry_2 = tswap32(lp[1]);
4256     
4257     read_exec_only = ((entry_2 >> 9) & 1) ^ 1;
4258     contents = (entry_2 >> 10) & 3;
4259     seg_not_present = ((entry_2 >> 15) & 1) ^ 1;
4260     seg_32bit = (entry_2 >> 22) & 1;
4261     limit_in_pages = (entry_2 >> 23) & 1;
4262     useable = (entry_2 >> 20) & 1;
4263 #ifdef TARGET_ABI32
4264     lm = 0;
4265 #else
4266     lm = (entry_2 >> 21) & 1;
4267 #endif
4268     flags = (seg_32bit << 0) | (contents << 1) |
4269         (read_exec_only << 3) | (limit_in_pages << 4) |
4270         (seg_not_present << 5) | (useable << 6) | (lm << 7);
4271     limit = (entry_1 & 0xffff) | (entry_2  & 0xf0000);
4272     base_addr = (entry_1 >> 16) | 
4273         (entry_2 & 0xff000000) | 
4274         ((entry_2 & 0xff) << 16);
4275     target_ldt_info->base_addr = tswapal(base_addr);
4276     target_ldt_info->limit = tswap32(limit);
4277     target_ldt_info->flags = tswap32(flags);
4278     unlock_user_struct(target_ldt_info, ptr, 1);
4279     return 0;
4280 }
4281 #endif /* TARGET_I386 && TARGET_ABI32 */
4282
4283 #ifndef TARGET_ABI32
4284 abi_long do_arch_prctl(CPUX86State *env, int code, abi_ulong addr)
4285 {
4286     abi_long ret = 0;
4287     abi_ulong val;
4288     int idx;
4289
4290     switch(code) {
4291     case TARGET_ARCH_SET_GS:
4292     case TARGET_ARCH_SET_FS:
4293         if (code == TARGET_ARCH_SET_GS)
4294             idx = R_GS;
4295         else
4296             idx = R_FS;
4297         cpu_x86_load_seg(env, idx, 0);
4298         env->segs[idx].base = addr;
4299         break;
4300     case TARGET_ARCH_GET_GS:
4301     case TARGET_ARCH_GET_FS:
4302         if (code == TARGET_ARCH_GET_GS)
4303             idx = R_GS;
4304         else
4305             idx = R_FS;
4306         val = env->segs[idx].base;
4307         if (put_user(val, addr, abi_ulong))
4308             ret = -TARGET_EFAULT;
4309         break;
4310     default:
4311         ret = -TARGET_EINVAL;
4312         break;
4313     }
4314     return ret;
4315 }
4316 #endif
4317
4318 #endif /* defined(TARGET_I386) */
4319
4320 #define NEW_STACK_SIZE 0x40000
4321
4322
4323 static pthread_mutex_t clone_lock = PTHREAD_MUTEX_INITIALIZER;
4324 typedef struct {
4325     CPUArchState *env;
4326     pthread_mutex_t mutex;
4327     pthread_cond_t cond;
4328     pthread_t thread;
4329     uint32_t tid;
4330     abi_ulong child_tidptr;
4331     abi_ulong parent_tidptr;
4332     sigset_t sigmask;
4333 } new_thread_info;
4334
4335 static void *clone_func(void *arg)
4336 {
4337     new_thread_info *info = arg;
4338     CPUArchState *env;
4339     CPUState *cpu;
4340     TaskState *ts;
4341
4342     env = info->env;
4343     cpu = ENV_GET_CPU(env);
4344     thread_cpu = cpu;
4345     ts = (TaskState *)cpu->opaque;
4346     info->tid = gettid();
4347     cpu->host_tid = info->tid;
4348     task_settid(ts);
4349     if (info->child_tidptr)
4350         put_user_u32(info->tid, info->child_tidptr);
4351     if (info->parent_tidptr)
4352         put_user_u32(info->tid, info->parent_tidptr);
4353     /* Enable signals.  */
4354     sigprocmask(SIG_SETMASK, &info->sigmask, NULL);
4355     /* Signal to the parent that we're ready.  */
4356     pthread_mutex_lock(&info->mutex);
4357     pthread_cond_broadcast(&info->cond);
4358     pthread_mutex_unlock(&info->mutex);
4359     /* Wait until the parent has finshed initializing the tls state.  */
4360     pthread_mutex_lock(&clone_lock);
4361     pthread_mutex_unlock(&clone_lock);
4362     cpu_loop(env);
4363     /* never exits */
4364     return NULL;
4365 }
4366
4367 /* do_fork() Must return host values and target errnos (unlike most
4368    do_*() functions). */
4369 static int do_fork(CPUArchState *env, unsigned int flags, abi_ulong newsp,
4370                    abi_ulong parent_tidptr, target_ulong newtls,
4371                    abi_ulong child_tidptr)
4372 {
4373     CPUState *cpu = ENV_GET_CPU(env);
4374     int ret;
4375     TaskState *ts;
4376     CPUState *new_cpu;
4377     CPUArchState *new_env;
4378     unsigned int nptl_flags;
4379     sigset_t sigmask;
4380
4381     /* Emulate vfork() with fork() */
4382     if (flags & CLONE_VFORK)
4383         flags &= ~(CLONE_VFORK | CLONE_VM);
4384
4385     if (flags & CLONE_VM) {
4386         TaskState *parent_ts = (TaskState *)cpu->opaque;
4387         new_thread_info info;
4388         pthread_attr_t attr;
4389
4390         ts = g_malloc0(sizeof(TaskState));
4391         init_task_state(ts);
4392         /* we create a new CPU instance. */
4393         new_env = cpu_copy(env);
4394         /* Init regs that differ from the parent.  */
4395         cpu_clone_regs(new_env, newsp);
4396         new_cpu = ENV_GET_CPU(new_env);
4397         new_cpu->opaque = ts;
4398         ts->bprm = parent_ts->bprm;
4399         ts->info = parent_ts->info;
4400         nptl_flags = flags;
4401         flags &= ~CLONE_NPTL_FLAGS2;
4402
4403         if (nptl_flags & CLONE_CHILD_CLEARTID) {
4404             ts->child_tidptr = child_tidptr;
4405         }
4406
4407         if (nptl_flags & CLONE_SETTLS)
4408             cpu_set_tls (new_env, newtls);
4409
4410         /* Grab a mutex so that thread setup appears atomic.  */
4411         pthread_mutex_lock(&clone_lock);
4412
4413         memset(&info, 0, sizeof(info));
4414         pthread_mutex_init(&info.mutex, NULL);
4415         pthread_mutex_lock(&info.mutex);
4416         pthread_cond_init(&info.cond, NULL);
4417         info.env = new_env;
4418         if (nptl_flags & CLONE_CHILD_SETTID)
4419             info.child_tidptr = child_tidptr;
4420         if (nptl_flags & CLONE_PARENT_SETTID)
4421             info.parent_tidptr = parent_tidptr;
4422
4423         ret = pthread_attr_init(&attr);
4424         ret = pthread_attr_setstacksize(&attr, NEW_STACK_SIZE);
4425         ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
4426         /* It is not safe to deliver signals until the child has finished
4427            initializing, so temporarily block all signals.  */
4428         sigfillset(&sigmask);
4429         sigprocmask(SIG_BLOCK, &sigmask, &info.sigmask);
4430
4431         ret = pthread_create(&info.thread, &attr, clone_func, &info);
4432         /* TODO: Free new CPU state if thread creation failed.  */
4433
4434         sigprocmask(SIG_SETMASK, &info.sigmask, NULL);
4435         pthread_attr_destroy(&attr);
4436         if (ret == 0) {
4437             /* Wait for the child to initialize.  */
4438             pthread_cond_wait(&info.cond, &info.mutex);
4439             ret = info.tid;
4440             if (flags & CLONE_PARENT_SETTID)
4441                 put_user_u32(ret, parent_tidptr);
4442         } else {
4443             ret = -1;
4444         }
4445         pthread_mutex_unlock(&info.mutex);
4446         pthread_cond_destroy(&info.cond);
4447         pthread_mutex_destroy(&info.mutex);
4448         pthread_mutex_unlock(&clone_lock);
4449     } else {
4450         /* if no CLONE_VM, we consider it is a fork */
4451         if ((flags & ~(CSIGNAL | CLONE_NPTL_FLAGS2)) != 0)
4452             return -EINVAL;
4453         fork_start();
4454         ret = fork();
4455         if (ret == 0) {
4456             /* Child Process.  */
4457             cpu_clone_regs(env, newsp);
4458             fork_end(1);
4459             /* There is a race condition here.  The parent process could
4460                theoretically read the TID in the child process before the child
4461                tid is set.  This would require using either ptrace
4462                (not implemented) or having *_tidptr to point at a shared memory
4463                mapping.  We can't repeat the spinlock hack used above because
4464                the child process gets its own copy of the lock.  */
4465             if (flags & CLONE_CHILD_SETTID)
4466                 put_user_u32(gettid(), child_tidptr);
4467             if (flags & CLONE_PARENT_SETTID)
4468                 put_user_u32(gettid(), parent_tidptr);
4469             ts = (TaskState *)cpu->opaque;
4470             if (flags & CLONE_SETTLS)
4471                 cpu_set_tls (env, newtls);
4472             if (flags & CLONE_CHILD_CLEARTID)
4473                 ts->child_tidptr = child_tidptr;
4474         } else {
4475             fork_end(0);
4476         }
4477     }
4478     return ret;
4479 }
4480
4481 /* warning : doesn't handle linux specific flags... */
4482 static int target_to_host_fcntl_cmd(int cmd)
4483 {
4484     switch(cmd) {
4485         case TARGET_F_DUPFD:
4486         case TARGET_F_GETFD:
4487         case TARGET_F_SETFD:
4488         case TARGET_F_GETFL:
4489         case TARGET_F_SETFL:
4490             return cmd;
4491         case TARGET_F_GETLK:
4492             return F_GETLK;
4493         case TARGET_F_SETLK:
4494             return F_SETLK;
4495         case TARGET_F_SETLKW:
4496             return F_SETLKW;
4497         case TARGET_F_GETOWN:
4498             return F_GETOWN;
4499         case TARGET_F_SETOWN:
4500             return F_SETOWN;
4501         case TARGET_F_GETSIG:
4502             return F_GETSIG;
4503         case TARGET_F_SETSIG:
4504             return F_SETSIG;
4505 #if TARGET_ABI_BITS == 32
4506         case TARGET_F_GETLK64:
4507             return F_GETLK64;
4508         case TARGET_F_SETLK64:
4509             return F_SETLK64;
4510         case TARGET_F_SETLKW64:
4511             return F_SETLKW64;
4512 #endif
4513         case TARGET_F_SETLEASE:
4514             return F_SETLEASE;
4515         case TARGET_F_GETLEASE:
4516             return F_GETLEASE;
4517 #ifdef F_DUPFD_CLOEXEC
4518         case TARGET_F_DUPFD_CLOEXEC:
4519             return F_DUPFD_CLOEXEC;
4520 #endif
4521         case TARGET_F_NOTIFY:
4522             return F_NOTIFY;
4523 #ifdef F_GETOWN_EX
4524         case TARGET_F_GETOWN_EX:
4525             return F_GETOWN_EX;
4526 #endif
4527 #ifdef F_SETOWN_EX
4528         case TARGET_F_SETOWN_EX:
4529             return F_SETOWN_EX;
4530 #endif
4531         default:
4532             return -TARGET_EINVAL;
4533     }
4534     return -TARGET_EINVAL;
4535 }
4536
4537 #define TRANSTBL_CONVERT(a) { -1, TARGET_##a, -1, a }
4538 static const bitmask_transtbl flock_tbl[] = {
4539     TRANSTBL_CONVERT(F_RDLCK),
4540     TRANSTBL_CONVERT(F_WRLCK),
4541     TRANSTBL_CONVERT(F_UNLCK),
4542     TRANSTBL_CONVERT(F_EXLCK),
4543     TRANSTBL_CONVERT(F_SHLCK),
4544     { 0, 0, 0, 0 }
4545 };
4546
4547 static abi_long do_fcntl(int fd, int cmd, abi_ulong arg)
4548 {
4549     struct flock fl;
4550     struct target_flock *target_fl;
4551     struct flock64 fl64;
4552     struct target_flock64 *target_fl64;
4553 #ifdef F_GETOWN_EX
4554     struct f_owner_ex fox;
4555     struct target_f_owner_ex *target_fox;
4556 #endif
4557     abi_long ret;
4558     int host_cmd = target_to_host_fcntl_cmd(cmd);
4559
4560     if (host_cmd == -TARGET_EINVAL)
4561             return host_cmd;
4562
4563     switch(cmd) {
4564     case TARGET_F_GETLK:
4565         if (!lock_user_struct(VERIFY_READ, target_fl, arg, 1))
4566             return -TARGET_EFAULT;
4567         fl.l_type =
4568                   target_to_host_bitmask(tswap16(target_fl->l_type), flock_tbl);
4569         fl.l_whence = tswap16(target_fl->l_whence);
4570         fl.l_start = tswapal(target_fl->l_start);
4571         fl.l_len = tswapal(target_fl->l_len);
4572         fl.l_pid = tswap32(target_fl->l_pid);
4573         unlock_user_struct(target_fl, arg, 0);
4574         ret = get_errno(fcntl(fd, host_cmd, &fl));
4575         if (ret == 0) {
4576             if (!lock_user_struct(VERIFY_WRITE, target_fl, arg, 0))
4577                 return -TARGET_EFAULT;
4578             target_fl->l_type =
4579                           host_to_target_bitmask(tswap16(fl.l_type), flock_tbl);
4580             target_fl->l_whence = tswap16(fl.l_whence);
4581             target_fl->l_start = tswapal(fl.l_start);
4582             target_fl->l_len = tswapal(fl.l_len);
4583             target_fl->l_pid = tswap32(fl.l_pid);
4584             unlock_user_struct(target_fl, arg, 1);
4585         }
4586         break;
4587
4588     case TARGET_F_SETLK:
4589     case TARGET_F_SETLKW:
4590         if (!lock_user_struct(VERIFY_READ, target_fl, arg, 1))
4591             return -TARGET_EFAULT;
4592         fl.l_type =
4593                   target_to_host_bitmask(tswap16(target_fl->l_type), flock_tbl);
4594         fl.l_whence = tswap16(target_fl->l_whence);
4595         fl.l_start = tswapal(target_fl->l_start);
4596         fl.l_len = tswapal(target_fl->l_len);
4597         fl.l_pid = tswap32(target_fl->l_pid);
4598         unlock_user_struct(target_fl, arg, 0);
4599         ret = get_errno(fcntl(fd, host_cmd, &fl));
4600         break;
4601
4602     case TARGET_F_GETLK64:
4603         if (!lock_user_struct(VERIFY_READ, target_fl64, arg, 1))
4604             return -TARGET_EFAULT;
4605         fl64.l_type =
4606            target_to_host_bitmask(tswap16(target_fl64->l_type), flock_tbl) >> 1;
4607         fl64.l_whence = tswap16(target_fl64->l_whence);
4608         fl64.l_start = tswap64(target_fl64->l_start);
4609         fl64.l_len = tswap64(target_fl64->l_len);
4610         fl64.l_pid = tswap32(target_fl64->l_pid);
4611         unlock_user_struct(target_fl64, arg, 0);
4612         ret = get_errno(fcntl(fd, host_cmd, &fl64));
4613         if (ret == 0) {
4614             if (!lock_user_struct(VERIFY_WRITE, target_fl64, arg, 0))
4615                 return -TARGET_EFAULT;
4616             target_fl64->l_type =
4617                    host_to_target_bitmask(tswap16(fl64.l_type), flock_tbl) >> 1;
4618             target_fl64->l_whence = tswap16(fl64.l_whence);
4619             target_fl64->l_start = tswap64(fl64.l_start);
4620             target_fl64->l_len = tswap64(fl64.l_len);
4621             target_fl64->l_pid = tswap32(fl64.l_pid);
4622             unlock_user_struct(target_fl64, arg, 1);
4623         }
4624         break;
4625     case TARGET_F_SETLK64:
4626     case TARGET_F_SETLKW64:
4627         if (!lock_user_struct(VERIFY_READ, target_fl64, arg, 1))
4628             return -TARGET_EFAULT;
4629         fl64.l_type =
4630            target_to_host_bitmask(tswap16(target_fl64->l_type), flock_tbl) >> 1;
4631         fl64.l_whence = tswap16(target_fl64->l_whence);
4632         fl64.l_start = tswap64(target_fl64->l_start);
4633         fl64.l_len = tswap64(target_fl64->l_len);
4634         fl64.l_pid = tswap32(target_fl64->l_pid);
4635         unlock_user_struct(target_fl64, arg, 0);
4636         ret = get_errno(fcntl(fd, host_cmd, &fl64));
4637         break;
4638
4639     case TARGET_F_GETFL:
4640         ret = get_errno(fcntl(fd, host_cmd, arg));
4641         if (ret >= 0) {
4642             ret = host_to_target_bitmask(ret, fcntl_flags_tbl);
4643         }
4644         break;
4645
4646     case TARGET_F_SETFL:
4647         ret = get_errno(fcntl(fd, host_cmd, target_to_host_bitmask(arg, fcntl_flags_tbl)));
4648         break;
4649
4650 #ifdef F_GETOWN_EX
4651     case TARGET_F_GETOWN_EX:
4652         ret = get_errno(fcntl(fd, host_cmd, &fox));
4653         if (ret >= 0) {
4654             if (!lock_user_struct(VERIFY_WRITE, target_fox, arg, 0))
4655                 return -TARGET_EFAULT;
4656             target_fox->type = tswap32(fox.type);
4657             target_fox->pid = tswap32(fox.pid);
4658             unlock_user_struct(target_fox, arg, 1);
4659         }
4660         break;
4661 #endif
4662
4663 #ifdef F_SETOWN_EX
4664     case TARGET_F_SETOWN_EX:
4665         if (!lock_user_struct(VERIFY_READ, target_fox, arg, 1))
4666             return -TARGET_EFAULT;
4667         fox.type = tswap32(target_fox->type);
4668         fox.pid = tswap32(target_fox->pid);
4669         unlock_user_struct(target_fox, arg, 0);
4670         ret = get_errno(fcntl(fd, host_cmd, &fox));
4671         break;
4672 #endif
4673
4674     case TARGET_F_SETOWN:
4675     case TARGET_F_GETOWN:
4676     case TARGET_F_SETSIG:
4677     case TARGET_F_GETSIG:
4678     case TARGET_F_SETLEASE:
4679     case TARGET_F_GETLEASE:
4680         ret = get_errno(fcntl(fd, host_cmd, arg));
4681         break;
4682
4683     default:
4684         ret = get_errno(fcntl(fd, cmd, arg));
4685         break;
4686     }
4687     return ret;
4688 }
4689
4690 #ifdef USE_UID16
4691
4692 static inline int high2lowuid(int uid)
4693 {
4694     if (uid > 65535)
4695         return 65534;
4696     else
4697         return uid;
4698 }
4699
4700 static inline int high2lowgid(int gid)
4701 {
4702     if (gid > 65535)
4703         return 65534;
4704     else
4705         return gid;
4706 }
4707
4708 static inline int low2highuid(int uid)
4709 {
4710     if ((int16_t)uid == -1)
4711         return -1;
4712     else
4713         return uid;
4714 }
4715
4716 static inline int low2highgid(int gid)
4717 {
4718     if ((int16_t)gid == -1)
4719         return -1;
4720     else
4721         return gid;
4722 }
4723 static inline int tswapid(int id)
4724 {
4725     return tswap16(id);
4726 }
4727
4728 #define put_user_id(x, gaddr) put_user_u16(x, gaddr)
4729
4730 #else /* !USE_UID16 */
4731 static inline int high2lowuid(int uid)
4732 {
4733     return uid;
4734 }
4735 static inline int high2lowgid(int gid)
4736 {
4737     return gid;
4738 }
4739 static inline int low2highuid(int uid)
4740 {
4741     return uid;
4742 }
4743 static inline int low2highgid(int gid)
4744 {
4745     return gid;
4746 }
4747 static inline int tswapid(int id)
4748 {
4749     return tswap32(id);
4750 }
4751
4752 #define put_user_id(x, gaddr) put_user_u32(x, gaddr)
4753
4754 #endif /* USE_UID16 */
4755
4756 void syscall_init(void)
4757 {
4758     IOCTLEntry *ie;
4759     const argtype *arg_type;
4760     int size;
4761     int i;
4762
4763 #define STRUCT(name, ...) thunk_register_struct(STRUCT_ ## name, #name, struct_ ## name ## _def);
4764 #define STRUCT_SPECIAL(name) thunk_register_struct_direct(STRUCT_ ## name, #name, &struct_ ## name ## _def);
4765 #include "syscall_types.h"
4766 #undef STRUCT
4767 #undef STRUCT_SPECIAL
4768
4769     /* Build target_to_host_errno_table[] table from
4770      * host_to_target_errno_table[]. */
4771     for (i = 0; i < ERRNO_TABLE_SIZE; i++) {
4772         target_to_host_errno_table[host_to_target_errno_table[i]] = i;
4773     }
4774
4775     /* we patch the ioctl size if necessary. We rely on the fact that
4776        no ioctl has all the bits at '1' in the size field */
4777     ie = ioctl_entries;
4778     while (ie->target_cmd != 0) {
4779         if (((ie->target_cmd >> TARGET_IOC_SIZESHIFT) & TARGET_IOC_SIZEMASK) ==
4780             TARGET_IOC_SIZEMASK) {
4781             arg_type = ie->arg_type;
4782             if (arg_type[0] != TYPE_PTR) {
4783                 fprintf(stderr, "cannot patch size for ioctl 0x%x\n",
4784                         ie->target_cmd);
4785                 exit(1);
4786             }
4787             arg_type++;
4788             size = thunk_type_size(arg_type, 0);
4789             ie->target_cmd = (ie->target_cmd &
4790                               ~(TARGET_IOC_SIZEMASK << TARGET_IOC_SIZESHIFT)) |
4791                 (size << TARGET_IOC_SIZESHIFT);
4792         }
4793
4794         /* automatic consistency check if same arch */
4795 #if (defined(__i386__) && defined(TARGET_I386) && defined(TARGET_ABI32)) || \
4796     (defined(__x86_64__) && defined(TARGET_X86_64))
4797         if (unlikely(ie->target_cmd != ie->host_cmd)) {
4798             fprintf(stderr, "ERROR: ioctl(%s): target=0x%x host=0x%x\n",
4799                     ie->name, ie->target_cmd, ie->host_cmd);
4800         }
4801 #endif
4802         ie++;
4803     }
4804 }
4805
4806 #if TARGET_ABI_BITS == 32
4807 static inline uint64_t target_offset64(uint32_t word0, uint32_t word1)
4808 {
4809 #ifdef TARGET_WORDS_BIGENDIAN
4810     return ((uint64_t)word0 << 32) | word1;
4811 #else
4812     return ((uint64_t)word1 << 32) | word0;
4813 #endif
4814 }
4815 #else /* TARGET_ABI_BITS == 32 */
4816 static inline uint64_t target_offset64(uint64_t word0, uint64_t word1)
4817 {
4818     return word0;
4819 }
4820 #endif /* TARGET_ABI_BITS != 32 */
4821
4822 #ifdef TARGET_NR_truncate64
4823 static inline abi_long target_truncate64(void *cpu_env, const char *arg1,
4824                                          abi_long arg2,
4825                                          abi_long arg3,
4826                                          abi_long arg4)
4827 {
4828     if (regpairs_aligned(cpu_env)) {
4829         arg2 = arg3;
4830         arg3 = arg4;
4831     }
4832     return get_errno(truncate64(arg1, target_offset64(arg2, arg3)));
4833 }
4834 #endif
4835
4836 #ifdef TARGET_NR_ftruncate64
4837 static inline abi_long target_ftruncate64(void *cpu_env, abi_long arg1,
4838                                           abi_long arg2,
4839                                           abi_long arg3,
4840                                           abi_long arg4)
4841 {
4842     if (regpairs_aligned(cpu_env)) {
4843         arg2 = arg3;
4844         arg3 = arg4;
4845     }
4846     return get_errno(ftruncate64(arg1, target_offset64(arg2, arg3)));
4847 }
4848 #endif
4849
4850 static inline abi_long target_to_host_timespec(struct timespec *host_ts,
4851                                                abi_ulong target_addr)
4852 {
4853     struct target_timespec *target_ts;
4854
4855     if (!lock_user_struct(VERIFY_READ, target_ts, target_addr, 1))
4856         return -TARGET_EFAULT;
4857     host_ts->tv_sec = tswapal(target_ts->tv_sec);
4858     host_ts->tv_nsec = tswapal(target_ts->tv_nsec);
4859     unlock_user_struct(target_ts, target_addr, 0);
4860     return 0;
4861 }
4862
4863 static inline abi_long host_to_target_timespec(abi_ulong target_addr,
4864                                                struct timespec *host_ts)
4865 {
4866     struct target_timespec *target_ts;
4867
4868     if (!lock_user_struct(VERIFY_WRITE, target_ts, target_addr, 0))
4869         return -TARGET_EFAULT;
4870     target_ts->tv_sec = tswapal(host_ts->tv_sec);
4871     target_ts->tv_nsec = tswapal(host_ts->tv_nsec);
4872     unlock_user_struct(target_ts, target_addr, 1);
4873     return 0;
4874 }
4875
4876 static inline abi_long target_to_host_itimerspec(struct itimerspec *host_itspec,
4877                                                  abi_ulong target_addr)
4878 {
4879     struct target_itimerspec *target_itspec;
4880
4881     if (!lock_user_struct(VERIFY_READ, target_itspec, target_addr, 1)) {
4882         return -TARGET_EFAULT;
4883     }
4884
4885     host_itspec->it_interval.tv_sec =
4886                             tswapal(target_itspec->it_interval.tv_sec);
4887     host_itspec->it_interval.tv_nsec =
4888                             tswapal(target_itspec->it_interval.tv_nsec);
4889     host_itspec->it_value.tv_sec = tswapal(target_itspec->it_value.tv_sec);
4890     host_itspec->it_value.tv_nsec = tswapal(target_itspec->it_value.tv_nsec);
4891
4892     unlock_user_struct(target_itspec, target_addr, 1);
4893     return 0;
4894 }
4895
4896 static inline abi_long host_to_target_itimerspec(abi_ulong target_addr,
4897                                                struct itimerspec *host_its)
4898 {
4899     struct target_itimerspec *target_itspec;
4900
4901     if (!lock_user_struct(VERIFY_WRITE, target_itspec, target_addr, 0)) {
4902         return -TARGET_EFAULT;
4903     }
4904
4905     target_itspec->it_interval.tv_sec = tswapal(host_its->it_interval.tv_sec);
4906     target_itspec->it_interval.tv_nsec = tswapal(host_its->it_interval.tv_nsec);
4907
4908     target_itspec->it_value.tv_sec = tswapal(host_its->it_value.tv_sec);
4909     target_itspec->it_value.tv_nsec = tswapal(host_its->it_value.tv_nsec);
4910
4911     unlock_user_struct(target_itspec, target_addr, 0);
4912     return 0;
4913 }
4914
4915 static inline abi_long target_to_host_sigevent(struct sigevent *host_sevp,
4916                                                abi_ulong target_addr)
4917 {
4918     struct target_sigevent *target_sevp;
4919
4920     if (!lock_user_struct(VERIFY_READ, target_sevp, target_addr, 1)) {
4921         return -TARGET_EFAULT;
4922     }
4923
4924     /* This union is awkward on 64 bit systems because it has a 32 bit
4925      * integer and a pointer in it; we follow the conversion approach
4926      * used for handling sigval types in signal.c so the guest should get
4927      * the correct value back even if we did a 64 bit byteswap and it's
4928      * using the 32 bit integer.
4929      */
4930     host_sevp->sigev_value.sival_ptr =
4931         (void *)(uintptr_t)tswapal(target_sevp->sigev_value.sival_ptr);
4932     host_sevp->sigev_signo =
4933         target_to_host_signal(tswap32(target_sevp->sigev_signo));
4934     host_sevp->sigev_notify = tswap32(target_sevp->sigev_notify);
4935     host_sevp->_sigev_un._tid = tswap32(target_sevp->_sigev_un._tid);
4936
4937     unlock_user_struct(target_sevp, target_addr, 1);
4938     return 0;
4939 }
4940
4941 #if defined(TARGET_NR_stat64) || defined(TARGET_NR_newfstatat)
4942 static inline abi_long host_to_target_stat64(void *cpu_env,
4943                                              abi_ulong target_addr,
4944                                              struct stat *host_st)
4945 {
4946 #if defined(TARGET_ARM) && defined(TARGET_ABI32)
4947     if (((CPUARMState *)cpu_env)->eabi) {
4948         struct target_eabi_stat64 *target_st;
4949
4950         if (!lock_user_struct(VERIFY_WRITE, target_st, target_addr, 0))
4951             return -TARGET_EFAULT;
4952         memset(target_st, 0, sizeof(struct target_eabi_stat64));
4953         __put_user(host_st->st_dev, &target_st->st_dev);
4954         __put_user(host_st->st_ino, &target_st->st_ino);
4955 #ifdef TARGET_STAT64_HAS_BROKEN_ST_INO
4956         __put_user(host_st->st_ino, &target_st->__st_ino);
4957 #endif
4958         __put_user(host_st->st_mode, &target_st->st_mode);
4959         __put_user(host_st->st_nlink, &target_st->st_nlink);
4960         __put_user(host_st->st_uid, &target_st->st_uid);
4961         __put_user(host_st->st_gid, &target_st->st_gid);
4962         __put_user(host_st->st_rdev, &target_st->st_rdev);
4963         __put_user(host_st->st_size, &target_st->st_size);
4964         __put_user(host_st->st_blksize, &target_st->st_blksize);
4965         __put_user(host_st->st_blocks, &target_st->st_blocks);
4966         __put_user(host_st->st_atime, &target_st->target_st_atime);
4967         __put_user(host_st->st_mtime, &target_st->target_st_mtime);
4968         __put_user(host_st->st_ctime, &target_st->target_st_ctime);
4969         unlock_user_struct(target_st, target_addr, 1);
4970     } else
4971 #endif
4972     {
4973 #if defined(TARGET_HAS_STRUCT_STAT64)
4974         struct target_stat64 *target_st;
4975 #else
4976         struct target_stat *target_st;
4977 #endif
4978
4979         if (!lock_user_struct(VERIFY_WRITE, target_st, target_addr, 0))
4980             return -TARGET_EFAULT;
4981         memset(target_st, 0, sizeof(*target_st));
4982         __put_user(host_st->st_dev, &target_st->st_dev);
4983         __put_user(host_st->st_ino, &target_st->st_ino);
4984 #ifdef TARGET_STAT64_HAS_BROKEN_ST_INO
4985         __put_user(host_st->st_ino, &target_st->__st_ino);
4986 #endif
4987         __put_user(host_st->st_mode, &target_st->st_mode);
4988         __put_user(host_st->st_nlink, &target_st->st_nlink);
4989         __put_user(host_st->st_uid, &target_st->st_uid);
4990         __put_user(host_st->st_gid, &target_st->st_gid);
4991         __put_user(host_st->st_rdev, &target_st->st_rdev);
4992         /* XXX: better use of kernel struct */
4993         __put_user(host_st->st_size, &target_st->st_size);
4994         __put_user(host_st->st_blksize, &target_st->st_blksize);
4995         __put_user(host_st->st_blocks, &target_st->st_blocks);
4996         __put_user(host_st->st_atime, &target_st->target_st_atime);
4997         __put_user(host_st->st_mtime, &target_st->target_st_mtime);
4998         __put_user(host_st->st_ctime, &target_st->target_st_ctime);
4999         unlock_user_struct(target_st, target_addr, 1);
5000     }
5001
5002     return 0;
5003 }
5004 #endif
5005
5006 /* ??? Using host futex calls even when target atomic operations
5007    are not really atomic probably breaks things.  However implementing
5008    futexes locally would make futexes shared between multiple processes
5009    tricky.  However they're probably useless because guest atomic
5010    operations won't work either.  */
5011 static int do_futex(target_ulong uaddr, int op, int val, target_ulong timeout,
5012                     target_ulong uaddr2, int val3)
5013 {
5014     struct timespec ts, *pts;
5015     int base_op;
5016
5017     /* ??? We assume FUTEX_* constants are the same on both host
5018        and target.  */
5019 #ifdef FUTEX_CMD_MASK
5020     base_op = op & FUTEX_CMD_MASK;
5021 #else
5022     base_op = op;
5023 #endif
5024     switch (base_op) {
5025     case FUTEX_WAIT:
5026     case FUTEX_WAIT_BITSET:
5027         if (timeout) {
5028             pts = &ts;
5029             target_to_host_timespec(pts, timeout);
5030         } else {
5031             pts = NULL;
5032         }
5033         return get_errno(sys_futex(g2h(uaddr), op, tswap32(val),
5034                          pts, NULL, val3));
5035     case FUTEX_WAKE:
5036         return get_errno(sys_futex(g2h(uaddr), op, val, NULL, NULL, 0));
5037     case FUTEX_FD:
5038         return get_errno(sys_futex(g2h(uaddr), op, val, NULL, NULL, 0));
5039     case FUTEX_REQUEUE:
5040     case FUTEX_CMP_REQUEUE:
5041     case FUTEX_WAKE_OP:
5042         /* For FUTEX_REQUEUE, FUTEX_CMP_REQUEUE, and FUTEX_WAKE_OP, the
5043            TIMEOUT parameter is interpreted as a uint32_t by the kernel.
5044            But the prototype takes a `struct timespec *'; insert casts
5045            to satisfy the compiler.  We do not need to tswap TIMEOUT
5046            since it's not compared to guest memory.  */
5047         pts = (struct timespec *)(uintptr_t) timeout;
5048         return get_errno(sys_futex(g2h(uaddr), op, val, pts,
5049                                    g2h(uaddr2),
5050                                    (base_op == FUTEX_CMP_REQUEUE
5051                                     ? tswap32(val3)
5052                                     : val3)));
5053     default:
5054         return -TARGET_ENOSYS;
5055     }
5056 }
5057
5058 /* Map host to target signal numbers for the wait family of syscalls.
5059    Assume all other status bits are the same.  */
5060 int host_to_target_waitstatus(int status)
5061 {
5062     if (WIFSIGNALED(status)) {
5063         return host_to_target_signal(WTERMSIG(status)) | (status & ~0x7f);
5064     }
5065     if (WIFSTOPPED(status)) {
5066         return (host_to_target_signal(WSTOPSIG(status)) << 8)
5067                | (status & 0xff);
5068     }
5069     return status;
5070 }
5071
5072 static int open_self_cmdline(void *cpu_env, int fd)
5073 {
5074     int fd_orig = -1;
5075     bool word_skipped = false;
5076
5077     fd_orig = open("/proc/self/cmdline", O_RDONLY);
5078     if (fd_orig < 0) {
5079         return fd_orig;
5080     }
5081
5082     while (true) {
5083         ssize_t nb_read;
5084         char buf[128];
5085         char *cp_buf = buf;
5086
5087         nb_read = read(fd_orig, buf, sizeof(buf));
5088         if (nb_read < 0) {
5089             fd_orig = close(fd_orig);
5090             return -1;
5091         } else if (nb_read == 0) {
5092             break;
5093         }
5094
5095         if (!word_skipped) {
5096             /* Skip the first string, which is the path to qemu-*-static
5097                instead of the actual command. */
5098             cp_buf = memchr(buf, 0, sizeof(buf));
5099             if (cp_buf) {
5100                 /* Null byte found, skip one string */
5101                 cp_buf++;
5102                 nb_read -= cp_buf - buf;
5103                 word_skipped = true;
5104             }
5105         }
5106
5107         if (word_skipped) {
5108             if (write(fd, cp_buf, nb_read) != nb_read) {
5109                 return -1;
5110             }
5111         }
5112     }
5113
5114     return close(fd_orig);
5115 }
5116
5117 static int open_self_maps(void *cpu_env, int fd)
5118 {
5119     CPUState *cpu = ENV_GET_CPU((CPUArchState *)cpu_env);
5120     TaskState *ts = cpu->opaque;
5121     FILE *fp;
5122     char *line = NULL;
5123     size_t len = 0;
5124     ssize_t read;
5125
5126     fp = fopen("/proc/self/maps", "r");
5127     if (fp == NULL) {
5128         return -EACCES;
5129     }
5130
5131     while ((read = getline(&line, &len, fp)) != -1) {
5132         int fields, dev_maj, dev_min, inode;
5133         uint64_t min, max, offset;
5134         char flag_r, flag_w, flag_x, flag_p;
5135         char path[512] = "";
5136         fields = sscanf(line, "%"PRIx64"-%"PRIx64" %c%c%c%c %"PRIx64" %x:%x %d"
5137                         " %512s", &min, &max, &flag_r, &flag_w, &flag_x,
5138                         &flag_p, &offset, &dev_maj, &dev_min, &inode, path);
5139
5140         if ((fields < 10) || (fields > 11)) {
5141             continue;
5142         }
5143         if (h2g_valid(min)) {
5144             int flags = page_get_flags(h2g(min));
5145             max = h2g_valid(max - 1) ? max : (uintptr_t)g2h(GUEST_ADDR_MAX);
5146             if (page_check_range(h2g(min), max - min, flags) == -1) {
5147                 continue;
5148             }
5149             if (h2g(min) == ts->info->stack_limit) {
5150                 pstrcpy(path, sizeof(path), "      [stack]");
5151             }
5152             dprintf(fd, TARGET_ABI_FMT_lx "-" TARGET_ABI_FMT_lx
5153                     " %c%c%c%c %08" PRIx64 " %02x:%02x %d %s%s\n",
5154                     h2g(min), h2g(max - 1) + 1, flag_r, flag_w,
5155                     flag_x, flag_p, offset, dev_maj, dev_min, inode,
5156                     path[0] ? "         " : "", path);
5157         }
5158     }
5159
5160     free(line);
5161     fclose(fp);
5162
5163     return 0;
5164 }
5165
5166 static int open_self_stat(void *cpu_env, int fd)
5167 {
5168     CPUState *cpu = ENV_GET_CPU((CPUArchState *)cpu_env);
5169     TaskState *ts = cpu->opaque;
5170     abi_ulong start_stack = ts->info->start_stack;
5171     int i;
5172
5173     for (i = 0; i < 44; i++) {
5174       char buf[128];
5175       int len;
5176       uint64_t val = 0;
5177
5178       if (i == 0) {
5179         /* pid */
5180         val = getpid();
5181         snprintf(buf, sizeof(buf), "%"PRId64 " ", val);
5182       } else if (i == 1) {
5183         /* app name */
5184         snprintf(buf, sizeof(buf), "(%s) ", ts->bprm->argv[0]);
5185       } else if (i == 27) {
5186         /* stack bottom */
5187         val = start_stack;
5188         snprintf(buf, sizeof(buf), "%"PRId64 " ", val);
5189       } else {
5190         /* for the rest, there is MasterCard */
5191         snprintf(buf, sizeof(buf), "0%c", i == 43 ? '\n' : ' ');
5192       }
5193
5194       len = strlen(buf);
5195       if (write(fd, buf, len) != len) {
5196           return -1;
5197       }
5198     }
5199
5200     return 0;
5201 }
5202
5203 static int open_self_auxv(void *cpu_env, int fd)
5204 {
5205     CPUState *cpu = ENV_GET_CPU((CPUArchState *)cpu_env);
5206     TaskState *ts = cpu->opaque;
5207     abi_ulong auxv = ts->info->saved_auxv;
5208     abi_ulong len = ts->info->auxv_len;
5209     char *ptr;
5210
5211     /*
5212      * Auxiliary vector is stored in target process stack.
5213      * read in whole auxv vector and copy it to file
5214      */
5215     ptr = lock_user(VERIFY_READ, auxv, len, 0);
5216     if (ptr != NULL) {
5217         while (len > 0) {
5218             ssize_t r;
5219             r = write(fd, ptr, len);
5220             if (r <= 0) {
5221                 break;
5222             }
5223             len -= r;
5224             ptr += r;
5225         }
5226         lseek(fd, 0, SEEK_SET);
5227         unlock_user(ptr, auxv, len);
5228     }
5229
5230     return 0;
5231 }
5232
5233 static int is_proc_myself(const char *filename, const char *entry)
5234 {
5235     if (!strncmp(filename, "/proc/", strlen("/proc/"))) {
5236         filename += strlen("/proc/");
5237         if (!strncmp(filename, "self/", strlen("self/"))) {
5238             filename += strlen("self/");
5239         } else if (*filename >= '1' && *filename <= '9') {
5240             char myself[80];
5241             snprintf(myself, sizeof(myself), "%d/", getpid());
5242             if (!strncmp(filename, myself, strlen(myself))) {
5243                 filename += strlen(myself);
5244             } else {
5245                 return 0;
5246             }
5247         } else {
5248             return 0;
5249         }
5250         if (!strcmp(filename, entry)) {
5251             return 1;
5252         }
5253     }
5254     return 0;
5255 }
5256
5257 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
5258 static int is_proc(const char *filename, const char *entry)
5259 {
5260     return strcmp(filename, entry) == 0;
5261 }
5262
5263 static int open_net_route(void *cpu_env, int fd)
5264 {
5265     FILE *fp;
5266     char *line = NULL;
5267     size_t len = 0;
5268     ssize_t read;
5269
5270     fp = fopen("/proc/net/route", "r");
5271     if (fp == NULL) {
5272         return -EACCES;
5273     }
5274
5275     /* read header */
5276
5277     read = getline(&line, &len, fp);
5278     dprintf(fd, "%s", line);
5279
5280     /* read routes */
5281
5282     while ((read = getline(&line, &len, fp)) != -1) {
5283         char iface[16];
5284         uint32_t dest, gw, mask;
5285         unsigned int flags, refcnt, use, metric, mtu, window, irtt;
5286         sscanf(line, "%s\t%08x\t%08x\t%04x\t%d\t%d\t%d\t%08x\t%d\t%u\t%u\n",
5287                      iface, &dest, &gw, &flags, &refcnt, &use, &metric,
5288                      &mask, &mtu, &window, &irtt);
5289         dprintf(fd, "%s\t%08x\t%08x\t%04x\t%d\t%d\t%d\t%08x\t%d\t%u\t%u\n",
5290                 iface, tswap32(dest), tswap32(gw), flags, refcnt, use,
5291                 metric, tswap32(mask), mtu, window, irtt);
5292     }
5293
5294     free(line);
5295     fclose(fp);
5296
5297     return 0;
5298 }
5299 #endif
5300
5301 static int do_openat(void *cpu_env, int dirfd, const char *pathname, int flags, mode_t mode)
5302 {
5303     struct fake_open {
5304         const char *filename;
5305         int (*fill)(void *cpu_env, int fd);
5306         int (*cmp)(const char *s1, const char *s2);
5307     };
5308     const struct fake_open *fake_open;
5309     static const struct fake_open fakes[] = {
5310         { "maps", open_self_maps, is_proc_myself },
5311         { "stat", open_self_stat, is_proc_myself },
5312         { "auxv", open_self_auxv, is_proc_myself },
5313         { "cmdline", open_self_cmdline, is_proc_myself },
5314 #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
5315         { "/proc/net/route", open_net_route, is_proc },
5316 #endif
5317         { NULL, NULL, NULL }
5318     };
5319
5320     if (is_proc_myself(pathname, "exe")) {
5321         int execfd = qemu_getauxval(AT_EXECFD);
5322         return execfd ? execfd : get_errno(sys_openat(dirfd, exec_path, flags, mode));
5323     }
5324
5325     for (fake_open = fakes; fake_open->filename; fake_open++) {
5326         if (fake_open->cmp(pathname, fake_open->filename)) {
5327             break;
5328         }
5329     }
5330
5331     if (fake_open->filename) {
5332         const char *tmpdir;
5333         char filename[PATH_MAX];
5334         int fd, r;
5335
5336         /* create temporary file to map stat to */
5337         tmpdir = getenv("TMPDIR");
5338         if (!tmpdir)
5339             tmpdir = "/tmp";
5340         snprintf(filename, sizeof(filename), "%s/qemu-open.XXXXXX", tmpdir);
5341         fd = mkstemp(filename);
5342         if (fd < 0) {
5343             return fd;
5344         }
5345         unlink(filename);
5346
5347         if ((r = fake_open->fill(cpu_env, fd))) {
5348             close(fd);
5349             return r;
5350         }
5351         lseek(fd, 0, SEEK_SET);
5352
5353         return fd;
5354     }
5355
5356     return get_errno(sys_openat(dirfd, path(pathname), flags, mode));
5357 }
5358
5359 /* do_syscall() should always have a single exit point at the end so
5360    that actions, such as logging of syscall results, can be performed.
5361    All errnos that do_syscall() returns must be -TARGET_<errcode>. */
5362 abi_long do_syscall(void *cpu_env, int num, abi_long arg1,
5363                     abi_long arg2, abi_long arg3, abi_long arg4,
5364                     abi_long arg5, abi_long arg6, abi_long arg7,
5365                     abi_long arg8)
5366 {
5367     CPUState *cpu = ENV_GET_CPU(cpu_env);
5368     abi_long ret;
5369     struct stat st;
5370     struct statfs stfs;
5371     void *p;
5372
5373 #ifdef DEBUG
5374     gemu_log("syscall %d", num);
5375 #endif
5376     if(do_strace)
5377         print_syscall(num, arg1, arg2, arg3, arg4, arg5, arg6);
5378
5379     switch(num) {
5380     case TARGET_NR_exit:
5381         /* In old applications this may be used to implement _exit(2).
5382            However in threaded applictions it is used for thread termination,
5383            and _exit_group is used for application termination.
5384            Do thread termination if we have more then one thread.  */
5385         /* FIXME: This probably breaks if a signal arrives.  We should probably
5386            be disabling signals.  */
5387         if (CPU_NEXT(first_cpu)) {
5388             TaskState *ts;
5389
5390             cpu_list_lock();
5391             /* Remove the CPU from the list.  */
5392             QTAILQ_REMOVE(&cpus, cpu, node);
5393             cpu_list_unlock();
5394             ts = cpu->opaque;
5395             if (ts->child_tidptr) {
5396                 put_user_u32(0, ts->child_tidptr);
5397                 sys_futex(g2h(ts->child_tidptr), FUTEX_WAKE, INT_MAX,
5398                           NULL, NULL, 0);
5399             }
5400             thread_cpu = NULL;
5401             object_unref(OBJECT(cpu));
5402             g_free(ts);
5403             pthread_exit(NULL);
5404         }
5405 #ifdef TARGET_GPROF
5406         _mcleanup();
5407 #endif
5408         gdb_exit(cpu_env, arg1);
5409         _exit(arg1);
5410         ret = 0; /* avoid warning */
5411         break;
5412     case TARGET_NR_read:
5413         if (arg3 == 0)
5414             ret = 0;
5415         else {
5416             if (!(p = lock_user(VERIFY_WRITE, arg2, arg3, 0)))
5417                 goto efault;
5418             ret = get_errno(read(arg1, p, arg3));
5419             unlock_user(p, arg2, ret);
5420         }
5421         break;
5422     case TARGET_NR_write:
5423         if (!(p = lock_user(VERIFY_READ, arg2, arg3, 1)))
5424             goto efault;
5425         ret = get_errno(write(arg1, p, arg3));
5426         unlock_user(p, arg2, 0);
5427         break;
5428     case TARGET_NR_open:
5429         if (!(p = lock_user_string(arg1)))
5430             goto efault;
5431         ret = get_errno(do_openat(cpu_env, AT_FDCWD, p,
5432                                   target_to_host_bitmask(arg2, fcntl_flags_tbl),
5433                                   arg3));
5434         unlock_user(p, arg1, 0);
5435         break;
5436     case TARGET_NR_openat:
5437         if (!(p = lock_user_string(arg2)))
5438             goto efault;
5439         ret = get_errno(do_openat(cpu_env, arg1, p,
5440                                   target_to_host_bitmask(arg3, fcntl_flags_tbl),
5441                                   arg4));
5442         unlock_user(p, arg2, 0);
5443         break;
5444     case TARGET_NR_close:
5445         ret = get_errno(close(arg1));
5446         break;
5447     case TARGET_NR_brk:
5448         ret = do_brk(arg1);
5449         break;
5450     case TARGET_NR_fork:
5451         ret = get_errno(do_fork(cpu_env, SIGCHLD, 0, 0, 0, 0));
5452         break;
5453 #ifdef TARGET_NR_waitpid
5454     case TARGET_NR_waitpid:
5455         {
5456             int status;
5457             ret = get_errno(waitpid(arg1, &status, arg3));
5458             if (!is_error(ret) && arg2 && ret
5459                 && put_user_s32(host_to_target_waitstatus(status), arg2))
5460                 goto efault;
5461         }
5462         break;
5463 #endif
5464 #ifdef TARGET_NR_waitid
5465     case TARGET_NR_waitid:
5466         {
5467             siginfo_t info;
5468             info.si_pid = 0;
5469             ret = get_errno(waitid(arg1, arg2, &info, arg4));
5470             if (!is_error(ret) && arg3 && info.si_pid != 0) {
5471                 if (!(p = lock_user(VERIFY_WRITE, arg3, sizeof(target_siginfo_t), 0)))
5472                     goto efault;
5473                 host_to_target_siginfo(p, &info);
5474                 unlock_user(p, arg3, sizeof(target_siginfo_t));
5475             }
5476         }
5477         break;
5478 #endif
5479 #ifdef TARGET_NR_creat /* not on alpha */
5480     case TARGET_NR_creat:
5481         if (!(p = lock_user_string(arg1)))
5482             goto efault;
5483         ret = get_errno(creat(p, arg2));
5484         unlock_user(p, arg1, 0);
5485         break;
5486 #endif
5487     case TARGET_NR_link:
5488         {
5489             void * p2;
5490             p = lock_user_string(arg1);
5491             p2 = lock_user_string(arg2);
5492             if (!p || !p2)
5493                 ret = -TARGET_EFAULT;
5494             else
5495                 ret = get_errno(link(p, p2));
5496             unlock_user(p2, arg2, 0);
5497             unlock_user(p, arg1, 0);
5498         }
5499         break;
5500 #if defined(TARGET_NR_linkat)
5501     case TARGET_NR_linkat:
5502         {
5503             void * p2 = NULL;
5504             if (!arg2 || !arg4)
5505                 goto efault;
5506             p  = lock_user_string(arg2);
5507             p2 = lock_user_string(arg4);
5508             if (!p || !p2)
5509                 ret = -TARGET_EFAULT;
5510             else
5511                 ret = get_errno(linkat(arg1, p, arg3, p2, arg5));
5512             unlock_user(p, arg2, 0);
5513             unlock_user(p2, arg4, 0);
5514         }
5515         break;
5516 #endif
5517     case TARGET_NR_unlink:
5518         if (!(p = lock_user_string(arg1)))
5519             goto efault;
5520         ret = get_errno(unlink(p));
5521         unlock_user(p, arg1, 0);
5522         break;
5523 #if defined(TARGET_NR_unlinkat)
5524     case TARGET_NR_unlinkat:
5525         if (!(p = lock_user_string(arg2)))
5526             goto efault;
5527         ret = get_errno(unlinkat(arg1, p, arg3));
5528         unlock_user(p, arg2, 0);
5529         break;
5530 #endif
5531     case TARGET_NR_execve:
5532         {
5533             char **argp, **envp;
5534             int argc, envc;
5535             abi_ulong gp;
5536             abi_ulong guest_argp;
5537             abi_ulong guest_envp;
5538             abi_ulong addr;
5539             char **q;
5540             int total_size = 0;
5541
5542             argc = 0;
5543             guest_argp = arg2;
5544             for (gp = guest_argp; gp; gp += sizeof(abi_ulong)) {
5545                 if (get_user_ual(addr, gp))
5546                     goto efault;
5547                 if (!addr)
5548                     break;
5549                 argc++;
5550             }
5551             envc = 0;
5552             guest_envp = arg3;
5553             for (gp = guest_envp; gp; gp += sizeof(abi_ulong)) {
5554                 if (get_user_ual(addr, gp))
5555                     goto efault;
5556                 if (!addr)
5557                     break;
5558                 envc++;
5559             }
5560
5561             argp = alloca((argc + 1) * sizeof(void *));
5562             envp = alloca((envc + 1) * sizeof(void *));
5563
5564             for (gp = guest_argp, q = argp; gp;
5565                   gp += sizeof(abi_ulong), q++) {
5566                 if (get_user_ual(addr, gp))
5567                     goto execve_efault;
5568                 if (!addr)
5569                     break;
5570                 if (!(*q = lock_user_string(addr)))
5571                     goto execve_efault;
5572                 total_size += strlen(*q) + 1;
5573             }
5574             *q = NULL;
5575
5576             for (gp = guest_envp, q = envp; gp;
5577                   gp += sizeof(abi_ulong), q++) {
5578                 if (get_user_ual(addr, gp))
5579                     goto execve_efault;
5580                 if (!addr)
5581                     break;
5582                 if (!(*q = lock_user_string(addr)))
5583                     goto execve_efault;
5584                 total_size += strlen(*q) + 1;
5585             }
5586             *q = NULL;
5587
5588             /* This case will not be caught by the host's execve() if its
5589                page size is bigger than the target's. */
5590             if (total_size > MAX_ARG_PAGES * TARGET_PAGE_SIZE) {
5591                 ret = -TARGET_E2BIG;
5592                 goto execve_end;
5593             }
5594             if (!(p = lock_user_string(arg1)))
5595                 goto execve_efault;
5596             ret = get_errno(execve(p, argp, envp));
5597             unlock_user(p, arg1, 0);
5598
5599             goto execve_end;
5600
5601         execve_efault:
5602             ret = -TARGET_EFAULT;
5603
5604         execve_end:
5605             for (gp = guest_argp, q = argp; *q;
5606                   gp += sizeof(abi_ulong), q++) {
5607                 if (get_user_ual(addr, gp)
5608                     || !addr)
5609                     break;
5610                 unlock_user(*q, addr, 0);
5611             }
5612             for (gp = guest_envp, q = envp; *q;
5613                   gp += sizeof(abi_ulong), q++) {
5614                 if (get_user_ual(addr, gp)
5615                     || !addr)
5616                     break;
5617                 unlock_user(*q, addr, 0);
5618             }
5619         }
5620         break;
5621     case TARGET_NR_chdir:
5622         if (!(p = lock_user_string(arg1)))
5623             goto efault;
5624         ret = get_errno(chdir(p));
5625         unlock_user(p, arg1, 0);
5626         break;
5627 #ifdef TARGET_NR_time
5628     case TARGET_NR_time:
5629         {
5630             time_t host_time;
5631             ret = get_errno(time(&host_time));
5632             if (!is_error(ret)
5633                 && arg1
5634                 && put_user_sal(host_time, arg1))
5635                 goto efault;
5636         }
5637         break;
5638 #endif
5639     case TARGET_NR_mknod:
5640         if (!(p = lock_user_string(arg1)))
5641             goto efault;
5642         ret = get_errno(mknod(p, arg2, arg3));
5643         unlock_user(p, arg1, 0);
5644         break;
5645 #if defined(TARGET_NR_mknodat)
5646     case TARGET_NR_mknodat:
5647         if (!(p = lock_user_string(arg2)))
5648             goto efault;
5649         ret = get_errno(mknodat(arg1, p, arg3, arg4));
5650         unlock_user(p, arg2, 0);
5651         break;
5652 #endif
5653     case TARGET_NR_chmod:
5654         if (!(p = lock_user_string(arg1)))
5655             goto efault;
5656         ret = get_errno(chmod(p, arg2));
5657         unlock_user(p, arg1, 0);
5658         break;
5659 #ifdef TARGET_NR_break
5660     case TARGET_NR_break:
5661         goto unimplemented;
5662 #endif
5663 #ifdef TARGET_NR_oldstat
5664     case TARGET_NR_oldstat:
5665         goto unimplemented;
5666 #endif
5667     case TARGET_NR_lseek:
5668         ret = get_errno(lseek(arg1, arg2, arg3));
5669         break;
5670 #if defined(TARGET_NR_getxpid) && defined(TARGET_ALPHA)
5671     /* Alpha specific */
5672     case TARGET_NR_getxpid:
5673         ((CPUAlphaState *)cpu_env)->ir[IR_A4] = getppid();
5674         ret = get_errno(getpid());
5675         break;
5676 #endif
5677 #ifdef TARGET_NR_getpid
5678     case TARGET_NR_getpid:
5679         ret = get_errno(getpid());
5680         break;
5681 #endif
5682     case TARGET_NR_mount:
5683         {
5684             /* need to look at the data field */
5685             void *p2, *p3;
5686
5687             if (arg1) {
5688                 p = lock_user_string(arg1);
5689                 if (!p) {
5690                     goto efault;
5691                 }
5692             } else {
5693                 p = NULL;
5694             }
5695
5696             p2 = lock_user_string(arg2);
5697             if (!p2) {
5698                 if (arg1) {
5699                     unlock_user(p, arg1, 0);
5700                 }
5701                 goto efault;
5702             }
5703
5704             if (arg3) {
5705                 p3 = lock_user_string(arg3);
5706                 if (!p3) {
5707                     if (arg1) {
5708                         unlock_user(p, arg1, 0);
5709                     }
5710                     unlock_user(p2, arg2, 0);
5711                     goto efault;
5712                 }
5713             } else {
5714                 p3 = NULL;
5715             }
5716
5717             /* FIXME - arg5 should be locked, but it isn't clear how to
5718              * do that since it's not guaranteed to be a NULL-terminated
5719              * string.
5720              */
5721             if (!arg5) {
5722                 ret = mount(p, p2, p3, (unsigned long)arg4, NULL);
5723             } else {
5724                 ret = mount(p, p2, p3, (unsigned long)arg4, g2h(arg5));
5725             }
5726             ret = get_errno(ret);
5727
5728             if (arg1) {
5729                 unlock_user(p, arg1, 0);
5730             }
5731             unlock_user(p2, arg2, 0);
5732             if (arg3) {
5733                 unlock_user(p3, arg3, 0);
5734             }
5735         }
5736         break;
5737 #ifdef TARGET_NR_umount
5738     case TARGET_NR_umount:
5739         if (!(p = lock_user_string(arg1)))
5740             goto efault;
5741         ret = get_errno(umount(p));
5742         unlock_user(p, arg1, 0);
5743         break;
5744 #endif
5745 #ifdef TARGET_NR_stime /* not on alpha */
5746     case TARGET_NR_stime:
5747         {
5748             time_t host_time;
5749             if (get_user_sal(host_time, arg1))
5750                 goto efault;
5751             ret = get_errno(stime(&host_time));
5752         }
5753         break;
5754 #endif
5755     case TARGET_NR_ptrace:
5756         goto unimplemented;
5757 #ifdef TARGET_NR_alarm /* not on alpha */
5758     case TARGET_NR_alarm:
5759         ret = alarm(arg1);
5760         break;
5761 #endif
5762 #ifdef TARGET_NR_oldfstat
5763     case TARGET_NR_oldfstat:
5764         goto unimplemented;
5765 #endif
5766 #ifdef TARGET_NR_pause /* not on alpha */
5767     case TARGET_NR_pause:
5768         ret = get_errno(pause());
5769         break;
5770 #endif
5771 #ifdef TARGET_NR_utime
5772     case TARGET_NR_utime:
5773         {
5774             struct utimbuf tbuf, *host_tbuf;
5775             struct target_utimbuf *target_tbuf;
5776             if (arg2) {
5777                 if (!lock_user_struct(VERIFY_READ, target_tbuf, arg2, 1))
5778                     goto efault;
5779                 tbuf.actime = tswapal(target_tbuf->actime);
5780                 tbuf.modtime = tswapal(target_tbuf->modtime);
5781                 unlock_user_struct(target_tbuf, arg2, 0);
5782                 host_tbuf = &tbuf;
5783             } else {
5784                 host_tbuf = NULL;
5785             }
5786             if (!(p = lock_user_string(arg1)))
5787                 goto efault;
5788             ret = get_errno(utime(p, host_tbuf));
5789             unlock_user(p, arg1, 0);
5790         }
5791         break;
5792 #endif
5793     case TARGET_NR_utimes:
5794         {
5795             struct timeval *tvp, tv[2];
5796             if (arg2) {
5797                 if (copy_from_user_timeval(&tv[0], arg2)
5798                     || copy_from_user_timeval(&tv[1],
5799                                               arg2 + sizeof(struct target_timeval)))
5800                     goto efault;
5801                 tvp = tv;
5802             } else {
5803                 tvp = NULL;
5804             }
5805             if (!(p = lock_user_string(arg1)))
5806                 goto efault;
5807             ret = get_errno(utimes(p, tvp));
5808             unlock_user(p, arg1, 0);
5809         }
5810         break;
5811 #if defined(TARGET_NR_futimesat)
5812     case TARGET_NR_futimesat:
5813         {
5814             struct timeval *tvp, tv[2];
5815             if (arg3) {
5816                 if (copy_from_user_timeval(&tv[0], arg3)
5817                     || copy_from_user_timeval(&tv[1],
5818                                               arg3 + sizeof(struct target_timeval)))
5819                     goto efault;
5820                 tvp = tv;
5821             } else {
5822                 tvp = NULL;
5823             }
5824             if (!(p = lock_user_string(arg2)))
5825                 goto efault;
5826             ret = get_errno(futimesat(arg1, path(p), tvp));
5827             unlock_user(p, arg2, 0);
5828         }
5829         break;
5830 #endif
5831 #ifdef TARGET_NR_stty
5832     case TARGET_NR_stty:
5833         goto unimplemented;
5834 #endif
5835 #ifdef TARGET_NR_gtty
5836     case TARGET_NR_gtty:
5837         goto unimplemented;
5838 #endif
5839     case TARGET_NR_access:
5840         if (!(p = lock_user_string(arg1)))
5841             goto efault;
5842         ret = get_errno(access(path(p), arg2));
5843         unlock_user(p, arg1, 0);
5844         break;
5845 #if defined(TARGET_NR_faccessat) && defined(__NR_faccessat)
5846     case TARGET_NR_faccessat:
5847         if (!(p = lock_user_string(arg2)))
5848             goto efault;
5849         ret = get_errno(faccessat(arg1, p, arg3, 0));
5850         unlock_user(p, arg2, 0);
5851         break;
5852 #endif
5853 #ifdef TARGET_NR_nice /* not on alpha */
5854     case TARGET_NR_nice:
5855         ret = get_errno(nice(arg1));
5856         break;
5857 #endif
5858 #ifdef TARGET_NR_ftime
5859     case TARGET_NR_ftime:
5860         goto unimplemented;
5861 #endif
5862     case TARGET_NR_sync:
5863         sync();
5864         ret = 0;
5865         break;
5866     case TARGET_NR_kill:
5867         ret = get_errno(kill(arg1, target_to_host_signal(arg2)));
5868         break;
5869     case TARGET_NR_rename:
5870         {
5871             void *p2;
5872             p = lock_user_string(arg1);
5873             p2 = lock_user_string(arg2);
5874             if (!p || !p2)
5875                 ret = -TARGET_EFAULT;
5876             else
5877                 ret = get_errno(rename(p, p2));
5878             unlock_user(p2, arg2, 0);
5879             unlock_user(p, arg1, 0);
5880         }
5881         break;
5882 #if defined(TARGET_NR_renameat)
5883     case TARGET_NR_renameat:
5884         {
5885             void *p2;
5886             p  = lock_user_string(arg2);
5887             p2 = lock_user_string(arg4);
5888             if (!p || !p2)
5889                 ret = -TARGET_EFAULT;
5890             else
5891                 ret = get_errno(renameat(arg1, p, arg3, p2));
5892             unlock_user(p2, arg4, 0);
5893             unlock_user(p, arg2, 0);
5894         }
5895         break;
5896 #endif
5897     case TARGET_NR_mkdir:
5898         if (!(p = lock_user_string(arg1)))
5899             goto efault;
5900         ret = get_errno(mkdir(p, arg2));
5901         unlock_user(p, arg1, 0);
5902         break;
5903 #if defined(TARGET_NR_mkdirat)
5904     case TARGET_NR_mkdirat:
5905         if (!(p = lock_user_string(arg2)))
5906             goto efault;
5907         ret = get_errno(mkdirat(arg1, p, arg3));
5908         unlock_user(p, arg2, 0);
5909         break;
5910 #endif
5911     case TARGET_NR_rmdir:
5912         if (!(p = lock_user_string(arg1)))
5913             goto efault;
5914         ret = get_errno(rmdir(p));
5915         unlock_user(p, arg1, 0);
5916         break;
5917     case TARGET_NR_dup:
5918         ret = get_errno(dup(arg1));
5919         break;
5920     case TARGET_NR_pipe:
5921         ret = do_pipe(cpu_env, arg1, 0, 0);
5922         break;
5923 #ifdef TARGET_NR_pipe2
5924     case TARGET_NR_pipe2:
5925         ret = do_pipe(cpu_env, arg1,
5926                       target_to_host_bitmask(arg2, fcntl_flags_tbl), 1);
5927         break;
5928 #endif
5929     case TARGET_NR_times:
5930         {
5931             struct target_tms *tmsp;
5932             struct tms tms;
5933             ret = get_errno(times(&tms));
5934             if (arg1) {
5935                 tmsp = lock_user(VERIFY_WRITE, arg1, sizeof(struct target_tms), 0);
5936                 if (!tmsp)
5937                     goto efault;
5938                 tmsp->tms_utime = tswapal(host_to_target_clock_t(tms.tms_utime));
5939                 tmsp->tms_stime = tswapal(host_to_target_clock_t(tms.tms_stime));
5940                 tmsp->tms_cutime = tswapal(host_to_target_clock_t(tms.tms_cutime));
5941                 tmsp->tms_cstime = tswapal(host_to_target_clock_t(tms.tms_cstime));
5942             }
5943             if (!is_error(ret))
5944                 ret = host_to_target_clock_t(ret);
5945         }
5946         break;
5947 #ifdef TARGET_NR_prof
5948     case TARGET_NR_prof:
5949         goto unimplemented;
5950 #endif
5951 #ifdef TARGET_NR_signal
5952     case TARGET_NR_signal:
5953         goto unimplemented;
5954 #endif
5955     case TARGET_NR_acct:
5956         if (arg1 == 0) {
5957             ret = get_errno(acct(NULL));
5958         } else {
5959             if (!(p = lock_user_string(arg1)))
5960                 goto efault;
5961             ret = get_errno(acct(path(p)));
5962             unlock_user(p, arg1, 0);
5963         }
5964         break;
5965 #ifdef TARGET_NR_umount2
5966     case TARGET_NR_umount2:
5967         if (!(p = lock_user_string(arg1)))
5968             goto efault;
5969         ret = get_errno(umount2(p, arg2));
5970         unlock_user(p, arg1, 0);
5971         break;
5972 #endif
5973 #ifdef TARGET_NR_lock
5974     case TARGET_NR_lock:
5975         goto unimplemented;
5976 #endif
5977     case TARGET_NR_ioctl:
5978         ret = do_ioctl(arg1, arg2, arg3);
5979         break;
5980     case TARGET_NR_fcntl:
5981         ret = do_fcntl(arg1, arg2, arg3);
5982         break;
5983 #ifdef TARGET_NR_mpx
5984     case TARGET_NR_mpx:
5985         goto unimplemented;
5986 #endif
5987     case TARGET_NR_setpgid:
5988         ret = get_errno(setpgid(arg1, arg2));
5989         break;
5990 #ifdef TARGET_NR_ulimit
5991     case TARGET_NR_ulimit:
5992         goto unimplemented;
5993 #endif
5994 #ifdef TARGET_NR_oldolduname
5995     case TARGET_NR_oldolduname:
5996         goto unimplemented;
5997 #endif
5998     case TARGET_NR_umask:
5999         ret = get_errno(umask(arg1));
6000         break;
6001     case TARGET_NR_chroot:
6002         if (!(p = lock_user_string(arg1)))
6003             goto efault;
6004         ret = get_errno(chroot(p));
6005         unlock_user(p, arg1, 0);
6006         break;
6007     case TARGET_NR_ustat:
6008         goto unimplemented;
6009     case TARGET_NR_dup2:
6010         ret = get_errno(dup2(arg1, arg2));
6011         break;
6012 #if defined(CONFIG_DUP3) && defined(TARGET_NR_dup3)
6013     case TARGET_NR_dup3:
6014         ret = get_errno(dup3(arg1, arg2, arg3));
6015         break;
6016 #endif
6017 #ifdef TARGET_NR_getppid /* not on alpha */
6018     case TARGET_NR_getppid:
6019         ret = get_errno(getppid());
6020         break;
6021 #endif
6022     case TARGET_NR_getpgrp:
6023         ret = get_errno(getpgrp());
6024         break;
6025     case TARGET_NR_setsid:
6026         ret = get_errno(setsid());
6027         break;
6028 #ifdef TARGET_NR_sigaction
6029     case TARGET_NR_sigaction:
6030         {
6031 #if defined(TARGET_ALPHA)
6032             struct target_sigaction act, oact, *pact = 0;
6033             struct target_old_sigaction *old_act;
6034             if (arg2) {
6035                 if (!lock_user_struct(VERIFY_READ, old_act, arg2, 1))
6036                     goto efault;
6037                 act._sa_handler = old_act->_sa_handler;
6038                 target_siginitset(&act.sa_mask, old_act->sa_mask);
6039                 act.sa_flags = old_act->sa_flags;
6040                 act.sa_restorer = 0;
6041                 unlock_user_struct(old_act, arg2, 0);
6042                 pact = &act;
6043             }
6044             ret = get_errno(do_sigaction(arg1, pact, &oact));
6045             if (!is_error(ret) && arg3) {
6046                 if (!lock_user_struct(VERIFY_WRITE, old_act, arg3, 0))
6047                     goto efault;
6048                 old_act->_sa_handler = oact._sa_handler;
6049                 old_act->sa_mask = oact.sa_mask.sig[0];
6050                 old_act->sa_flags = oact.sa_flags;
6051                 unlock_user_struct(old_act, arg3, 1);
6052             }
6053 #elif defined(TARGET_MIPS)
6054             struct target_sigaction act, oact, *pact, *old_act;
6055
6056             if (arg2) {
6057                 if (!lock_user_struct(VERIFY_READ, old_act, arg2, 1))
6058                     goto efault;
6059                 act._sa_handler = old_act->_sa_handler;
6060                 target_siginitset(&act.sa_mask, old_act->sa_mask.sig[0]);
6061                 act.sa_flags = old_act->sa_flags;
6062                 unlock_user_struct(old_act, arg2, 0);
6063                 pact = &act;
6064             } else {
6065                 pact = NULL;
6066             }
6067
6068             ret = get_errno(do_sigaction(arg1, pact, &oact));
6069
6070             if (!is_error(ret) && arg3) {
6071                 if (!lock_user_struct(VERIFY_WRITE, old_act, arg3, 0))
6072                     goto efault;
6073                 old_act->_sa_handler = oact._sa_handler;
6074                 old_act->sa_flags = oact.sa_flags;
6075                 old_act->sa_mask.sig[0] = oact.sa_mask.sig[0];
6076                 old_act->sa_mask.sig[1] = 0;
6077                 old_act->sa_mask.sig[2] = 0;
6078                 old_act->sa_mask.sig[3] = 0;
6079                 unlock_user_struct(old_act, arg3, 1);
6080             }
6081 #else
6082             struct target_old_sigaction *old_act;
6083             struct target_sigaction act, oact, *pact;
6084             if (arg2) {
6085                 if (!lock_user_struct(VERIFY_READ, old_act, arg2, 1))
6086                     goto efault;
6087                 act._sa_handler = old_act->_sa_handler;
6088                 target_siginitset(&act.sa_mask, old_act->sa_mask);
6089                 act.sa_flags = old_act->sa_flags;
6090                 act.sa_restorer = old_act->sa_restorer;
6091                 unlock_user_struct(old_act, arg2, 0);
6092                 pact = &act;
6093             } else {
6094                 pact = NULL;
6095             }
6096             ret = get_errno(do_sigaction(arg1, pact, &oact));
6097             if (!is_error(ret) && arg3) {
6098                 if (!lock_user_struct(VERIFY_WRITE, old_act, arg3, 0))
6099                     goto efault;
6100                 old_act->_sa_handler = oact._sa_handler;
6101                 old_act->sa_mask = oact.sa_mask.sig[0];
6102                 old_act->sa_flags = oact.sa_flags;
6103                 old_act->sa_restorer = oact.sa_restorer;
6104                 unlock_user_struct(old_act, arg3, 1);
6105             }
6106 #endif
6107         }
6108         break;
6109 #endif
6110     case TARGET_NR_rt_sigaction:
6111         {
6112 #if defined(TARGET_ALPHA)
6113             struct target_sigaction act, oact, *pact = 0;
6114             struct target_rt_sigaction *rt_act;
6115             /* ??? arg4 == sizeof(sigset_t).  */
6116             if (arg2) {
6117                 if (!lock_user_struct(VERIFY_READ, rt_act, arg2, 1))
6118                     goto efault;
6119                 act._sa_handler = rt_act->_sa_handler;
6120                 act.sa_mask = rt_act->sa_mask;
6121                 act.sa_flags = rt_act->sa_flags;
6122                 act.sa_restorer = arg5;
6123                 unlock_user_struct(rt_act, arg2, 0);
6124                 pact = &act;
6125             }
6126             ret = get_errno(do_sigaction(arg1, pact, &oact));
6127             if (!is_error(ret) && arg3) {
6128                 if (!lock_user_struct(VERIFY_WRITE, rt_act, arg3, 0))
6129                     goto efault;
6130                 rt_act->_sa_handler = oact._sa_handler;
6131                 rt_act->sa_mask = oact.sa_mask;
6132                 rt_act->sa_flags = oact.sa_flags;
6133                 unlock_user_struct(rt_act, arg3, 1);
6134             }
6135 #else
6136             struct target_sigaction *act;
6137             struct target_sigaction *oact;
6138
6139             if (arg2) {
6140                 if (!lock_user_struct(VERIFY_READ, act, arg2, 1))
6141                     goto efault;
6142             } else
6143                 act = NULL;
6144             if (arg3) {
6145                 if (!lock_user_struct(VERIFY_WRITE, oact, arg3, 0)) {
6146                     ret = -TARGET_EFAULT;
6147                     goto rt_sigaction_fail;
6148                 }
6149             } else
6150                 oact = NULL;
6151             ret = get_errno(do_sigaction(arg1, act, oact));
6152         rt_sigaction_fail:
6153             if (act)
6154                 unlock_user_struct(act, arg2, 0);
6155             if (oact)
6156                 unlock_user_struct(oact, arg3, 1);
6157 #endif
6158         }
6159         break;
6160 #ifdef TARGET_NR_sgetmask /* not on alpha */
6161     case TARGET_NR_sgetmask:
6162         {
6163             sigset_t cur_set;
6164             abi_ulong target_set;
6165             do_sigprocmask(0, NULL, &cur_set);
6166             host_to_target_old_sigset(&target_set, &cur_set);
6167             ret = target_set;
6168         }
6169         break;
6170 #endif
6171 #ifdef TARGET_NR_ssetmask /* not on alpha */
6172     case TARGET_NR_ssetmask:
6173         {
6174             sigset_t set, oset, cur_set;
6175             abi_ulong target_set = arg1;
6176             do_sigprocmask(0, NULL, &cur_set);
6177             target_to_host_old_sigset(&set, &target_set);
6178             sigorset(&set, &set, &cur_set);
6179             do_sigprocmask(SIG_SETMASK, &set, &oset);
6180             host_to_target_old_sigset(&target_set, &oset);
6181             ret = target_set;
6182         }
6183         break;
6184 #endif
6185 #ifdef TARGET_NR_sigprocmask
6186     case TARGET_NR_sigprocmask:
6187         {
6188 #if defined(TARGET_ALPHA)
6189             sigset_t set, oldset;
6190             abi_ulong mask;
6191             int how;
6192
6193             switch (arg1) {
6194             case TARGET_SIG_BLOCK:
6195                 how = SIG_BLOCK;
6196                 break;
6197             case TARGET_SIG_UNBLOCK:
6198                 how = SIG_UNBLOCK;
6199                 break;
6200             case TARGET_SIG_SETMASK:
6201                 how = SIG_SETMASK;
6202                 break;
6203             default:
6204                 ret = -TARGET_EINVAL;
6205                 goto fail;
6206             }
6207             mask = arg2;
6208             target_to_host_old_sigset(&set, &mask);
6209
6210             ret = get_errno(do_sigprocmask(how, &set, &oldset));
6211             if (!is_error(ret)) {
6212                 host_to_target_old_sigset(&mask, &oldset);
6213                 ret = mask;
6214                 ((CPUAlphaState *)cpu_env)->ir[IR_V0] = 0; /* force no error */
6215             }
6216 #else
6217             sigset_t set, oldset, *set_ptr;
6218             int how;
6219
6220             if (arg2) {
6221                 switch (arg1) {
6222                 case TARGET_SIG_BLOCK:
6223                     how = SIG_BLOCK;
6224                     break;
6225                 case TARGET_SIG_UNBLOCK:
6226                     how = SIG_UNBLOCK;
6227                     break;
6228                 case TARGET_SIG_SETMASK:
6229                     how = SIG_SETMASK;
6230                     break;
6231                 default:
6232                     ret = -TARGET_EINVAL;
6233                     goto fail;
6234                 }
6235                 if (!(p = lock_user(VERIFY_READ, arg2, sizeof(target_sigset_t), 1)))
6236                     goto efault;
6237                 target_to_host_old_sigset(&set, p);
6238                 unlock_user(p, arg2, 0);
6239                 set_ptr = &set;
6240             } else {
6241                 how = 0;
6242                 set_ptr = NULL;
6243             }
6244             ret = get_errno(do_sigprocmask(how, set_ptr, &oldset));
6245             if (!is_error(ret) && arg3) {
6246                 if (!(p = lock_user(VERIFY_WRITE, arg3, sizeof(target_sigset_t), 0)))
6247                     goto efault;
6248                 host_to_target_old_sigset(p, &oldset);
6249                 unlock_user(p, arg3, sizeof(target_sigset_t));
6250             }
6251 #endif
6252         }
6253         break;
6254 #endif
6255     case TARGET_NR_rt_sigprocmask:
6256         {
6257             int how = arg1;
6258             sigset_t set, oldset, *set_ptr;
6259
6260             if (arg2) {
6261                 switch(how) {
6262                 case TARGET_SIG_BLOCK:
6263                     how = SIG_BLOCK;
6264                     break;
6265                 case TARGET_SIG_UNBLOCK:
6266                     how = SIG_UNBLOCK;
6267                     break;
6268                 case TARGET_SIG_SETMASK:
6269                     how = SIG_SETMASK;
6270                     break;
6271                 default:
6272                     ret = -TARGET_EINVAL;
6273                     goto fail;
6274                 }
6275                 if (!(p = lock_user(VERIFY_READ, arg2, sizeof(target_sigset_t), 1)))
6276                     goto efault;
6277                 target_to_host_sigset(&set, p);
6278                 unlock_user(p, arg2, 0);
6279                 set_ptr = &set;
6280             } else {
6281                 how = 0;
6282                 set_ptr = NULL;
6283             }
6284             ret = get_errno(do_sigprocmask(how, set_ptr, &oldset));
6285             if (!is_error(ret) && arg3) {
6286                 if (!(p = lock_user(VERIFY_WRITE, arg3, sizeof(target_sigset_t), 0)))
6287                     goto efault;
6288                 host_to_target_sigset(p, &oldset);
6289                 unlock_user(p, arg3, sizeof(target_sigset_t));
6290             }
6291         }
6292         break;
6293 #ifdef TARGET_NR_sigpending
6294     case TARGET_NR_sigpending:
6295         {
6296             sigset_t set;
6297             ret = get_errno(sigpending(&set));
6298             if (!is_error(ret)) {
6299                 if (!(p = lock_user(VERIFY_WRITE, arg1, sizeof(target_sigset_t), 0)))
6300                     goto efault;
6301                 host_to_target_old_sigset(p, &set);
6302                 unlock_user(p, arg1, sizeof(target_sigset_t));
6303             }
6304         }
6305         break;
6306 #endif
6307     case TARGET_NR_rt_sigpending:
6308         {
6309             sigset_t set;
6310             ret = get_errno(sigpending(&set));
6311             if (!is_error(ret)) {
6312                 if (!(p = lock_user(VERIFY_WRITE, arg1, sizeof(target_sigset_t), 0)))
6313                     goto efault;
6314                 host_to_target_sigset(p, &set);
6315                 unlock_user(p, arg1, sizeof(target_sigset_t));
6316             }
6317         }
6318         break;
6319 #ifdef TARGET_NR_sigsuspend
6320     case TARGET_NR_sigsuspend:
6321         {
6322             sigset_t set;
6323 #if defined(TARGET_ALPHA)
6324             abi_ulong mask = arg1;
6325             target_to_host_old_sigset(&set, &mask);
6326 #else
6327             if (!(p = lock_user(VERIFY_READ, arg1, sizeof(target_sigset_t), 1)))
6328                 goto efault;
6329             target_to_host_old_sigset(&set, p);
6330             unlock_user(p, arg1, 0);
6331 #endif
6332             ret = get_errno(sigsuspend(&set));
6333         }
6334         break;
6335 #endif
6336     case TARGET_NR_rt_sigsuspend:
6337         {
6338             sigset_t set;
6339             if (!(p = lock_user(VERIFY_READ, arg1, sizeof(target_sigset_t), 1)))
6340                 goto efault;
6341             target_to_host_sigset(&set, p);
6342             unlock_user(p, arg1, 0);
6343             ret = get_errno(sigsuspend(&set));
6344         }
6345         break;
6346     case TARGET_NR_rt_sigtimedwait:
6347         {
6348             sigset_t set;
6349             struct timespec uts, *puts;
6350             siginfo_t uinfo;
6351
6352             if (!(p = lock_user(VERIFY_READ, arg1, sizeof(target_sigset_t), 1)))
6353                 goto efault;
6354             target_to_host_sigset(&set, p);
6355             unlock_user(p, arg1, 0);
6356             if (arg3) {
6357                 puts = &uts;
6358                 target_to_host_timespec(puts, arg3);
6359             } else {
6360                 puts = NULL;
6361             }
6362             ret = get_errno(sigtimedwait(&set, &uinfo, puts));
6363             if (!is_error(ret)) {
6364                 if (arg2) {
6365                     p = lock_user(VERIFY_WRITE, arg2, sizeof(target_siginfo_t),
6366                                   0);
6367                     if (!p) {
6368                         goto efault;
6369                     }
6370                     host_to_target_siginfo(p, &uinfo);
6371                     unlock_user(p, arg2, sizeof(target_siginfo_t));
6372                 }
6373                 ret = host_to_target_signal(ret);
6374             }
6375         }
6376         break;
6377     case TARGET_NR_rt_sigqueueinfo:
6378         {
6379             siginfo_t uinfo;
6380             if (!(p = lock_user(VERIFY_READ, arg3, sizeof(target_sigset_t), 1)))
6381                 goto efault;
6382             target_to_host_siginfo(&uinfo, p);
6383             unlock_user(p, arg1, 0);
6384             ret = get_errno(sys_rt_sigqueueinfo(arg1, arg2, &uinfo));
6385         }
6386         break;
6387 #ifdef TARGET_NR_sigreturn
6388     case TARGET_NR_sigreturn:
6389         /* NOTE: ret is eax, so not transcoding must be done */
6390         ret = do_sigreturn(cpu_env);
6391         break;
6392 #endif
6393     case TARGET_NR_rt_sigreturn:
6394         /* NOTE: ret is eax, so not transcoding must be done */
6395         ret = do_rt_sigreturn(cpu_env);
6396         break;
6397     case TARGET_NR_sethostname:
6398         if (!(p = lock_user_string(arg1)))
6399             goto efault;
6400         ret = get_errno(sethostname(p, arg2));
6401         unlock_user(p, arg1, 0);
6402         break;
6403     case TARGET_NR_setrlimit:
6404         {
6405             int resource = target_to_host_resource(arg1);
6406             struct target_rlimit *target_rlim;
6407             struct rlimit rlim;
6408             if (!lock_user_struct(VERIFY_READ, target_rlim, arg2, 1))
6409                 goto efault;
6410             rlim.rlim_cur = target_to_host_rlim(target_rlim->rlim_cur);
6411             rlim.rlim_max = target_to_host_rlim(target_rlim->rlim_max);
6412             unlock_user_struct(target_rlim, arg2, 0);
6413             ret = get_errno(setrlimit(resource, &rlim));
6414         }
6415         break;
6416     case TARGET_NR_getrlimit:
6417         {
6418             int resource = target_to_host_resource(arg1);
6419             struct target_rlimit *target_rlim;
6420             struct rlimit rlim;
6421
6422             ret = get_errno(getrlimit(resource, &rlim));
6423             if (!is_error(ret)) {
6424                 if (!lock_user_struct(VERIFY_WRITE, target_rlim, arg2, 0))
6425                     goto efault;
6426                 target_rlim->rlim_cur = host_to_target_rlim(rlim.rlim_cur);
6427                 target_rlim->rlim_max = host_to_target_rlim(rlim.rlim_max);
6428                 unlock_user_struct(target_rlim, arg2, 1);
6429             }
6430         }
6431         break;
6432     case TARGET_NR_getrusage:
6433         {
6434             struct rusage rusage;
6435             ret = get_errno(getrusage(arg1, &rusage));
6436             if (!is_error(ret)) {
6437                 ret = host_to_target_rusage(arg2, &rusage);
6438             }
6439         }
6440         break;
6441     case TARGET_NR_gettimeofday:
6442         {
6443             struct timeval tv;
6444             ret = get_errno(gettimeofday(&tv, NULL));
6445             if (!is_error(ret)) {
6446                 if (copy_to_user_timeval(arg1, &tv))
6447                     goto efault;
6448             }
6449         }
6450         break;
6451     case TARGET_NR_settimeofday:
6452         {
6453             struct timeval tv, *ptv = NULL;
6454             struct timezone tz, *ptz = NULL;
6455
6456             if (arg1) {
6457                 if (copy_from_user_timeval(&tv, arg1)) {
6458                     goto efault;
6459                 }
6460                 ptv = &tv;
6461             }
6462
6463             if (arg2) {
6464                 if (copy_from_user_timezone(&tz, arg2)) {
6465                     goto efault;
6466                 }
6467                 ptz = &tz;
6468             }
6469
6470             ret = get_errno(settimeofday(ptv, ptz));
6471         }
6472         break;
6473 #if defined(TARGET_NR_select)
6474     case TARGET_NR_select:
6475 #if defined(TARGET_S390X) || defined(TARGET_ALPHA)
6476         ret = do_select(arg1, arg2, arg3, arg4, arg5);
6477 #else
6478         {
6479             struct target_sel_arg_struct *sel;
6480             abi_ulong inp, outp, exp, tvp;
6481             long nsel;
6482
6483             if (!lock_user_struct(VERIFY_READ, sel, arg1, 1))
6484                 goto efault;
6485             nsel = tswapal(sel->n);
6486             inp = tswapal(sel->inp);
6487             outp = tswapal(sel->outp);
6488             exp = tswapal(sel->exp);
6489             tvp = tswapal(sel->tvp);
6490             unlock_user_struct(sel, arg1, 0);
6491             ret = do_select(nsel, inp, outp, exp, tvp);
6492         }
6493 #endif
6494         break;
6495 #endif
6496 #ifdef TARGET_NR_pselect6
6497     case TARGET_NR_pselect6:
6498         {
6499             abi_long rfd_addr, wfd_addr, efd_addr, n, ts_addr;
6500             fd_set rfds, wfds, efds;
6501             fd_set *rfds_ptr, *wfds_ptr, *efds_ptr;
6502             struct timespec ts, *ts_ptr;
6503
6504             /*
6505              * The 6th arg is actually two args smashed together,
6506              * so we cannot use the C library.
6507              */
6508             sigset_t set;
6509             struct {
6510                 sigset_t *set;
6511                 size_t size;
6512             } sig, *sig_ptr;
6513
6514             abi_ulong arg_sigset, arg_sigsize, *arg7;
6515             target_sigset_t *target_sigset;
6516
6517             n = arg1;
6518             rfd_addr = arg2;
6519             wfd_addr = arg3;
6520             efd_addr = arg4;
6521             ts_addr = arg5;
6522
6523             ret = copy_from_user_fdset_ptr(&rfds, &rfds_ptr, rfd_addr, n);
6524             if (ret) {
6525                 goto fail;
6526             }
6527             ret = copy_from_user_fdset_ptr(&wfds, &wfds_ptr, wfd_addr, n);
6528             if (ret) {
6529                 goto fail;
6530             }
6531             ret = copy_from_user_fdset_ptr(&efds, &efds_ptr, efd_addr, n);
6532             if (ret) {
6533                 goto fail;
6534             }
6535
6536             /*
6537              * This takes a timespec, and not a timeval, so we cannot
6538              * use the do_select() helper ...
6539              */
6540             if (ts_addr) {
6541                 if (target_to_host_timespec(&ts, ts_addr)) {
6542                     goto efault;
6543                 }
6544                 ts_ptr = &ts;
6545             } else {
6546                 ts_ptr = NULL;
6547             }
6548
6549             /* Extract the two packed args for the sigset */
6550             if (arg6) {
6551                 sig_ptr = &sig;
6552                 sig.size = _NSIG / 8;
6553
6554                 arg7 = lock_user(VERIFY_READ, arg6, sizeof(*arg7) * 2, 1);
6555                 if (!arg7) {
6556                     goto efault;
6557                 }
6558                 arg_sigset = tswapal(arg7[0]);
6559                 arg_sigsize = tswapal(arg7[1]);
6560                 unlock_user(arg7, arg6, 0);
6561
6562                 if (arg_sigset) {
6563                     sig.set = &set;
6564                     if (arg_sigsize != sizeof(*target_sigset)) {
6565                         /* Like the kernel, we enforce correct size sigsets */
6566                         ret = -TARGET_EINVAL;
6567                         goto fail;
6568                     }
6569                     target_sigset = lock_user(VERIFY_READ, arg_sigset,
6570                                               sizeof(*target_sigset), 1);
6571                     if (!target_sigset) {
6572                         goto efault;
6573                     }
6574                     target_to_host_sigset(&set, target_sigset);
6575                     unlock_user(target_sigset, arg_sigset, 0);
6576                 } else {
6577                     sig.set = NULL;
6578                 }
6579             } else {
6580                 sig_ptr = NULL;
6581             }
6582
6583             ret = get_errno(sys_pselect6(n, rfds_ptr, wfds_ptr, efds_ptr,
6584                                          ts_ptr, sig_ptr));
6585
6586             if (!is_error(ret)) {
6587                 if (rfd_addr && copy_to_user_fdset(rfd_addr, &rfds, n))
6588                     goto efault;
6589                 if (wfd_addr && copy_to_user_fdset(wfd_addr, &wfds, n))
6590                     goto efault;
6591                 if (efd_addr && copy_to_user_fdset(efd_addr, &efds, n))
6592                     goto efault;
6593
6594                 if (ts_addr && host_to_target_timespec(ts_addr, &ts))
6595                     goto efault;
6596             }
6597         }
6598         break;
6599 #endif
6600     case TARGET_NR_symlink:
6601         {
6602             void *p2;
6603             p = lock_user_string(arg1);
6604             p2 = lock_user_string(arg2);
6605             if (!p || !p2)
6606                 ret = -TARGET_EFAULT;
6607             else
6608                 ret = get_errno(symlink(p, p2));
6609             unlock_user(p2, arg2, 0);
6610             unlock_user(p, arg1, 0);
6611         }
6612         break;
6613 #if defined(TARGET_NR_symlinkat)
6614     case TARGET_NR_symlinkat:
6615         {
6616             void *p2;
6617             p  = lock_user_string(arg1);
6618             p2 = lock_user_string(arg3);
6619             if (!p || !p2)
6620                 ret = -TARGET_EFAULT;
6621             else
6622                 ret = get_errno(symlinkat(p, arg2, p2));
6623             unlock_user(p2, arg3, 0);
6624             unlock_user(p, arg1, 0);
6625         }
6626         break;
6627 #endif
6628 #ifdef TARGET_NR_oldlstat
6629     case TARGET_NR_oldlstat:
6630         goto unimplemented;
6631 #endif
6632     case TARGET_NR_readlink:
6633         {
6634             void *p2;
6635             p = lock_user_string(arg1);
6636             p2 = lock_user(VERIFY_WRITE, arg2, arg3, 0);
6637             if (!p || !p2) {
6638                 ret = -TARGET_EFAULT;
6639             } else if (is_proc_myself((const char *)p, "exe")) {
6640                 char real[PATH_MAX], *temp;
6641                 temp = realpath(exec_path, real);
6642                 ret = temp == NULL ? get_errno(-1) : strlen(real) ;
6643                 snprintf((char *)p2, arg3, "%s", real);
6644             } else {
6645                 ret = get_errno(readlink(path(p), p2, arg3));
6646             }
6647             unlock_user(p2, arg2, ret);
6648             unlock_user(p, arg1, 0);
6649         }
6650         break;
6651 #if defined(TARGET_NR_readlinkat)
6652     case TARGET_NR_readlinkat:
6653         {
6654             void *p2;
6655             p  = lock_user_string(arg2);
6656             p2 = lock_user(VERIFY_WRITE, arg3, arg4, 0);
6657             if (!p || !p2) {
6658                 ret = -TARGET_EFAULT;
6659             } else if (is_proc_myself((const char *)p, "exe")) {
6660                 char real[PATH_MAX], *temp;
6661                 temp = realpath(exec_path, real);
6662                 ret = temp == NULL ? get_errno(-1) : strlen(real) ;
6663                 snprintf((char *)p2, arg4, "%s", real);
6664             } else {
6665                 ret = get_errno(readlinkat(arg1, path(p), p2, arg4));
6666             }
6667             unlock_user(p2, arg3, ret);
6668             unlock_user(p, arg2, 0);
6669         }
6670         break;
6671 #endif
6672 #ifdef TARGET_NR_uselib
6673     case TARGET_NR_uselib:
6674         goto unimplemented;
6675 #endif
6676 #ifdef TARGET_NR_swapon
6677     case TARGET_NR_swapon:
6678         if (!(p = lock_user_string(arg1)))
6679             goto efault;
6680         ret = get_errno(swapon(p, arg2));
6681         unlock_user(p, arg1, 0);
6682         break;
6683 #endif
6684     case TARGET_NR_reboot:
6685         if (arg3 == LINUX_REBOOT_CMD_RESTART2) {
6686            /* arg4 must be ignored in all other cases */
6687            p = lock_user_string(arg4);
6688            if (!p) {
6689               goto efault;
6690            }
6691            ret = get_errno(reboot(arg1, arg2, arg3, p));
6692            unlock_user(p, arg4, 0);
6693         } else {
6694            ret = get_errno(reboot(arg1, arg2, arg3, NULL));
6695         }
6696         break;
6697 #ifdef TARGET_NR_readdir
6698     case TARGET_NR_readdir:
6699         goto unimplemented;
6700 #endif
6701 #ifdef TARGET_NR_mmap
6702     case TARGET_NR_mmap:
6703 #if (defined(TARGET_I386) && defined(TARGET_ABI32)) || \
6704     (defined(TARGET_ARM) && defined(TARGET_ABI32)) || \
6705     defined(TARGET_M68K) || defined(TARGET_CRIS) || defined(TARGET_MICROBLAZE) \
6706     || defined(TARGET_S390X)
6707         {
6708             abi_ulong *v;
6709             abi_ulong v1, v2, v3, v4, v5, v6;
6710             if (!(v = lock_user(VERIFY_READ, arg1, 6 * sizeof(abi_ulong), 1)))
6711                 goto efault;
6712             v1 = tswapal(v[0]);
6713             v2 = tswapal(v[1]);
6714             v3 = tswapal(v[2]);
6715             v4 = tswapal(v[3]);
6716             v5 = tswapal(v[4]);
6717             v6 = tswapal(v[5]);
6718             unlock_user(v, arg1, 0);
6719             ret = get_errno(target_mmap(v1, v2, v3,
6720                                         target_to_host_bitmask(v4, mmap_flags_tbl),
6721                                         v5, v6));
6722         }
6723 #else
6724         ret = get_errno(target_mmap(arg1, arg2, arg3,
6725                                     target_to_host_bitmask(arg4, mmap_flags_tbl),
6726                                     arg5,
6727                                     arg6));
6728 #endif
6729         break;
6730 #endif
6731 #ifdef TARGET_NR_mmap2
6732     case TARGET_NR_mmap2:
6733 #ifndef MMAP_SHIFT
6734 #define MMAP_SHIFT 12
6735 #endif
6736         ret = get_errno(target_mmap(arg1, arg2, arg3,
6737                                     target_to_host_bitmask(arg4, mmap_flags_tbl),
6738                                     arg5,
6739                                     arg6 << MMAP_SHIFT));
6740         break;
6741 #endif
6742     case TARGET_NR_munmap:
6743         ret = get_errno(target_munmap(arg1, arg2));
6744         break;
6745     case TARGET_NR_mprotect:
6746         {
6747             TaskState *ts = cpu->opaque;
6748             /* Special hack to detect libc making the stack executable.  */
6749             if ((arg3 & PROT_GROWSDOWN)
6750                 && arg1 >= ts->info->stack_limit
6751                 && arg1 <= ts->info->start_stack) {
6752                 arg3 &= ~PROT_GROWSDOWN;
6753                 arg2 = arg2 + arg1 - ts->info->stack_limit;
6754                 arg1 = ts->info->stack_limit;
6755             }
6756         }
6757         ret = get_errno(target_mprotect(arg1, arg2, arg3));
6758         break;
6759 #ifdef TARGET_NR_mremap
6760     case TARGET_NR_mremap:
6761         ret = get_errno(target_mremap(arg1, arg2, arg3, arg4, arg5));
6762         break;
6763 #endif
6764         /* ??? msync/mlock/munlock are broken for softmmu.  */
6765 #ifdef TARGET_NR_msync
6766     case TARGET_NR_msync:
6767         ret = get_errno(msync(g2h(arg1), arg2, arg3));
6768         break;
6769 #endif
6770 #ifdef TARGET_NR_mlock
6771     case TARGET_NR_mlock:
6772         ret = get_errno(mlock(g2h(arg1), arg2));
6773         break;
6774 #endif
6775 #ifdef TARGET_NR_munlock
6776     case TARGET_NR_munlock:
6777         ret = get_errno(munlock(g2h(arg1), arg2));
6778         break;
6779 #endif
6780 #ifdef TARGET_NR_mlockall
6781     case TARGET_NR_mlockall:
6782         ret = get_errno(mlockall(arg1));
6783         break;
6784 #endif
6785 #ifdef TARGET_NR_munlockall
6786     case TARGET_NR_munlockall:
6787         ret = get_errno(munlockall());
6788         break;
6789 #endif
6790     case TARGET_NR_truncate:
6791         if (!(p = lock_user_string(arg1)))
6792             goto efault;
6793         ret = get_errno(truncate(p, arg2));
6794         unlock_user(p, arg1, 0);
6795         break;
6796     case TARGET_NR_ftruncate:
6797         ret = get_errno(ftruncate(arg1, arg2));
6798         break;
6799     case TARGET_NR_fchmod:
6800         ret = get_errno(fchmod(arg1, arg2));
6801         break;
6802 #if defined(TARGET_NR_fchmodat)
6803     case TARGET_NR_fchmodat:
6804         if (!(p = lock_user_string(arg2)))
6805             goto efault;
6806         ret = get_errno(fchmodat(arg1, p, arg3, 0));
6807         unlock_user(p, arg2, 0);
6808         break;
6809 #endif
6810     case TARGET_NR_getpriority:
6811         /* Note that negative values are valid for getpriority, so we must
6812            differentiate based on errno settings.  */
6813         errno = 0;
6814         ret = getpriority(arg1, arg2);
6815         if (ret == -1 && errno != 0) {
6816             ret = -host_to_target_errno(errno);
6817             break;
6818         }
6819 #ifdef TARGET_ALPHA
6820         /* Return value is the unbiased priority.  Signal no error.  */
6821         ((CPUAlphaState *)cpu_env)->ir[IR_V0] = 0;
6822 #else
6823         /* Return value is a biased priority to avoid negative numbers.  */
6824         ret = 20 - ret;
6825 #endif
6826         break;
6827     case TARGET_NR_setpriority:
6828         ret = get_errno(setpriority(arg1, arg2, arg3));
6829         break;
6830 #ifdef TARGET_NR_profil
6831     case TARGET_NR_profil:
6832         goto unimplemented;
6833 #endif
6834     case TARGET_NR_statfs:
6835         if (!(p = lock_user_string(arg1)))
6836             goto efault;
6837         ret = get_errno(statfs(path(p), &stfs));
6838         unlock_user(p, arg1, 0);
6839     convert_statfs:
6840         if (!is_error(ret)) {
6841             struct target_statfs *target_stfs;
6842
6843             if (!lock_user_struct(VERIFY_WRITE, target_stfs, arg2, 0))
6844                 goto efault;
6845             __put_user(stfs.f_type, &target_stfs->f_type);
6846             __put_user(stfs.f_bsize, &target_stfs->f_bsize);
6847             __put_user(stfs.f_blocks, &target_stfs->f_blocks);
6848             __put_user(stfs.f_bfree, &target_stfs->f_bfree);
6849             __put_user(stfs.f_bavail, &target_stfs->f_bavail);
6850             __put_user(stfs.f_files, &target_stfs->f_files);
6851             __put_user(stfs.f_ffree, &target_stfs->f_ffree);
6852             __put_user(stfs.f_fsid.__val[0], &target_stfs->f_fsid.val[0]);
6853             __put_user(stfs.f_fsid.__val[1], &target_stfs->f_fsid.val[1]);
6854             __put_user(stfs.f_namelen, &target_stfs->f_namelen);
6855             __put_user(stfs.f_frsize, &target_stfs->f_frsize);
6856             memset(target_stfs->f_spare, 0, sizeof(target_stfs->f_spare));
6857             unlock_user_struct(target_stfs, arg2, 1);
6858         }
6859         break;
6860     case TARGET_NR_fstatfs:
6861         ret = get_errno(fstatfs(arg1, &stfs));
6862         goto convert_statfs;
6863 #ifdef TARGET_NR_statfs64
6864     case TARGET_NR_statfs64:
6865         if (!(p = lock_user_string(arg1)))
6866             goto efault;
6867         ret = get_errno(statfs(path(p), &stfs));
6868         unlock_user(p, arg1, 0);
6869     convert_statfs64:
6870         if (!is_error(ret)) {
6871             struct target_statfs64 *target_stfs;
6872
6873             if (!lock_user_struct(VERIFY_WRITE, target_stfs, arg3, 0))
6874                 goto efault;
6875             __put_user(stfs.f_type, &target_stfs->f_type);
6876             __put_user(stfs.f_bsize, &target_stfs->f_bsize);
6877             __put_user(stfs.f_blocks, &target_stfs->f_blocks);
6878             __put_user(stfs.f_bfree, &target_stfs->f_bfree);
6879             __put_user(stfs.f_bavail, &target_stfs->f_bavail);
6880             __put_user(stfs.f_files, &target_stfs->f_files);
6881             __put_user(stfs.f_ffree, &target_stfs->f_ffree);
6882             __put_user(stfs.f_fsid.__val[0], &target_stfs->f_fsid.val[0]);
6883             __put_user(stfs.f_fsid.__val[1], &target_stfs->f_fsid.val[1]);
6884             __put_user(stfs.f_namelen, &target_stfs->f_namelen);
6885             __put_user(stfs.f_frsize, &target_stfs->f_frsize);
6886             memset(target_stfs->f_spare, 0, sizeof(target_stfs->f_spare));
6887             unlock_user_struct(target_stfs, arg3, 1);
6888         }
6889         break;
6890     case TARGET_NR_fstatfs64:
6891         ret = get_errno(fstatfs(arg1, &stfs));
6892         goto convert_statfs64;
6893 #endif
6894 #ifdef TARGET_NR_ioperm
6895     case TARGET_NR_ioperm:
6896         goto unimplemented;
6897 #endif
6898 #ifdef TARGET_NR_socketcall
6899     case TARGET_NR_socketcall:
6900         ret = do_socketcall(arg1, arg2);
6901         break;
6902 #endif
6903 #ifdef TARGET_NR_accept
6904     case TARGET_NR_accept:
6905         ret = do_accept4(arg1, arg2, arg3, 0);
6906         break;
6907 #endif
6908 #ifdef TARGET_NR_accept4
6909     case TARGET_NR_accept4:
6910 #ifdef CONFIG_ACCEPT4
6911         ret = do_accept4(arg1, arg2, arg3, arg4);
6912 #else
6913         goto unimplemented;
6914 #endif
6915         break;
6916 #endif
6917 #ifdef TARGET_NR_bind
6918     case TARGET_NR_bind:
6919         ret = do_bind(arg1, arg2, arg3);
6920         break;
6921 #endif
6922 #ifdef TARGET_NR_connect
6923     case TARGET_NR_connect:
6924         ret = do_connect(arg1, arg2, arg3);
6925         break;
6926 #endif
6927 #ifdef TARGET_NR_getpeername
6928     case TARGET_NR_getpeername:
6929         ret = do_getpeername(arg1, arg2, arg3);
6930         break;
6931 #endif
6932 #ifdef TARGET_NR_getsockname
6933     case TARGET_NR_getsockname:
6934         ret = do_getsockname(arg1, arg2, arg3);
6935         break;
6936 #endif
6937 #ifdef TARGET_NR_getsockopt
6938     case TARGET_NR_getsockopt:
6939         ret = do_getsockopt(arg1, arg2, arg3, arg4, arg5);
6940         break;
6941 #endif
6942 #ifdef TARGET_NR_listen
6943     case TARGET_NR_listen:
6944         ret = get_errno(listen(arg1, arg2));
6945         break;
6946 #endif
6947 #ifdef TARGET_NR_recv
6948     case TARGET_NR_recv:
6949         ret = do_recvfrom(arg1, arg2, arg3, arg4, 0, 0);
6950         break;
6951 #endif
6952 #ifdef TARGET_NR_recvfrom
6953     case TARGET_NR_recvfrom:
6954         ret = do_recvfrom(arg1, arg2, arg3, arg4, arg5, arg6);
6955         break;
6956 #endif
6957 #ifdef TARGET_NR_recvmsg
6958     case TARGET_NR_recvmsg:
6959         ret = do_sendrecvmsg(arg1, arg2, arg3, 0);
6960         break;
6961 #endif
6962 #ifdef TARGET_NR_send
6963     case TARGET_NR_send:
6964         ret = do_sendto(arg1, arg2, arg3, arg4, 0, 0);
6965         break;
6966 #endif
6967 #ifdef TARGET_NR_sendmsg
6968     case TARGET_NR_sendmsg:
6969         ret = do_sendrecvmsg(arg1, arg2, arg3, 1);
6970         break;
6971 #endif
6972 #ifdef TARGET_NR_sendmmsg
6973     case TARGET_NR_sendmmsg:
6974         ret = do_sendrecvmmsg(arg1, arg2, arg3, arg4, 1);
6975         break;
6976     case TARGET_NR_recvmmsg:
6977         ret = do_sendrecvmmsg(arg1, arg2, arg3, arg4, 0);
6978         break;
6979 #endif
6980 #ifdef TARGET_NR_sendto
6981     case TARGET_NR_sendto:
6982         ret = do_sendto(arg1, arg2, arg3, arg4, arg5, arg6);
6983         break;
6984 #endif
6985 #ifdef TARGET_NR_shutdown
6986     case TARGET_NR_shutdown:
6987         ret = get_errno(shutdown(arg1, arg2));
6988         break;
6989 #endif
6990 #ifdef TARGET_NR_socket
6991     case TARGET_NR_socket:
6992         ret = do_socket(arg1, arg2, arg3);
6993         break;
6994 #endif
6995 #ifdef TARGET_NR_socketpair
6996     case TARGET_NR_socketpair:
6997         ret = do_socketpair(arg1, arg2, arg3, arg4);
6998         break;
6999 #endif
7000 #ifdef TARGET_NR_setsockopt
7001     case TARGET_NR_setsockopt:
7002         ret = do_setsockopt(arg1, arg2, arg3, arg4, (socklen_t) arg5);
7003         break;
7004 #endif
7005
7006     case TARGET_NR_syslog:
7007         if (!(p = lock_user_string(arg2)))
7008             goto efault;
7009         ret = get_errno(sys_syslog((int)arg1, p, (int)arg3));
7010         unlock_user(p, arg2, 0);
7011         break;
7012
7013     case TARGET_NR_setitimer:
7014         {
7015             struct itimerval value, ovalue, *pvalue;
7016
7017             if (arg2) {
7018                 pvalue = &value;
7019                 if (copy_from_user_timeval(&pvalue->it_interval, arg2)
7020                     || copy_from_user_timeval(&pvalue->it_value,
7021                                               arg2 + sizeof(struct target_timeval)))
7022                     goto efault;
7023             } else {
7024                 pvalue = NULL;
7025             }
7026             ret = get_errno(setitimer(arg1, pvalue, &ovalue));
7027             if (!is_error(ret) && arg3) {
7028                 if (copy_to_user_timeval(arg3,
7029                                          &ovalue.it_interval)
7030                     || copy_to_user_timeval(arg3 + sizeof(struct target_timeval),
7031                                             &ovalue.it_value))
7032                     goto efault;
7033             }
7034         }
7035         break;
7036     case TARGET_NR_getitimer:
7037         {
7038             struct itimerval value;
7039
7040             ret = get_errno(getitimer(arg1, &value));
7041             if (!is_error(ret) && arg2) {
7042                 if (copy_to_user_timeval(arg2,
7043                                          &value.it_interval)
7044                     || copy_to_user_timeval(arg2 + sizeof(struct target_timeval),
7045                                             &value.it_value))
7046                     goto efault;
7047             }
7048         }
7049         break;
7050     case TARGET_NR_stat:
7051         if (!(p = lock_user_string(arg1)))
7052             goto efault;
7053         ret = get_errno(stat(path(p), &st));
7054         unlock_user(p, arg1, 0);
7055         goto do_stat;
7056     case TARGET_NR_lstat:
7057         if (!(p = lock_user_string(arg1)))
7058             goto efault;
7059         ret = get_errno(lstat(path(p), &st));
7060         unlock_user(p, arg1, 0);
7061         goto do_stat;
7062     case TARGET_NR_fstat:
7063         {
7064             ret = get_errno(fstat(arg1, &st));
7065         do_stat:
7066             if (!is_error(ret)) {
7067                 struct target_stat *target_st;
7068
7069                 if (!lock_user_struct(VERIFY_WRITE, target_st, arg2, 0))
7070                     goto efault;
7071                 memset(target_st, 0, sizeof(*target_st));
7072                 __put_user(st.st_dev, &target_st->st_dev);
7073                 __put_user(st.st_ino, &target_st->st_ino);
7074                 __put_user(st.st_mode, &target_st->st_mode);
7075                 __put_user(st.st_uid, &target_st->st_uid);
7076                 __put_user(st.st_gid, &target_st->st_gid);
7077                 __put_user(st.st_nlink, &target_st->st_nlink);
7078                 __put_user(st.st_rdev, &target_st->st_rdev);
7079                 __put_user(st.st_size, &target_st->st_size);
7080                 __put_user(st.st_blksize, &target_st->st_blksize);
7081                 __put_user(st.st_blocks, &target_st->st_blocks);
7082                 __put_user(st.st_atime, &target_st->target_st_atime);
7083                 __put_user(st.st_mtime, &target_st->target_st_mtime);
7084                 __put_user(st.st_ctime, &target_st->target_st_ctime);
7085                 unlock_user_struct(target_st, arg2, 1);
7086             }
7087         }
7088         break;
7089 #ifdef TARGET_NR_olduname
7090     case TARGET_NR_olduname:
7091         goto unimplemented;
7092 #endif
7093 #ifdef TARGET_NR_iopl
7094     case TARGET_NR_iopl:
7095         goto unimplemented;
7096 #endif
7097     case TARGET_NR_vhangup:
7098         ret = get_errno(vhangup());
7099         break;
7100 #ifdef TARGET_NR_idle
7101     case TARGET_NR_idle:
7102         goto unimplemented;
7103 #endif
7104 #ifdef TARGET_NR_syscall
7105     case TARGET_NR_syscall:
7106         ret = do_syscall(cpu_env, arg1 & 0xffff, arg2, arg3, arg4, arg5,
7107                          arg6, arg7, arg8, 0);
7108         break;
7109 #endif
7110     case TARGET_NR_wait4:
7111         {
7112             int status;
7113             abi_long status_ptr = arg2;
7114             struct rusage rusage, *rusage_ptr;
7115             abi_ulong target_rusage = arg4;
7116             abi_long rusage_err;
7117             if (target_rusage)
7118                 rusage_ptr = &rusage;
7119             else
7120                 rusage_ptr = NULL;
7121             ret = get_errno(wait4(arg1, &status, arg3, rusage_ptr));
7122             if (!is_error(ret)) {
7123                 if (status_ptr && ret) {
7124                     status = host_to_target_waitstatus(status);
7125                     if (put_user_s32(status, status_ptr))
7126                         goto efault;
7127                 }
7128                 if (target_rusage) {
7129                     rusage_err = host_to_target_rusage(target_rusage, &rusage);
7130                     if (rusage_err) {
7131                         ret = rusage_err;
7132                     }
7133                 }
7134             }
7135         }
7136         break;
7137 #ifdef TARGET_NR_swapoff
7138     case TARGET_NR_swapoff:
7139         if (!(p = lock_user_string(arg1)))
7140             goto efault;
7141         ret = get_errno(swapoff(p));
7142         unlock_user(p, arg1, 0);
7143         break;
7144 #endif
7145     case TARGET_NR_sysinfo:
7146         {
7147             struct target_sysinfo *target_value;
7148             struct sysinfo value;
7149             ret = get_errno(sysinfo(&value));
7150             if (!is_error(ret) && arg1)
7151             {
7152                 if (!lock_user_struct(VERIFY_WRITE, target_value, arg1, 0))
7153                     goto efault;
7154                 __put_user(value.uptime, &target_value->uptime);
7155                 __put_user(value.loads[0], &target_value->loads[0]);
7156                 __put_user(value.loads[1], &target_value->loads[1]);
7157                 __put_user(value.loads[2], &target_value->loads[2]);
7158                 __put_user(value.totalram, &target_value->totalram);
7159                 __put_user(value.freeram, &target_value->freeram);
7160                 __put_user(value.sharedram, &target_value->sharedram);
7161                 __put_user(value.bufferram, &target_value->bufferram);
7162                 __put_user(value.totalswap, &target_value->totalswap);
7163                 __put_user(value.freeswap, &target_value->freeswap);
7164                 __put_user(value.procs, &target_value->procs);
7165                 __put_user(value.totalhigh, &target_value->totalhigh);
7166                 __put_user(value.freehigh, &target_value->freehigh);
7167                 __put_user(value.mem_unit, &target_value->mem_unit);
7168                 unlock_user_struct(target_value, arg1, 1);
7169             }
7170         }
7171         break;
7172 #ifdef TARGET_NR_ipc
7173     case TARGET_NR_ipc:
7174         ret = do_ipc(arg1, arg2, arg3, arg4, arg5, arg6);
7175         break;
7176 #endif
7177 #ifdef TARGET_NR_semget
7178     case TARGET_NR_semget:
7179         ret = get_errno(semget(arg1, arg2, arg3));
7180         break;
7181 #endif
7182 #ifdef TARGET_NR_semop
7183     case TARGET_NR_semop:
7184         ret = do_semop(arg1, arg2, arg3);
7185         break;
7186 #endif
7187 #ifdef TARGET_NR_semctl
7188     case TARGET_NR_semctl:
7189         ret = do_semctl(arg1, arg2, arg3, (union target_semun)(abi_ulong)arg4);
7190         break;
7191 #endif
7192 #ifdef TARGET_NR_msgctl
7193     case TARGET_NR_msgctl:
7194         ret = do_msgctl(arg1, arg2, arg3);
7195         break;
7196 #endif
7197 #ifdef TARGET_NR_msgget
7198     case TARGET_NR_msgget:
7199         ret = get_errno(msgget(arg1, arg2));
7200         break;
7201 #endif
7202 #ifdef TARGET_NR_msgrcv
7203     case TARGET_NR_msgrcv:
7204         ret = do_msgrcv(arg1, arg2, arg3, arg4, arg5);
7205         break;
7206 #endif
7207 #ifdef TARGET_NR_msgsnd
7208     case TARGET_NR_msgsnd:
7209         ret = do_msgsnd(arg1, arg2, arg3, arg4);
7210         break;
7211 #endif
7212 #ifdef TARGET_NR_shmget
7213     case TARGET_NR_shmget:
7214         ret = get_errno(shmget(arg1, arg2, arg3));
7215         break;
7216 #endif
7217 #ifdef TARGET_NR_shmctl
7218     case TARGET_NR_shmctl:
7219         ret = do_shmctl(arg1, arg2, arg3);
7220         break;
7221 #endif
7222 #ifdef TARGET_NR_shmat
7223     case TARGET_NR_shmat:
7224         ret = do_shmat(arg1, arg2, arg3);
7225         break;
7226 #endif
7227 #ifdef TARGET_NR_shmdt
7228     case TARGET_NR_shmdt:
7229         ret = do_shmdt(arg1);
7230         break;
7231 #endif
7232     case TARGET_NR_fsync:
7233         ret = get_errno(fsync(arg1));
7234         break;
7235     case TARGET_NR_clone:
7236         /* Linux manages to have three different orderings for its
7237          * arguments to clone(); the BACKWARDS and BACKWARDS2 defines
7238          * match the kernel's CONFIG_CLONE_* settings.
7239          * Microblaze is further special in that it uses a sixth
7240          * implicit argument to clone for the TLS pointer.
7241          */
7242 #if defined(TARGET_MICROBLAZE)
7243         ret = get_errno(do_fork(cpu_env, arg1, arg2, arg4, arg6, arg5));
7244 #elif defined(TARGET_CLONE_BACKWARDS)
7245         ret = get_errno(do_fork(cpu_env, arg1, arg2, arg3, arg4, arg5));
7246 #elif defined(TARGET_CLONE_BACKWARDS2)
7247         ret = get_errno(do_fork(cpu_env, arg2, arg1, arg3, arg5, arg4));
7248 #else
7249         ret = get_errno(do_fork(cpu_env, arg1, arg2, arg3, arg5, arg4));
7250 #endif
7251         break;
7252 #ifdef __NR_exit_group
7253         /* new thread calls */
7254     case TARGET_NR_exit_group:
7255 #ifdef TARGET_GPROF
7256         _mcleanup();
7257 #endif
7258         gdb_exit(cpu_env, arg1);
7259         ret = get_errno(exit_group(arg1));
7260         break;
7261 #endif
7262     case TARGET_NR_setdomainname:
7263         if (!(p = lock_user_string(arg1)))
7264             goto efault;
7265         ret = get_errno(setdomainname(p, arg2));
7266         unlock_user(p, arg1, 0);
7267         break;
7268     case TARGET_NR_uname:
7269         /* no need to transcode because we use the linux syscall */
7270         {
7271             struct new_utsname * buf;
7272
7273             if (!lock_user_struct(VERIFY_WRITE, buf, arg1, 0))
7274                 goto efault;
7275             ret = get_errno(sys_uname(buf));
7276             if (!is_error(ret)) {
7277                 /* Overrite the native machine name with whatever is being
7278                    emulated. */
7279                 strcpy (buf->machine, cpu_to_uname_machine(cpu_env));
7280                 /* Allow the user to override the reported release.  */
7281                 if (qemu_uname_release && *qemu_uname_release)
7282                   strcpy (buf->release, qemu_uname_release);
7283             }
7284             unlock_user_struct(buf, arg1, 1);
7285         }
7286         break;
7287 #ifdef TARGET_I386
7288     case TARGET_NR_modify_ldt:
7289         ret = do_modify_ldt(cpu_env, arg1, arg2, arg3);
7290         break;
7291 #if !defined(TARGET_X86_64)
7292     case TARGET_NR_vm86old:
7293         goto unimplemented;
7294     case TARGET_NR_vm86:
7295         ret = do_vm86(cpu_env, arg1, arg2);
7296         break;
7297 #endif
7298 #endif
7299     case TARGET_NR_adjtimex:
7300         goto unimplemented;
7301 #ifdef TARGET_NR_create_module
7302     case TARGET_NR_create_module:
7303 #endif
7304     case TARGET_NR_init_module:
7305     case TARGET_NR_delete_module:
7306 #ifdef TARGET_NR_get_kernel_syms
7307     case TARGET_NR_get_kernel_syms:
7308 #endif
7309         goto unimplemented;
7310     case TARGET_NR_quotactl:
7311         goto unimplemented;
7312     case TARGET_NR_getpgid:
7313         ret = get_errno(getpgid(arg1));
7314         break;
7315     case TARGET_NR_fchdir:
7316         ret = get_errno(fchdir(arg1));
7317         break;
7318 #ifdef TARGET_NR_bdflush /* not on x86_64 */
7319     case TARGET_NR_bdflush:
7320         goto unimplemented;
7321 #endif
7322 #ifdef TARGET_NR_sysfs
7323     case TARGET_NR_sysfs:
7324         goto unimplemented;
7325 #endif
7326     case TARGET_NR_personality:
7327         ret = get_errno(personality(arg1));
7328         break;
7329 #ifdef TARGET_NR_afs_syscall
7330     case TARGET_NR_afs_syscall:
7331         goto unimplemented;
7332 #endif
7333 #ifdef TARGET_NR__llseek /* Not on alpha */
7334     case TARGET_NR__llseek:
7335         {
7336             int64_t res;
7337 #if !defined(__NR_llseek)
7338             res = lseek(arg1, ((uint64_t)arg2 << 32) | arg3, arg5);
7339             if (res == -1) {
7340                 ret = get_errno(res);
7341             } else {
7342                 ret = 0;
7343             }
7344 #else
7345             ret = get_errno(_llseek(arg1, arg2, arg3, &res, arg5));
7346 #endif
7347             if ((ret == 0) && put_user_s64(res, arg4)) {
7348                 goto efault;
7349             }
7350         }
7351         break;
7352 #endif
7353     case TARGET_NR_getdents:
7354 #ifdef __NR_getdents
7355 #if TARGET_ABI_BITS == 32 && HOST_LONG_BITS == 64
7356         {
7357             struct target_dirent *target_dirp;
7358             struct linux_dirent *dirp;
7359             abi_long count = arg3;
7360
7361             dirp = malloc(count);
7362             if (!dirp) {
7363                 ret = -TARGET_ENOMEM;
7364                 goto fail;
7365             }
7366
7367             ret = get_errno(sys_getdents(arg1, dirp, count));
7368             if (!is_error(ret)) {
7369                 struct linux_dirent *de;
7370                 struct target_dirent *tde;
7371                 int len = ret;
7372                 int reclen, treclen;
7373                 int count1, tnamelen;
7374
7375                 count1 = 0;
7376                 de = dirp;
7377                 if (!(target_dirp = lock_user(VERIFY_WRITE, arg2, count, 0)))
7378                     goto efault;
7379                 tde = target_dirp;
7380                 while (len > 0) {
7381                     reclen = de->d_reclen;
7382                     tnamelen = reclen - offsetof(struct linux_dirent, d_name);
7383                     assert(tnamelen >= 0);
7384                     treclen = tnamelen + offsetof(struct target_dirent, d_name);
7385                     assert(count1 + treclen <= count);
7386                     tde->d_reclen = tswap16(treclen);
7387                     tde->d_ino = tswapal(de->d_ino);
7388                     tde->d_off = tswapal(de->d_off);
7389                     memcpy(tde->d_name, de->d_name, tnamelen);
7390                     de = (struct linux_dirent *)((char *)de + reclen);
7391                     len -= reclen;
7392                     tde = (struct target_dirent *)((char *)tde + treclen);
7393                     count1 += treclen;
7394                 }
7395                 ret = count1;
7396                 unlock_user(target_dirp, arg2, ret);
7397             }
7398             free(dirp);
7399         }
7400 #else
7401         {
7402             struct linux_dirent *dirp;
7403             abi_long count = arg3;
7404
7405             if (!(dirp = lock_user(VERIFY_WRITE, arg2, count, 0)))
7406                 goto efault;
7407             ret = get_errno(sys_getdents(arg1, dirp, count));
7408             if (!is_error(ret)) {
7409                 struct linux_dirent *de;
7410                 int len = ret;
7411                 int reclen;
7412                 de = dirp;
7413                 while (len > 0) {
7414                     reclen = de->d_reclen;
7415                     if (reclen > len)
7416                         break;
7417                     de->d_reclen = tswap16(reclen);
7418                     tswapls(&de->d_ino);
7419                     tswapls(&de->d_off);
7420                     de = (struct linux_dirent *)((char *)de + reclen);
7421                     len -= reclen;
7422                 }
7423             }
7424             unlock_user(dirp, arg2, ret);
7425         }
7426 #endif
7427 #else
7428         /* Implement getdents in terms of getdents64 */
7429         {
7430             struct linux_dirent64 *dirp;
7431             abi_long count = arg3;
7432
7433             dirp = lock_user(VERIFY_WRITE, arg2, count, 0);
7434             if (!dirp) {
7435                 goto efault;
7436             }
7437             ret = get_errno(sys_getdents64(arg1, dirp, count));
7438             if (!is_error(ret)) {
7439                 /* Convert the dirent64 structs to target dirent.  We do this
7440                  * in-place, since we can guarantee that a target_dirent is no
7441                  * larger than a dirent64; however this means we have to be
7442                  * careful to read everything before writing in the new format.
7443                  */
7444                 struct linux_dirent64 *de;
7445                 struct target_dirent *tde;
7446                 int len = ret;
7447                 int tlen = 0;
7448
7449                 de = dirp;
7450                 tde = (struct target_dirent *)dirp;
7451                 while (len > 0) {
7452                     int namelen, treclen;
7453                     int reclen = de->d_reclen;
7454                     uint64_t ino = de->d_ino;
7455                     int64_t off = de->d_off;
7456                     uint8_t type = de->d_type;
7457
7458                     namelen = strlen(de->d_name);
7459                     treclen = offsetof(struct target_dirent, d_name)
7460                         + namelen + 2;
7461                     treclen = QEMU_ALIGN_UP(treclen, sizeof(abi_long));
7462
7463                     memmove(tde->d_name, de->d_name, namelen + 1);
7464                     tde->d_ino = tswapal(ino);
7465                     tde->d_off = tswapal(off);
7466                     tde->d_reclen = tswap16(treclen);
7467                     /* The target_dirent type is in what was formerly a padding
7468                      * byte at the end of the structure:
7469                      */
7470                     *(((char *)tde) + treclen - 1) = type;
7471
7472                     de = (struct linux_dirent64 *)((char *)de + reclen);
7473                     tde = (struct target_dirent *)((char *)tde + treclen);
7474                     len -= reclen;
7475                     tlen += treclen;
7476                 }
7477                 ret = tlen;
7478             }
7479             unlock_user(dirp, arg2, ret);
7480         }
7481 #endif
7482         break;
7483 #if defined(TARGET_NR_getdents64) && defined(__NR_getdents64)
7484     case TARGET_NR_getdents64:
7485         {
7486             struct linux_dirent64 *dirp;
7487             abi_long count = arg3;
7488             if (!(dirp = lock_user(VERIFY_WRITE, arg2, count, 0)))
7489                 goto efault;
7490             ret = get_errno(sys_getdents64(arg1, dirp, count));
7491             if (!is_error(ret)) {
7492                 struct linux_dirent64 *de;
7493                 int len = ret;
7494                 int reclen;
7495                 de = dirp;
7496                 while (len > 0) {
7497                     reclen = de->d_reclen;
7498                     if (reclen > len)
7499                         break;
7500                     de->d_reclen = tswap16(reclen);
7501                     tswap64s((uint64_t *)&de->d_ino);
7502                     tswap64s((uint64_t *)&de->d_off);
7503                     de = (struct linux_dirent64 *)((char *)de + reclen);
7504                     len -= reclen;
7505                 }
7506             }
7507             unlock_user(dirp, arg2, ret);
7508         }
7509         break;
7510 #endif /* TARGET_NR_getdents64 */
7511 #if defined(TARGET_NR__newselect)
7512     case TARGET_NR__newselect:
7513         ret = do_select(arg1, arg2, arg3, arg4, arg5);
7514         break;
7515 #endif
7516 #if defined(TARGET_NR_poll) || defined(TARGET_NR_ppoll)
7517 # ifdef TARGET_NR_poll
7518     case TARGET_NR_poll:
7519 # endif
7520 # ifdef TARGET_NR_ppoll
7521     case TARGET_NR_ppoll:
7522 # endif
7523         {
7524             struct target_pollfd *target_pfd;
7525             unsigned int nfds = arg2;
7526             int timeout = arg3;
7527             struct pollfd *pfd;
7528             unsigned int i;
7529
7530             target_pfd = lock_user(VERIFY_WRITE, arg1, sizeof(struct target_pollfd) * nfds, 1);
7531             if (!target_pfd)
7532                 goto efault;
7533
7534             pfd = alloca(sizeof(struct pollfd) * nfds);
7535             for(i = 0; i < nfds; i++) {
7536                 pfd[i].fd = tswap32(target_pfd[i].fd);
7537                 pfd[i].events = tswap16(target_pfd[i].events);
7538             }
7539
7540 # ifdef TARGET_NR_ppoll
7541             if (num == TARGET_NR_ppoll) {
7542                 struct timespec _timeout_ts, *timeout_ts = &_timeout_ts;
7543                 target_sigset_t *target_set;
7544                 sigset_t _set, *set = &_set;
7545
7546                 if (arg3) {
7547                     if (target_to_host_timespec(timeout_ts, arg3)) {
7548                         unlock_user(target_pfd, arg1, 0);
7549                         goto efault;
7550                     }
7551                 } else {
7552                     timeout_ts = NULL;
7553                 }
7554
7555                 if (arg4) {
7556                     target_set = lock_user(VERIFY_READ, arg4, sizeof(target_sigset_t), 1);
7557                     if (!target_set) {
7558                         unlock_user(target_pfd, arg1, 0);
7559                         goto efault;
7560                     }
7561                     target_to_host_sigset(set, target_set);
7562                 } else {
7563                     set = NULL;
7564                 }
7565
7566                 ret = get_errno(sys_ppoll(pfd, nfds, timeout_ts, set, _NSIG/8));
7567
7568                 if (!is_error(ret) && arg3) {
7569                     host_to_target_timespec(arg3, timeout_ts);
7570                 }
7571                 if (arg4) {
7572                     unlock_user(target_set, arg4, 0);
7573                 }
7574             } else
7575 # endif
7576                 ret = get_errno(poll(pfd, nfds, timeout));
7577
7578             if (!is_error(ret)) {
7579                 for(i = 0; i < nfds; i++) {
7580                     target_pfd[i].revents = tswap16(pfd[i].revents);
7581                 }
7582             }
7583             unlock_user(target_pfd, arg1, sizeof(struct target_pollfd) * nfds);
7584         }
7585         break;
7586 #endif
7587     case TARGET_NR_flock:
7588         /* NOTE: the flock constant seems to be the same for every
7589            Linux platform */
7590         ret = get_errno(flock(arg1, arg2));
7591         break;
7592     case TARGET_NR_readv:
7593         {
7594             struct iovec *vec = lock_iovec(VERIFY_WRITE, arg2, arg3, 0);
7595             if (vec != NULL) {
7596                 ret = get_errno(readv(arg1, vec, arg3));
7597                 unlock_iovec(vec, arg2, arg3, 1);
7598             } else {
7599                 ret = -host_to_target_errno(errno);
7600             }
7601         }
7602         break;
7603     case TARGET_NR_writev:
7604         {
7605             struct iovec *vec = lock_iovec(VERIFY_READ, arg2, arg3, 1);
7606             if (vec != NULL) {
7607                 ret = get_errno(writev(arg1, vec, arg3));
7608                 unlock_iovec(vec, arg2, arg3, 0);
7609             } else {
7610                 ret = -host_to_target_errno(errno);
7611             }
7612         }
7613         break;
7614     case TARGET_NR_getsid:
7615         ret = get_errno(getsid(arg1));
7616         break;
7617 #if defined(TARGET_NR_fdatasync) /* Not on alpha (osf_datasync ?) */
7618     case TARGET_NR_fdatasync:
7619         ret = get_errno(fdatasync(arg1));
7620         break;
7621 #endif
7622     case TARGET_NR__sysctl:
7623         /* We don't implement this, but ENOTDIR is always a safe
7624            return value. */
7625         ret = -TARGET_ENOTDIR;
7626         break;
7627     case TARGET_NR_sched_getaffinity:
7628         {
7629             unsigned int mask_size;
7630             unsigned long *mask;
7631
7632             /*
7633              * sched_getaffinity needs multiples of ulong, so need to take
7634              * care of mismatches between target ulong and host ulong sizes.
7635              */
7636             if (arg2 & (sizeof(abi_ulong) - 1)) {
7637                 ret = -TARGET_EINVAL;
7638                 break;
7639             }
7640             mask_size = (arg2 + (sizeof(*mask) - 1)) & ~(sizeof(*mask) - 1);
7641
7642             mask = alloca(mask_size);
7643             ret = get_errno(sys_sched_getaffinity(arg1, mask_size, mask));
7644
7645             if (!is_error(ret)) {
7646                 if (ret > arg2) {
7647                     /* More data returned than the caller's buffer will fit.
7648                      * This only happens if sizeof(abi_long) < sizeof(long)
7649                      * and the caller passed us a buffer holding an odd number
7650                      * of abi_longs. If the host kernel is actually using the
7651                      * extra 4 bytes then fail EINVAL; otherwise we can just
7652                      * ignore them and only copy the interesting part.
7653                      */
7654                     int numcpus = sysconf(_SC_NPROCESSORS_CONF);
7655                     if (numcpus > arg2 * 8) {
7656                         ret = -TARGET_EINVAL;
7657                         break;
7658                     }
7659                     ret = arg2;
7660                 }
7661
7662                 if (copy_to_user(arg3, mask, ret)) {
7663                     goto efault;
7664                 }
7665             }
7666         }
7667         break;
7668     case TARGET_NR_sched_setaffinity:
7669         {
7670             unsigned int mask_size;
7671             unsigned long *mask;
7672
7673             /*
7674              * sched_setaffinity needs multiples of ulong, so need to take
7675              * care of mismatches between target ulong and host ulong sizes.
7676              */
7677             if (arg2 & (sizeof(abi_ulong) - 1)) {
7678                 ret = -TARGET_EINVAL;
7679                 break;
7680             }
7681             mask_size = (arg2 + (sizeof(*mask) - 1)) & ~(sizeof(*mask) - 1);
7682
7683             mask = alloca(mask_size);
7684             if (!lock_user_struct(VERIFY_READ, p, arg3, 1)) {
7685                 goto efault;
7686             }
7687             memcpy(mask, p, arg2);
7688             unlock_user_struct(p, arg2, 0);
7689
7690             ret = get_errno(sys_sched_setaffinity(arg1, mask_size, mask));
7691         }
7692         break;
7693     case TARGET_NR_sched_setparam:
7694         {
7695             struct sched_param *target_schp;
7696             struct sched_param schp;
7697
7698             if (!lock_user_struct(VERIFY_READ, target_schp, arg2, 1))
7699                 goto efault;
7700             schp.sched_priority = tswap32(target_schp->sched_priority);
7701             unlock_user_struct(target_schp, arg2, 0);
7702             ret = get_errno(sched_setparam(arg1, &schp));
7703         }
7704         break;
7705     case TARGET_NR_sched_getparam:
7706         {
7707             struct sched_param *target_schp;
7708             struct sched_param schp;
7709             ret = get_errno(sched_getparam(arg1, &schp));
7710             if (!is_error(ret)) {
7711                 if (!lock_user_struct(VERIFY_WRITE, target_schp, arg2, 0))
7712                     goto efault;
7713                 target_schp->sched_priority = tswap32(schp.sched_priority);
7714                 unlock_user_struct(target_schp, arg2, 1);
7715             }
7716         }
7717         break;
7718     case TARGET_NR_sched_setscheduler:
7719         {
7720             struct sched_param *target_schp;
7721             struct sched_param schp;
7722             if (!lock_user_struct(VERIFY_READ, target_schp, arg3, 1))
7723                 goto efault;
7724             schp.sched_priority = tswap32(target_schp->sched_priority);
7725             unlock_user_struct(target_schp, arg3, 0);
7726             ret = get_errno(sched_setscheduler(arg1, arg2, &schp));
7727         }
7728         break;
7729     case TARGET_NR_sched_getscheduler:
7730         ret = get_errno(sched_getscheduler(arg1));
7731         break;
7732     case TARGET_NR_sched_yield:
7733         ret = get_errno(sched_yield());
7734         break;
7735     case TARGET_NR_sched_get_priority_max:
7736         ret = get_errno(sched_get_priority_max(arg1));
7737         break;
7738     case TARGET_NR_sched_get_priority_min:
7739         ret = get_errno(sched_get_priority_min(arg1));
7740         break;
7741     case TARGET_NR_sched_rr_get_interval:
7742         {
7743             struct timespec ts;
7744             ret = get_errno(sched_rr_get_interval(arg1, &ts));
7745             if (!is_error(ret)) {
7746                 host_to_target_timespec(arg2, &ts);
7747             }
7748         }
7749         break;
7750     case TARGET_NR_nanosleep:
7751         {
7752             struct timespec req, rem;
7753             target_to_host_timespec(&req, arg1);
7754             ret = get_errno(nanosleep(&req, &rem));
7755             if (is_error(ret) && arg2) {
7756                 host_to_target_timespec(arg2, &rem);
7757             }
7758         }
7759         break;
7760 #ifdef TARGET_NR_query_module
7761     case TARGET_NR_query_module:
7762         goto unimplemented;
7763 #endif
7764 #ifdef TARGET_NR_nfsservctl
7765     case TARGET_NR_nfsservctl:
7766         goto unimplemented;
7767 #endif
7768     case TARGET_NR_prctl:
7769         switch (arg1) {
7770         case PR_GET_PDEATHSIG:
7771         {
7772             int deathsig;
7773             ret = get_errno(prctl(arg1, &deathsig, arg3, arg4, arg5));
7774             if (!is_error(ret) && arg2
7775                 && put_user_ual(deathsig, arg2)) {
7776                 goto efault;
7777             }
7778             break;
7779         }
7780 #ifdef PR_GET_NAME
7781         case PR_GET_NAME:
7782         {
7783             void *name = lock_user(VERIFY_WRITE, arg2, 16, 1);
7784             if (!name) {
7785                 goto efault;
7786             }
7787             ret = get_errno(prctl(arg1, (unsigned long)name,
7788                                   arg3, arg4, arg5));
7789             unlock_user(name, arg2, 16);
7790             break;
7791         }
7792         case PR_SET_NAME:
7793         {
7794             void *name = lock_user(VERIFY_READ, arg2, 16, 1);
7795             if (!name) {
7796                 goto efault;
7797             }
7798             ret = get_errno(prctl(arg1, (unsigned long)name,
7799                                   arg3, arg4, arg5));
7800             unlock_user(name, arg2, 0);
7801             break;
7802         }
7803 #endif
7804         default:
7805             /* Most prctl options have no pointer arguments */
7806             ret = get_errno(prctl(arg1, arg2, arg3, arg4, arg5));
7807             break;
7808         }
7809         break;
7810 #ifdef TARGET_NR_arch_prctl
7811     case TARGET_NR_arch_prctl:
7812 #if defined(TARGET_I386) && !defined(TARGET_ABI32)
7813         ret = do_arch_prctl(cpu_env, arg1, arg2);
7814         break;
7815 #else
7816         goto unimplemented;
7817 #endif
7818 #endif
7819 #ifdef TARGET_NR_pread64
7820     case TARGET_NR_pread64:
7821         if (regpairs_aligned(cpu_env)) {
7822             arg4 = arg5;
7823             arg5 = arg6;
7824         }
7825         if (!(p = lock_user(VERIFY_WRITE, arg2, arg3, 0)))
7826             goto efault;
7827         ret = get_errno(pread64(arg1, p, arg3, target_offset64(arg4, arg5)));
7828         unlock_user(p, arg2, ret);
7829         break;
7830     case TARGET_NR_pwrite64:
7831         if (regpairs_aligned(cpu_env)) {
7832             arg4 = arg5;
7833             arg5 = arg6;
7834         }
7835         if (!(p = lock_user(VERIFY_READ, arg2, arg3, 1)))
7836             goto efault;
7837         ret = get_errno(pwrite64(arg1, p, arg3, target_offset64(arg4, arg5)));
7838         unlock_user(p, arg2, 0);
7839         break;
7840 #endif
7841     case TARGET_NR_getcwd:
7842         if (!(p = lock_user(VERIFY_WRITE, arg1, arg2, 0)))
7843             goto efault;
7844         ret = get_errno(sys_getcwd1(p, arg2));
7845         unlock_user(p, arg1, ret);
7846         break;
7847     case TARGET_NR_capget:
7848     case TARGET_NR_capset:
7849     {
7850         struct target_user_cap_header *target_header;
7851         struct target_user_cap_data *target_data = NULL;
7852         struct __user_cap_header_struct header;
7853         struct __user_cap_data_struct data[2];
7854         struct __user_cap_data_struct *dataptr = NULL;
7855         int i, target_datalen;
7856         int data_items = 1;
7857
7858         if (!lock_user_struct(VERIFY_WRITE, target_header, arg1, 1)) {
7859             goto efault;
7860         }
7861         header.version = tswap32(target_header->version);
7862         header.pid = tswap32(target_header->pid);
7863
7864         if (header.version != _LINUX_CAPABILITY_VERSION) {
7865             /* Version 2 and up takes pointer to two user_data structs */
7866             data_items = 2;
7867         }
7868
7869         target_datalen = sizeof(*target_data) * data_items;
7870
7871         if (arg2) {
7872             if (num == TARGET_NR_capget) {
7873                 target_data = lock_user(VERIFY_WRITE, arg2, target_datalen, 0);
7874             } else {
7875                 target_data = lock_user(VERIFY_READ, arg2, target_datalen, 1);
7876             }
7877             if (!target_data) {
7878                 unlock_user_struct(target_header, arg1, 0);
7879                 goto efault;
7880             }
7881
7882             if (num == TARGET_NR_capset) {
7883                 for (i = 0; i < data_items; i++) {
7884                     data[i].effective = tswap32(target_data[i].effective);
7885                     data[i].permitted = tswap32(target_data[i].permitted);
7886                     data[i].inheritable = tswap32(target_data[i].inheritable);
7887                 }
7888             }
7889
7890             dataptr = data;
7891         }
7892
7893         if (num == TARGET_NR_capget) {
7894             ret = get_errno(capget(&header, dataptr));
7895         } else {
7896             ret = get_errno(capset(&header, dataptr));
7897         }
7898
7899         /* The kernel always updates version for both capget and capset */
7900         target_header->version = tswap32(header.version);
7901         unlock_user_struct(target_header, arg1, 1);
7902
7903         if (arg2) {
7904             if (num == TARGET_NR_capget) {
7905                 for (i = 0; i < data_items; i++) {
7906                     target_data[i].effective = tswap32(data[i].effective);
7907                     target_data[i].permitted = tswap32(data[i].permitted);
7908                     target_data[i].inheritable = tswap32(data[i].inheritable);
7909                 }
7910                 unlock_user(target_data, arg2, target_datalen);
7911             } else {
7912                 unlock_user(target_data, arg2, 0);
7913             }
7914         }
7915         break;
7916     }
7917     case TARGET_NR_sigaltstack:
7918 #if defined(TARGET_I386) || defined(TARGET_ARM) || defined(TARGET_MIPS) || \
7919     defined(TARGET_SPARC) || defined(TARGET_PPC) || defined(TARGET_ALPHA) || \
7920     defined(TARGET_M68K) || defined(TARGET_S390X) || defined(TARGET_OPENRISC)
7921         ret = do_sigaltstack(arg1, arg2, get_sp_from_cpustate((CPUArchState *)cpu_env));
7922         break;
7923 #else
7924         goto unimplemented;
7925 #endif
7926
7927 #ifdef CONFIG_SENDFILE
7928     case TARGET_NR_sendfile:
7929     {
7930         off_t *offp = NULL;
7931         off_t off;
7932         if (arg3) {
7933             ret = get_user_sal(off, arg3);
7934             if (is_error(ret)) {
7935                 break;
7936             }
7937             offp = &off;
7938         }
7939         ret = get_errno(sendfile(arg1, arg2, offp, arg4));
7940         if (!is_error(ret) && arg3) {
7941             abi_long ret2 = put_user_sal(off, arg3);
7942             if (is_error(ret2)) {
7943                 ret = ret2;
7944             }
7945         }
7946         break;
7947     }
7948 #ifdef TARGET_NR_sendfile64
7949     case TARGET_NR_sendfile64:
7950     {
7951         off_t *offp = NULL;
7952         off_t off;
7953         if (arg3) {
7954             ret = get_user_s64(off, arg3);
7955             if (is_error(ret)) {
7956                 break;
7957             }
7958             offp = &off;
7959         }
7960         ret = get_errno(sendfile(arg1, arg2, offp, arg4));
7961         if (!is_error(ret) && arg3) {
7962             abi_long ret2 = put_user_s64(off, arg3);
7963             if (is_error(ret2)) {
7964                 ret = ret2;
7965             }
7966         }
7967         break;
7968     }
7969 #endif
7970 #else
7971     case TARGET_NR_sendfile:
7972 #ifdef TARGET_NR_sendfile64
7973     case TARGET_NR_sendfile64:
7974 #endif
7975         goto unimplemented;
7976 #endif
7977
7978 #ifdef TARGET_NR_getpmsg
7979     case TARGET_NR_getpmsg:
7980         goto unimplemented;
7981 #endif
7982 #ifdef TARGET_NR_putpmsg
7983     case TARGET_NR_putpmsg:
7984         goto unimplemented;
7985 #endif
7986 #ifdef TARGET_NR_vfork
7987     case TARGET_NR_vfork:
7988         ret = get_errno(do_fork(cpu_env, CLONE_VFORK | CLONE_VM | SIGCHLD,
7989                         0, 0, 0, 0));
7990         break;
7991 #endif
7992 #ifdef TARGET_NR_ugetrlimit
7993     case TARGET_NR_ugetrlimit:
7994     {
7995         struct rlimit rlim;
7996         int resource = target_to_host_resource(arg1);
7997         ret = get_errno(getrlimit(resource, &rlim));
7998         if (!is_error(ret)) {
7999             struct target_rlimit *target_rlim;
8000             if (!lock_user_struct(VERIFY_WRITE, target_rlim, arg2, 0))
8001                 goto efault;
8002             target_rlim->rlim_cur = host_to_target_rlim(rlim.rlim_cur);
8003             target_rlim->rlim_max = host_to_target_rlim(rlim.rlim_max);
8004             unlock_user_struct(target_rlim, arg2, 1);
8005         }
8006         break;
8007     }
8008 #endif
8009 #ifdef TARGET_NR_truncate64
8010     case TARGET_NR_truncate64:
8011         if (!(p = lock_user_string(arg1)))
8012             goto efault;
8013         ret = target_truncate64(cpu_env, p, arg2, arg3, arg4);
8014         unlock_user(p, arg1, 0);
8015         break;
8016 #endif
8017 #ifdef TARGET_NR_ftruncate64
8018     case TARGET_NR_ftruncate64:
8019         ret = target_ftruncate64(cpu_env, arg1, arg2, arg3, arg4);
8020         break;
8021 #endif
8022 #ifdef TARGET_NR_stat64
8023     case TARGET_NR_stat64:
8024         if (!(p = lock_user_string(arg1)))
8025             goto efault;
8026         ret = get_errno(stat(path(p), &st));
8027         unlock_user(p, arg1, 0);
8028         if (!is_error(ret))
8029             ret = host_to_target_stat64(cpu_env, arg2, &st);
8030         break;
8031 #endif
8032 #ifdef TARGET_NR_lstat64
8033     case TARGET_NR_lstat64:
8034         if (!(p = lock_user_string(arg1)))
8035             goto efault;
8036         ret = get_errno(lstat(path(p), &st));
8037         unlock_user(p, arg1, 0);
8038         if (!is_error(ret))
8039             ret = host_to_target_stat64(cpu_env, arg2, &st);
8040         break;
8041 #endif
8042 #ifdef TARGET_NR_fstat64
8043     case TARGET_NR_fstat64:
8044         ret = get_errno(fstat(arg1, &st));
8045         if (!is_error(ret))
8046             ret = host_to_target_stat64(cpu_env, arg2, &st);
8047         break;
8048 #endif
8049 #if (defined(TARGET_NR_fstatat64) || defined(TARGET_NR_newfstatat))
8050 #ifdef TARGET_NR_fstatat64
8051     case TARGET_NR_fstatat64:
8052 #endif
8053 #ifdef TARGET_NR_newfstatat
8054     case TARGET_NR_newfstatat:
8055 #endif
8056         if (!(p = lock_user_string(arg2)))
8057             goto efault;
8058         ret = get_errno(fstatat(arg1, path(p), &st, arg4));
8059         if (!is_error(ret))
8060             ret = host_to_target_stat64(cpu_env, arg3, &st);
8061         break;
8062 #endif
8063     case TARGET_NR_lchown:
8064         if (!(p = lock_user_string(arg1)))
8065             goto efault;
8066         ret = get_errno(lchown(p, low2highuid(arg2), low2highgid(arg3)));
8067         unlock_user(p, arg1, 0);
8068         break;
8069 #ifdef TARGET_NR_getuid
8070     case TARGET_NR_getuid:
8071         ret = get_errno(high2lowuid(getuid()));
8072         break;
8073 #endif
8074 #ifdef TARGET_NR_getgid
8075     case TARGET_NR_getgid:
8076         ret = get_errno(high2lowgid(getgid()));
8077         break;
8078 #endif
8079 #ifdef TARGET_NR_geteuid
8080     case TARGET_NR_geteuid:
8081         ret = get_errno(high2lowuid(geteuid()));
8082         break;
8083 #endif
8084 #ifdef TARGET_NR_getegid
8085     case TARGET_NR_getegid:
8086         ret = get_errno(high2lowgid(getegid()));
8087         break;
8088 #endif
8089     case TARGET_NR_setreuid:
8090         ret = get_errno(setreuid(low2highuid(arg1), low2highuid(arg2)));
8091         break;
8092     case TARGET_NR_setregid:
8093         ret = get_errno(setregid(low2highgid(arg1), low2highgid(arg2)));
8094         break;
8095     case TARGET_NR_getgroups:
8096         {
8097             int gidsetsize = arg1;
8098             target_id *target_grouplist;
8099             gid_t *grouplist;
8100             int i;
8101
8102             grouplist = alloca(gidsetsize * sizeof(gid_t));
8103             ret = get_errno(getgroups(gidsetsize, grouplist));
8104             if (gidsetsize == 0)
8105                 break;
8106             if (!is_error(ret)) {
8107                 target_grouplist = lock_user(VERIFY_WRITE, arg2, gidsetsize * sizeof(target_id), 0);
8108                 if (!target_grouplist)
8109                     goto efault;
8110                 for(i = 0;i < ret; i++)
8111                     target_grouplist[i] = tswapid(high2lowgid(grouplist[i]));
8112                 unlock_user(target_grouplist, arg2, gidsetsize * sizeof(target_id));
8113             }
8114         }
8115         break;
8116     case TARGET_NR_setgroups:
8117         {
8118             int gidsetsize = arg1;
8119             target_id *target_grouplist;
8120             gid_t *grouplist = NULL;
8121             int i;
8122             if (gidsetsize) {
8123                 grouplist = alloca(gidsetsize * sizeof(gid_t));
8124                 target_grouplist = lock_user(VERIFY_READ, arg2, gidsetsize * sizeof(target_id), 1);
8125                 if (!target_grouplist) {
8126                     ret = -TARGET_EFAULT;
8127                     goto fail;
8128                 }
8129                 for (i = 0; i < gidsetsize; i++) {
8130                     grouplist[i] = low2highgid(tswapid(target_grouplist[i]));
8131                 }
8132                 unlock_user(target_grouplist, arg2, 0);
8133             }
8134             ret = get_errno(setgroups(gidsetsize, grouplist));
8135         }
8136         break;
8137     case TARGET_NR_fchown:
8138         ret = get_errno(fchown(arg1, low2highuid(arg2), low2highgid(arg3)));
8139         break;
8140 #if defined(TARGET_NR_fchownat)
8141     case TARGET_NR_fchownat:
8142         if (!(p = lock_user_string(arg2))) 
8143             goto efault;
8144         ret = get_errno(fchownat(arg1, p, low2highuid(arg3),
8145                                  low2highgid(arg4), arg5));
8146         unlock_user(p, arg2, 0);
8147         break;
8148 #endif
8149 #ifdef TARGET_NR_setresuid
8150     case TARGET_NR_setresuid:
8151         ret = get_errno(setresuid(low2highuid(arg1),
8152                                   low2highuid(arg2),
8153                                   low2highuid(arg3)));
8154         break;
8155 #endif
8156 #ifdef TARGET_NR_getresuid
8157     case TARGET_NR_getresuid:
8158         {
8159             uid_t ruid, euid, suid;
8160             ret = get_errno(getresuid(&ruid, &euid, &suid));
8161             if (!is_error(ret)) {
8162                 if (put_user_id(high2lowuid(ruid), arg1)
8163                     || put_user_id(high2lowuid(euid), arg2)
8164                     || put_user_id(high2lowuid(suid), arg3))
8165                     goto efault;
8166             }
8167         }
8168         break;
8169 #endif
8170 #ifdef TARGET_NR_getresgid
8171     case TARGET_NR_setresgid:
8172         ret = get_errno(setresgid(low2highgid(arg1),
8173                                   low2highgid(arg2),
8174                                   low2highgid(arg3)));
8175         break;
8176 #endif
8177 #ifdef TARGET_NR_getresgid
8178     case TARGET_NR_getresgid:
8179         {
8180             gid_t rgid, egid, sgid;
8181             ret = get_errno(getresgid(&rgid, &egid, &sgid));
8182             if (!is_error(ret)) {
8183                 if (put_user_id(high2lowgid(rgid), arg1)
8184                     || put_user_id(high2lowgid(egid), arg2)
8185                     || put_user_id(high2lowgid(sgid), arg3))
8186                     goto efault;
8187             }
8188         }
8189         break;
8190 #endif
8191     case TARGET_NR_chown:
8192         if (!(p = lock_user_string(arg1)))
8193             goto efault;
8194         ret = get_errno(chown(p, low2highuid(arg2), low2highgid(arg3)));
8195         unlock_user(p, arg1, 0);
8196         break;
8197     case TARGET_NR_setuid:
8198         ret = get_errno(setuid(low2highuid(arg1)));
8199         break;
8200     case TARGET_NR_setgid:
8201         ret = get_errno(setgid(low2highgid(arg1)));
8202         break;
8203     case TARGET_NR_setfsuid:
8204         ret = get_errno(setfsuid(arg1));
8205         break;
8206     case TARGET_NR_setfsgid:
8207         ret = get_errno(setfsgid(arg1));
8208         break;
8209
8210 #ifdef TARGET_NR_lchown32
8211     case TARGET_NR_lchown32:
8212         if (!(p = lock_user_string(arg1)))
8213             goto efault;
8214         ret = get_errno(lchown(p, arg2, arg3));
8215         unlock_user(p, arg1, 0);
8216         break;
8217 #endif
8218 #ifdef TARGET_NR_getuid32
8219     case TARGET_NR_getuid32:
8220         ret = get_errno(getuid());
8221         break;
8222 #endif
8223
8224 #if defined(TARGET_NR_getxuid) && defined(TARGET_ALPHA)
8225    /* Alpha specific */
8226     case TARGET_NR_getxuid:
8227          {
8228             uid_t euid;
8229             euid=geteuid();
8230             ((CPUAlphaState *)cpu_env)->ir[IR_A4]=euid;
8231          }
8232         ret = get_errno(getuid());
8233         break;
8234 #endif
8235 #if defined(TARGET_NR_getxgid) && defined(TARGET_ALPHA)
8236    /* Alpha specific */
8237     case TARGET_NR_getxgid:
8238          {
8239             uid_t egid;
8240             egid=getegid();
8241             ((CPUAlphaState *)cpu_env)->ir[IR_A4]=egid;
8242          }
8243         ret = get_errno(getgid());
8244         break;
8245 #endif
8246 #if defined(TARGET_NR_osf_getsysinfo) && defined(TARGET_ALPHA)
8247     /* Alpha specific */
8248     case TARGET_NR_osf_getsysinfo:
8249         ret = -TARGET_EOPNOTSUPP;
8250         switch (arg1) {
8251           case TARGET_GSI_IEEE_FP_CONTROL:
8252             {
8253                 uint64_t swcr, fpcr = cpu_alpha_load_fpcr (cpu_env);
8254
8255                 /* Copied from linux ieee_fpcr_to_swcr.  */
8256                 swcr = (fpcr >> 35) & SWCR_STATUS_MASK;
8257                 swcr |= (fpcr >> 36) & SWCR_MAP_DMZ;
8258                 swcr |= (~fpcr >> 48) & (SWCR_TRAP_ENABLE_INV
8259                                         | SWCR_TRAP_ENABLE_DZE
8260                                         | SWCR_TRAP_ENABLE_OVF);
8261                 swcr |= (~fpcr >> 57) & (SWCR_TRAP_ENABLE_UNF
8262                                         | SWCR_TRAP_ENABLE_INE);
8263                 swcr |= (fpcr >> 47) & SWCR_MAP_UMZ;
8264                 swcr |= (~fpcr >> 41) & SWCR_TRAP_ENABLE_DNO;
8265
8266                 if (put_user_u64 (swcr, arg2))
8267                         goto efault;
8268                 ret = 0;
8269             }
8270             break;
8271
8272           /* case GSI_IEEE_STATE_AT_SIGNAL:
8273              -- Not implemented in linux kernel.
8274              case GSI_UACPROC:
8275              -- Retrieves current unaligned access state; not much used.
8276              case GSI_PROC_TYPE:
8277              -- Retrieves implver information; surely not used.
8278              case GSI_GET_HWRPB:
8279              -- Grabs a copy of the HWRPB; surely not used.
8280           */
8281         }
8282         break;
8283 #endif
8284 #if defined(TARGET_NR_osf_setsysinfo) && defined(TARGET_ALPHA)
8285     /* Alpha specific */
8286     case TARGET_NR_osf_setsysinfo:
8287         ret = -TARGET_EOPNOTSUPP;
8288         switch (arg1) {
8289           case TARGET_SSI_IEEE_FP_CONTROL:
8290             {
8291                 uint64_t swcr, fpcr, orig_fpcr;
8292
8293                 if (get_user_u64 (swcr, arg2)) {
8294                     goto efault;
8295                 }
8296                 orig_fpcr = cpu_alpha_load_fpcr(cpu_env);
8297                 fpcr = orig_fpcr & FPCR_DYN_MASK;
8298
8299                 /* Copied from linux ieee_swcr_to_fpcr.  */
8300                 fpcr |= (swcr & SWCR_STATUS_MASK) << 35;
8301                 fpcr |= (swcr & SWCR_MAP_DMZ) << 36;
8302                 fpcr |= (~swcr & (SWCR_TRAP_ENABLE_INV
8303                                   | SWCR_TRAP_ENABLE_DZE
8304                                   | SWCR_TRAP_ENABLE_OVF)) << 48;
8305                 fpcr |= (~swcr & (SWCR_TRAP_ENABLE_UNF
8306                                   | SWCR_TRAP_ENABLE_INE)) << 57;
8307                 fpcr |= (swcr & SWCR_MAP_UMZ ? FPCR_UNDZ | FPCR_UNFD : 0);
8308                 fpcr |= (~swcr & SWCR_TRAP_ENABLE_DNO) << 41;
8309
8310                 cpu_alpha_store_fpcr(cpu_env, fpcr);
8311                 ret = 0;
8312             }
8313             break;
8314
8315           case TARGET_SSI_IEEE_RAISE_EXCEPTION:
8316             {
8317                 uint64_t exc, fpcr, orig_fpcr;
8318                 int si_code;
8319
8320                 if (get_user_u64(exc, arg2)) {
8321                     goto efault;
8322                 }
8323
8324                 orig_fpcr = cpu_alpha_load_fpcr(cpu_env);
8325
8326                 /* We only add to the exception status here.  */
8327                 fpcr = orig_fpcr | ((exc & SWCR_STATUS_MASK) << 35);
8328
8329                 cpu_alpha_store_fpcr(cpu_env, fpcr);
8330                 ret = 0;
8331
8332                 /* Old exceptions are not signaled.  */
8333                 fpcr &= ~(orig_fpcr & FPCR_STATUS_MASK);
8334
8335                 /* If any exceptions set by this call,
8336                    and are unmasked, send a signal.  */
8337                 si_code = 0;
8338                 if ((fpcr & (FPCR_INE | FPCR_INED)) == FPCR_INE) {
8339                     si_code = TARGET_FPE_FLTRES;
8340                 }
8341                 if ((fpcr & (FPCR_UNF | FPCR_UNFD)) == FPCR_UNF) {
8342                     si_code = TARGET_FPE_FLTUND;
8343                 }
8344                 if ((fpcr & (FPCR_OVF | FPCR_OVFD)) == FPCR_OVF) {
8345                     si_code = TARGET_FPE_FLTOVF;
8346                 }
8347                 if ((fpcr & (FPCR_DZE | FPCR_DZED)) == FPCR_DZE) {
8348                     si_code = TARGET_FPE_FLTDIV;
8349                 }
8350                 if ((fpcr & (FPCR_INV | FPCR_INVD)) == FPCR_INV) {
8351                     si_code = TARGET_FPE_FLTINV;
8352                 }
8353                 if (si_code != 0) {
8354                     target_siginfo_t info;
8355                     info.si_signo = SIGFPE;
8356                     info.si_errno = 0;
8357                     info.si_code = si_code;
8358                     info._sifields._sigfault._addr
8359                         = ((CPUArchState *)cpu_env)->pc;
8360                     queue_signal((CPUArchState *)cpu_env, info.si_signo, &info);
8361                 }
8362             }
8363             break;
8364
8365           /* case SSI_NVPAIRS:
8366              -- Used with SSIN_UACPROC to enable unaligned accesses.
8367              case SSI_IEEE_STATE_AT_SIGNAL:
8368              case SSI_IEEE_IGNORE_STATE_AT_SIGNAL:
8369              -- Not implemented in linux kernel
8370           */
8371         }
8372         break;
8373 #endif
8374 #ifdef TARGET_NR_osf_sigprocmask
8375     /* Alpha specific.  */
8376     case TARGET_NR_osf_sigprocmask:
8377         {
8378             abi_ulong mask;
8379             int how;
8380             sigset_t set, oldset;
8381
8382             switch(arg1) {
8383             case TARGET_SIG_BLOCK:
8384                 how = SIG_BLOCK;
8385                 break;
8386             case TARGET_SIG_UNBLOCK:
8387                 how = SIG_UNBLOCK;
8388                 break;
8389             case TARGET_SIG_SETMASK:
8390                 how = SIG_SETMASK;
8391                 break;
8392             default:
8393                 ret = -TARGET_EINVAL;
8394                 goto fail;
8395             }
8396             mask = arg2;
8397             target_to_host_old_sigset(&set, &mask);
8398             do_sigprocmask(how, &set, &oldset);
8399             host_to_target_old_sigset(&mask, &oldset);
8400             ret = mask;
8401         }
8402         break;
8403 #endif
8404
8405 #ifdef TARGET_NR_getgid32
8406     case TARGET_NR_getgid32:
8407         ret = get_errno(getgid());
8408         break;
8409 #endif
8410 #ifdef TARGET_NR_geteuid32
8411     case TARGET_NR_geteuid32:
8412         ret = get_errno(geteuid());
8413         break;
8414 #endif
8415 #ifdef TARGET_NR_getegid32
8416     case TARGET_NR_getegid32:
8417         ret = get_errno(getegid());
8418         break;
8419 #endif
8420 #ifdef TARGET_NR_setreuid32
8421     case TARGET_NR_setreuid32:
8422         ret = get_errno(setreuid(arg1, arg2));
8423         break;
8424 #endif
8425 #ifdef TARGET_NR_setregid32
8426     case TARGET_NR_setregid32:
8427         ret = get_errno(setregid(arg1, arg2));
8428         break;
8429 #endif
8430 #ifdef TARGET_NR_getgroups32
8431     case TARGET_NR_getgroups32:
8432         {
8433             int gidsetsize = arg1;
8434             uint32_t *target_grouplist;
8435             gid_t *grouplist;
8436             int i;
8437
8438             grouplist = alloca(gidsetsize * sizeof(gid_t));
8439             ret = get_errno(getgroups(gidsetsize, grouplist));
8440             if (gidsetsize == 0)
8441                 break;
8442             if (!is_error(ret)) {
8443                 target_grouplist = lock_user(VERIFY_WRITE, arg2, gidsetsize * 4, 0);
8444                 if (!target_grouplist) {
8445                     ret = -TARGET_EFAULT;
8446                     goto fail;
8447                 }
8448                 for(i = 0;i < ret; i++)
8449                     target_grouplist[i] = tswap32(grouplist[i]);
8450                 unlock_user(target_grouplist, arg2, gidsetsize * 4);
8451             }
8452         }
8453         break;
8454 #endif
8455 #ifdef TARGET_NR_setgroups32
8456     case TARGET_NR_setgroups32:
8457         {
8458             int gidsetsize = arg1;
8459             uint32_t *target_grouplist;
8460             gid_t *grouplist;
8461             int i;
8462
8463             grouplist = alloca(gidsetsize * sizeof(gid_t));
8464             target_grouplist = lock_user(VERIFY_READ, arg2, gidsetsize * 4, 1);
8465             if (!target_grouplist) {
8466                 ret = -TARGET_EFAULT;
8467                 goto fail;
8468             }
8469             for(i = 0;i < gidsetsize; i++)
8470                 grouplist[i] = tswap32(target_grouplist[i]);
8471             unlock_user(target_grouplist, arg2, 0);
8472             ret = get_errno(setgroups(gidsetsize, grouplist));
8473         }
8474         break;
8475 #endif
8476 #ifdef TARGET_NR_fchown32
8477     case TARGET_NR_fchown32:
8478         ret = get_errno(fchown(arg1, arg2, arg3));
8479         break;
8480 #endif
8481 #ifdef TARGET_NR_setresuid32
8482     case TARGET_NR_setresuid32:
8483         ret = get_errno(setresuid(arg1, arg2, arg3));
8484         break;
8485 #endif
8486 #ifdef TARGET_NR_getresuid32
8487     case TARGET_NR_getresuid32:
8488         {
8489             uid_t ruid, euid, suid;
8490             ret = get_errno(getresuid(&ruid, &euid, &suid));
8491             if (!is_error(ret)) {
8492                 if (put_user_u32(ruid, arg1)
8493                     || put_user_u32(euid, arg2)
8494                     || put_user_u32(suid, arg3))
8495                     goto efault;
8496             }
8497         }
8498         break;
8499 #endif
8500 #ifdef TARGET_NR_setresgid32
8501     case TARGET_NR_setresgid32:
8502         ret = get_errno(setresgid(arg1, arg2, arg3));
8503         break;
8504 #endif
8505 #ifdef TARGET_NR_getresgid32
8506     case TARGET_NR_getresgid32:
8507         {
8508             gid_t rgid, egid, sgid;
8509             ret = get_errno(getresgid(&rgid, &egid, &sgid));
8510             if (!is_error(ret)) {
8511                 if (put_user_u32(rgid, arg1)
8512                     || put_user_u32(egid, arg2)
8513                     || put_user_u32(sgid, arg3))
8514                     goto efault;
8515             }
8516         }
8517         break;
8518 #endif
8519 #ifdef TARGET_NR_chown32
8520     case TARGET_NR_chown32:
8521         if (!(p = lock_user_string(arg1)))
8522             goto efault;
8523         ret = get_errno(chown(p, arg2, arg3));
8524         unlock_user(p, arg1, 0);
8525         break;
8526 #endif
8527 #ifdef TARGET_NR_setuid32
8528     case TARGET_NR_setuid32:
8529         ret = get_errno(setuid(arg1));
8530         break;
8531 #endif
8532 #ifdef TARGET_NR_setgid32
8533     case TARGET_NR_setgid32:
8534         ret = get_errno(setgid(arg1));
8535         break;
8536 #endif
8537 #ifdef TARGET_NR_setfsuid32
8538     case TARGET_NR_setfsuid32:
8539         ret = get_errno(setfsuid(arg1));
8540         break;
8541 #endif
8542 #ifdef TARGET_NR_setfsgid32
8543     case TARGET_NR_setfsgid32:
8544         ret = get_errno(setfsgid(arg1));
8545         break;
8546 #endif
8547
8548     case TARGET_NR_pivot_root:
8549         goto unimplemented;
8550 #ifdef TARGET_NR_mincore
8551     case TARGET_NR_mincore:
8552         {
8553             void *a;
8554             ret = -TARGET_EFAULT;
8555             if (!(a = lock_user(VERIFY_READ, arg1,arg2, 0)))
8556                 goto efault;
8557             if (!(p = lock_user_string(arg3)))
8558                 goto mincore_fail;
8559             ret = get_errno(mincore(a, arg2, p));
8560             unlock_user(p, arg3, ret);
8561             mincore_fail:
8562             unlock_user(a, arg1, 0);
8563         }
8564         break;
8565 #endif
8566 #ifdef TARGET_NR_arm_fadvise64_64
8567     case TARGET_NR_arm_fadvise64_64:
8568         {
8569                 /*
8570                  * arm_fadvise64_64 looks like fadvise64_64 but
8571                  * with different argument order
8572                  */
8573                 abi_long temp;
8574                 temp = arg3;
8575                 arg3 = arg4;
8576                 arg4 = temp;
8577         }
8578 #endif
8579 #if defined(TARGET_NR_fadvise64_64) || defined(TARGET_NR_arm_fadvise64_64) || defined(TARGET_NR_fadvise64)
8580 #ifdef TARGET_NR_fadvise64_64
8581     case TARGET_NR_fadvise64_64:
8582 #endif
8583 #ifdef TARGET_NR_fadvise64
8584     case TARGET_NR_fadvise64:
8585 #endif
8586 #ifdef TARGET_S390X
8587         switch (arg4) {
8588         case 4: arg4 = POSIX_FADV_NOREUSE + 1; break; /* make sure it's an invalid value */
8589         case 5: arg4 = POSIX_FADV_NOREUSE + 2; break; /* ditto */
8590         case 6: arg4 = POSIX_FADV_DONTNEED; break;
8591         case 7: arg4 = POSIX_FADV_NOREUSE; break;
8592         default: break;
8593         }
8594 #endif
8595         ret = -posix_fadvise(arg1, arg2, arg3, arg4);
8596         break;
8597 #endif
8598 #ifdef TARGET_NR_madvise
8599     case TARGET_NR_madvise:
8600         /* A straight passthrough may not be safe because qemu sometimes
8601            turns private file-backed mappings into anonymous mappings.
8602            This will break MADV_DONTNEED.
8603            This is a hint, so ignoring and returning success is ok.  */
8604         ret = get_errno(0);
8605         break;
8606 #endif
8607 #if TARGET_ABI_BITS == 32
8608     case TARGET_NR_fcntl64:
8609     {
8610         int cmd;
8611         struct flock64 fl;
8612         struct target_flock64 *target_fl;
8613 #ifdef TARGET_ARM
8614         struct target_eabi_flock64 *target_efl;
8615 #endif
8616
8617         cmd = target_to_host_fcntl_cmd(arg2);
8618         if (cmd == -TARGET_EINVAL) {
8619             ret = cmd;
8620             break;
8621         }
8622
8623         switch(arg2) {
8624         case TARGET_F_GETLK64:
8625 #ifdef TARGET_ARM
8626             if (((CPUARMState *)cpu_env)->eabi) {
8627                 if (!lock_user_struct(VERIFY_READ, target_efl, arg3, 1)) 
8628                     goto efault;
8629                 fl.l_type = tswap16(target_efl->l_type);
8630                 fl.l_whence = tswap16(target_efl->l_whence);
8631                 fl.l_start = tswap64(target_efl->l_start);
8632                 fl.l_len = tswap64(target_efl->l_len);
8633                 fl.l_pid = tswap32(target_efl->l_pid);
8634                 unlock_user_struct(target_efl, arg3, 0);
8635             } else
8636 #endif
8637             {
8638                 if (!lock_user_struct(VERIFY_READ, target_fl, arg3, 1)) 
8639                     goto efault;
8640                 fl.l_type = tswap16(target_fl->l_type);
8641                 fl.l_whence = tswap16(target_fl->l_whence);
8642                 fl.l_start = tswap64(target_fl->l_start);
8643                 fl.l_len = tswap64(target_fl->l_len);
8644                 fl.l_pid = tswap32(target_fl->l_pid);
8645                 unlock_user_struct(target_fl, arg3, 0);
8646             }
8647             ret = get_errno(fcntl(arg1, cmd, &fl));
8648             if (ret == 0) {
8649 #ifdef TARGET_ARM
8650                 if (((CPUARMState *)cpu_env)->eabi) {
8651                     if (!lock_user_struct(VERIFY_WRITE, target_efl, arg3, 0)) 
8652                         goto efault;
8653                     target_efl->l_type = tswap16(fl.l_type);
8654                     target_efl->l_whence = tswap16(fl.l_whence);
8655                     target_efl->l_start = tswap64(fl.l_start);
8656                     target_efl->l_len = tswap64(fl.l_len);
8657                     target_efl->l_pid = tswap32(fl.l_pid);
8658                     unlock_user_struct(target_efl, arg3, 1);
8659                 } else
8660 #endif
8661                 {
8662                     if (!lock_user_struct(VERIFY_WRITE, target_fl, arg3, 0)) 
8663                         goto efault;
8664                     target_fl->l_type = tswap16(fl.l_type);
8665                     target_fl->l_whence = tswap16(fl.l_whence);
8666                     target_fl->l_start = tswap64(fl.l_start);
8667                     target_fl->l_len = tswap64(fl.l_len);
8668                     target_fl->l_pid = tswap32(fl.l_pid);
8669                     unlock_user_struct(target_fl, arg3, 1);
8670                 }
8671             }
8672             break;
8673
8674         case TARGET_F_SETLK64:
8675         case TARGET_F_SETLKW64:
8676 #ifdef TARGET_ARM
8677             if (((CPUARMState *)cpu_env)->eabi) {
8678                 if (!lock_user_struct(VERIFY_READ, target_efl, arg3, 1)) 
8679                     goto efault;
8680                 fl.l_type = tswap16(target_efl->l_type);
8681                 fl.l_whence = tswap16(target_efl->l_whence);
8682                 fl.l_start = tswap64(target_efl->l_start);
8683                 fl.l_len = tswap64(target_efl->l_len);
8684                 fl.l_pid = tswap32(target_efl->l_pid);
8685                 unlock_user_struct(target_efl, arg3, 0);
8686             } else
8687 #endif
8688             {
8689                 if (!lock_user_struct(VERIFY_READ, target_fl, arg3, 1)) 
8690                     goto efault;
8691                 fl.l_type = tswap16(target_fl->l_type);
8692                 fl.l_whence = tswap16(target_fl->l_whence);
8693                 fl.l_start = tswap64(target_fl->l_start);
8694                 fl.l_len = tswap64(target_fl->l_len);
8695                 fl.l_pid = tswap32(target_fl->l_pid);
8696                 unlock_user_struct(target_fl, arg3, 0);
8697             }
8698             ret = get_errno(fcntl(arg1, cmd, &fl));
8699             break;
8700         default:
8701             ret = do_fcntl(arg1, arg2, arg3);
8702             break;
8703         }
8704         break;
8705     }
8706 #endif
8707 #ifdef TARGET_NR_cacheflush
8708     case TARGET_NR_cacheflush:
8709         /* self-modifying code is handled automatically, so nothing needed */
8710         ret = 0;
8711         break;
8712 #endif
8713 #ifdef TARGET_NR_security
8714     case TARGET_NR_security:
8715         goto unimplemented;
8716 #endif
8717 #ifdef TARGET_NR_getpagesize
8718     case TARGET_NR_getpagesize:
8719         ret = TARGET_PAGE_SIZE;
8720         break;
8721 #endif
8722     case TARGET_NR_gettid:
8723         ret = get_errno(gettid());
8724         break;
8725 #ifdef TARGET_NR_readahead
8726     case TARGET_NR_readahead:
8727 #if TARGET_ABI_BITS == 32
8728         if (regpairs_aligned(cpu_env)) {
8729             arg2 = arg3;
8730             arg3 = arg4;
8731             arg4 = arg5;
8732         }
8733         ret = get_errno(readahead(arg1, ((off64_t)arg3 << 32) | arg2, arg4));
8734 #else
8735         ret = get_errno(readahead(arg1, arg2, arg3));
8736 #endif
8737         break;
8738 #endif
8739 #ifdef CONFIG_ATTR
8740 #ifdef TARGET_NR_setxattr
8741     case TARGET_NR_listxattr:
8742     case TARGET_NR_llistxattr:
8743     {
8744         void *p, *b = 0;
8745         if (arg2) {
8746             b = lock_user(VERIFY_WRITE, arg2, arg3, 0);
8747             if (!b) {
8748                 ret = -TARGET_EFAULT;
8749                 break;
8750             }
8751         }
8752         p = lock_user_string(arg1);
8753         if (p) {
8754             if (num == TARGET_NR_listxattr) {
8755                 ret = get_errno(listxattr(p, b, arg3));
8756             } else {
8757                 ret = get_errno(llistxattr(p, b, arg3));
8758             }
8759         } else {
8760             ret = -TARGET_EFAULT;
8761         }
8762         unlock_user(p, arg1, 0);
8763         unlock_user(b, arg2, arg3);
8764         break;
8765     }
8766     case TARGET_NR_flistxattr:
8767     {
8768         void *b = 0;
8769         if (arg2) {
8770             b = lock_user(VERIFY_WRITE, arg2, arg3, 0);
8771             if (!b) {
8772                 ret = -TARGET_EFAULT;
8773                 break;
8774             }
8775         }
8776         ret = get_errno(flistxattr(arg1, b, arg3));
8777         unlock_user(b, arg2, arg3);
8778         break;
8779     }
8780     case TARGET_NR_setxattr:
8781     case TARGET_NR_lsetxattr:
8782         {
8783             void *p, *n, *v = 0;
8784             if (arg3) {
8785                 v = lock_user(VERIFY_READ, arg3, arg4, 1);
8786                 if (!v) {
8787                     ret = -TARGET_EFAULT;
8788                     break;
8789                 }
8790             }
8791             p = lock_user_string(arg1);
8792             n = lock_user_string(arg2);
8793             if (p && n) {
8794                 if (num == TARGET_NR_setxattr) {
8795                     ret = get_errno(setxattr(p, n, v, arg4, arg5));
8796                 } else {
8797                     ret = get_errno(lsetxattr(p, n, v, arg4, arg5));
8798                 }
8799             } else {
8800                 ret = -TARGET_EFAULT;
8801             }
8802             unlock_user(p, arg1, 0);
8803             unlock_user(n, arg2, 0);
8804             unlock_user(v, arg3, 0);
8805         }
8806         break;
8807     case TARGET_NR_fsetxattr:
8808         {
8809             void *n, *v = 0;
8810             if (arg3) {
8811                 v = lock_user(VERIFY_READ, arg3, arg4, 1);
8812                 if (!v) {
8813                     ret = -TARGET_EFAULT;
8814                     break;
8815                 }
8816             }
8817             n = lock_user_string(arg2);
8818             if (n) {
8819                 ret = get_errno(fsetxattr(arg1, n, v, arg4, arg5));
8820             } else {
8821                 ret = -TARGET_EFAULT;
8822             }
8823             unlock_user(n, arg2, 0);
8824             unlock_user(v, arg3, 0);
8825         }
8826         break;
8827     case TARGET_NR_getxattr:
8828     case TARGET_NR_lgetxattr:
8829         {
8830             void *p, *n, *v = 0;
8831             if (arg3) {
8832                 v = lock_user(VERIFY_WRITE, arg3, arg4, 0);
8833                 if (!v) {
8834                     ret = -TARGET_EFAULT;
8835                     break;
8836                 }
8837             }
8838             p = lock_user_string(arg1);
8839             n = lock_user_string(arg2);
8840             if (p && n) {
8841                 if (num == TARGET_NR_getxattr) {
8842                     ret = get_errno(getxattr(p, n, v, arg4));
8843                 } else {
8844                     ret = get_errno(lgetxattr(p, n, v, arg4));
8845                 }
8846             } else {
8847                 ret = -TARGET_EFAULT;
8848             }
8849             unlock_user(p, arg1, 0);
8850             unlock_user(n, arg2, 0);
8851             unlock_user(v, arg3, arg4);
8852         }
8853         break;
8854     case TARGET_NR_fgetxattr:
8855         {
8856             void *n, *v = 0;
8857             if (arg3) {
8858                 v = lock_user(VERIFY_WRITE, arg3, arg4, 0);
8859                 if (!v) {
8860                     ret = -TARGET_EFAULT;
8861                     break;
8862                 }
8863             }
8864             n = lock_user_string(arg2);
8865             if (n) {
8866                 ret = get_errno(fgetxattr(arg1, n, v, arg4));
8867             } else {
8868                 ret = -TARGET_EFAULT;
8869             }
8870             unlock_user(n, arg2, 0);
8871             unlock_user(v, arg3, arg4);
8872         }
8873         break;
8874     case TARGET_NR_removexattr:
8875     case TARGET_NR_lremovexattr:
8876         {
8877             void *p, *n;
8878             p = lock_user_string(arg1);
8879             n = lock_user_string(arg2);
8880             if (p && n) {
8881                 if (num == TARGET_NR_removexattr) {
8882                     ret = get_errno(removexattr(p, n));
8883                 } else {
8884                     ret = get_errno(lremovexattr(p, n));
8885                 }
8886             } else {
8887                 ret = -TARGET_EFAULT;
8888             }
8889             unlock_user(p, arg1, 0);
8890             unlock_user(n, arg2, 0);
8891         }
8892         break;
8893     case TARGET_NR_fremovexattr:
8894         {
8895             void *n;
8896             n = lock_user_string(arg2);
8897             if (n) {
8898                 ret = get_errno(fremovexattr(arg1, n));
8899             } else {
8900                 ret = -TARGET_EFAULT;
8901             }
8902             unlock_user(n, arg2, 0);
8903         }
8904         break;
8905 #endif
8906 #endif /* CONFIG_ATTR */
8907 #ifdef TARGET_NR_set_thread_area
8908     case TARGET_NR_set_thread_area:
8909 #if defined(TARGET_MIPS)
8910       ((CPUMIPSState *) cpu_env)->active_tc.CP0_UserLocal = arg1;
8911       ret = 0;
8912       break;
8913 #elif defined(TARGET_CRIS)
8914       if (arg1 & 0xff)
8915           ret = -TARGET_EINVAL;
8916       else {
8917           ((CPUCRISState *) cpu_env)->pregs[PR_PID] = arg1;
8918           ret = 0;
8919       }
8920       break;
8921 #elif defined(TARGET_I386) && defined(TARGET_ABI32)
8922       ret = do_set_thread_area(cpu_env, arg1);
8923       break;
8924 #elif defined(TARGET_M68K)
8925       {
8926           TaskState *ts = cpu->opaque;
8927           ts->tp_value = arg1;
8928           ret = 0;
8929           break;
8930       }
8931 #else
8932       goto unimplemented_nowarn;
8933 #endif
8934 #endif
8935 #ifdef TARGET_NR_get_thread_area
8936     case TARGET_NR_get_thread_area:
8937 #if defined(TARGET_I386) && defined(TARGET_ABI32)
8938         ret = do_get_thread_area(cpu_env, arg1);
8939         break;
8940 #elif defined(TARGET_M68K)
8941         {
8942             TaskState *ts = cpu->opaque;
8943             ret = ts->tp_value;
8944             break;
8945         }
8946 #else
8947         goto unimplemented_nowarn;
8948 #endif
8949 #endif
8950 #ifdef TARGET_NR_getdomainname
8951     case TARGET_NR_getdomainname:
8952         goto unimplemented_nowarn;
8953 #endif
8954
8955 #ifdef TARGET_NR_clock_gettime
8956     case TARGET_NR_clock_gettime:
8957     {
8958         struct timespec ts;
8959         ret = get_errno(clock_gettime(arg1, &ts));
8960         if (!is_error(ret)) {
8961             host_to_target_timespec(arg2, &ts);
8962         }
8963         break;
8964     }
8965 #endif
8966 #ifdef TARGET_NR_clock_getres
8967     case TARGET_NR_clock_getres:
8968     {
8969         struct timespec ts;
8970         ret = get_errno(clock_getres(arg1, &ts));
8971         if (!is_error(ret)) {
8972             host_to_target_timespec(arg2, &ts);
8973         }
8974         break;
8975     }
8976 #endif
8977 #ifdef TARGET_NR_clock_nanosleep
8978     case TARGET_NR_clock_nanosleep:
8979     {
8980         struct timespec ts;
8981         target_to_host_timespec(&ts, arg3);
8982         ret = get_errno(clock_nanosleep(arg1, arg2, &ts, arg4 ? &ts : NULL));
8983         if (arg4)
8984             host_to_target_timespec(arg4, &ts);
8985         break;
8986     }
8987 #endif
8988
8989 #if defined(TARGET_NR_set_tid_address) && defined(__NR_set_tid_address)
8990     case TARGET_NR_set_tid_address:
8991         ret = get_errno(set_tid_address((int *)g2h(arg1)));
8992         break;
8993 #endif
8994
8995 #if defined(TARGET_NR_tkill) && defined(__NR_tkill)
8996     case TARGET_NR_tkill:
8997         ret = get_errno(sys_tkill((int)arg1, target_to_host_signal(arg2)));
8998         break;
8999 #endif
9000
9001 #if defined(TARGET_NR_tgkill) && defined(__NR_tgkill)
9002     case TARGET_NR_tgkill:
9003         ret = get_errno(sys_tgkill((int)arg1, (int)arg2,
9004                         target_to_host_signal(arg3)));
9005         break;
9006 #endif
9007
9008 #ifdef TARGET_NR_set_robust_list
9009     case TARGET_NR_set_robust_list:
9010     case TARGET_NR_get_robust_list:
9011         /* The ABI for supporting robust futexes has userspace pass
9012          * the kernel a pointer to a linked list which is updated by
9013          * userspace after the syscall; the list is walked by the kernel
9014          * when the thread exits. Since the linked list in QEMU guest
9015          * memory isn't a valid linked list for the host and we have
9016          * no way to reliably intercept the thread-death event, we can't
9017          * support these. Silently return ENOSYS so that guest userspace
9018          * falls back to a non-robust futex implementation (which should
9019          * be OK except in the corner case of the guest crashing while
9020          * holding a mutex that is shared with another process via
9021          * shared memory).
9022          */
9023         goto unimplemented_nowarn;
9024 #endif
9025
9026 #if defined(TARGET_NR_utimensat)
9027     case TARGET_NR_utimensat:
9028         {
9029             struct timespec *tsp, ts[2];
9030             if (!arg3) {
9031                 tsp = NULL;
9032             } else {
9033                 target_to_host_timespec(ts, arg3);
9034                 target_to_host_timespec(ts+1, arg3+sizeof(struct target_timespec));
9035                 tsp = ts;
9036             }
9037             if (!arg2)
9038                 ret = get_errno(sys_utimensat(arg1, NULL, tsp, arg4));
9039             else {
9040                 if (!(p = lock_user_string(arg2))) {
9041                     ret = -TARGET_EFAULT;
9042                     goto fail;
9043                 }
9044                 ret = get_errno(sys_utimensat(arg1, path(p), tsp, arg4));
9045                 unlock_user(p, arg2, 0);
9046             }
9047         }
9048         break;
9049 #endif
9050     case TARGET_NR_futex:
9051         ret = do_futex(arg1, arg2, arg3, arg4, arg5, arg6);
9052         break;
9053 #if defined(TARGET_NR_inotify_init) && defined(__NR_inotify_init)
9054     case TARGET_NR_inotify_init:
9055         ret = get_errno(sys_inotify_init());
9056         break;
9057 #endif
9058 #ifdef CONFIG_INOTIFY1
9059 #if defined(TARGET_NR_inotify_init1) && defined(__NR_inotify_init1)
9060     case TARGET_NR_inotify_init1:
9061         ret = get_errno(sys_inotify_init1(arg1));
9062         break;
9063 #endif
9064 #endif
9065 #if defined(TARGET_NR_inotify_add_watch) && defined(__NR_inotify_add_watch)
9066     case TARGET_NR_inotify_add_watch:
9067         p = lock_user_string(arg2);
9068         ret = get_errno(sys_inotify_add_watch(arg1, path(p), arg3));
9069         unlock_user(p, arg2, 0);
9070         break;
9071 #endif
9072 #if defined(TARGET_NR_inotify_rm_watch) && defined(__NR_inotify_rm_watch)
9073     case TARGET_NR_inotify_rm_watch:
9074         ret = get_errno(sys_inotify_rm_watch(arg1, arg2));
9075         break;
9076 #endif
9077
9078 #if defined(TARGET_NR_mq_open) && defined(__NR_mq_open)
9079     case TARGET_NR_mq_open:
9080         {
9081             struct mq_attr posix_mq_attr;
9082
9083             p = lock_user_string(arg1 - 1);
9084             if (arg4 != 0)
9085                 copy_from_user_mq_attr (&posix_mq_attr, arg4);
9086             ret = get_errno(mq_open(p, arg2, arg3, &posix_mq_attr));
9087             unlock_user (p, arg1, 0);
9088         }
9089         break;
9090
9091     case TARGET_NR_mq_unlink:
9092         p = lock_user_string(arg1 - 1);
9093         ret = get_errno(mq_unlink(p));
9094         unlock_user (p, arg1, 0);
9095         break;
9096
9097     case TARGET_NR_mq_timedsend:
9098         {
9099             struct timespec ts;
9100
9101             p = lock_user (VERIFY_READ, arg2, arg3, 1);
9102             if (arg5 != 0) {
9103                 target_to_host_timespec(&ts, arg5);
9104                 ret = get_errno(mq_timedsend(arg1, p, arg3, arg4, &ts));
9105                 host_to_target_timespec(arg5, &ts);
9106             }
9107             else
9108                 ret = get_errno(mq_send(arg1, p, arg3, arg4));
9109             unlock_user (p, arg2, arg3);
9110         }
9111         break;
9112
9113     case TARGET_NR_mq_timedreceive:
9114         {
9115             struct timespec ts;
9116             unsigned int prio;
9117
9118             p = lock_user (VERIFY_READ, arg2, arg3, 1);
9119             if (arg5 != 0) {
9120                 target_to_host_timespec(&ts, arg5);
9121                 ret = get_errno(mq_timedreceive(arg1, p, arg3, &prio, &ts));
9122                 host_to_target_timespec(arg5, &ts);
9123             }
9124             else
9125                 ret = get_errno(mq_receive(arg1, p, arg3, &prio));
9126             unlock_user (p, arg2, arg3);
9127             if (arg4 != 0)
9128                 put_user_u32(prio, arg4);
9129         }
9130         break;
9131
9132     /* Not implemented for now... */
9133 /*     case TARGET_NR_mq_notify: */
9134 /*         break; */
9135
9136     case TARGET_NR_mq_getsetattr:
9137         {
9138             struct mq_attr posix_mq_attr_in, posix_mq_attr_out;
9139             ret = 0;
9140             if (arg3 != 0) {
9141                 ret = mq_getattr(arg1, &posix_mq_attr_out);
9142                 copy_to_user_mq_attr(arg3, &posix_mq_attr_out);
9143             }
9144             if (arg2 != 0) {
9145                 copy_from_user_mq_attr(&posix_mq_attr_in, arg2);
9146                 ret |= mq_setattr(arg1, &posix_mq_attr_in, &posix_mq_attr_out);
9147             }
9148
9149         }
9150         break;
9151 #endif
9152
9153 #ifdef CONFIG_SPLICE
9154 #ifdef TARGET_NR_tee
9155     case TARGET_NR_tee:
9156         {
9157             ret = get_errno(tee(arg1,arg2,arg3,arg4));
9158         }
9159         break;
9160 #endif
9161 #ifdef TARGET_NR_splice
9162     case TARGET_NR_splice:
9163         {
9164             loff_t loff_in, loff_out;
9165             loff_t *ploff_in = NULL, *ploff_out = NULL;
9166             if(arg2) {
9167                 get_user_u64(loff_in, arg2);
9168                 ploff_in = &loff_in;
9169             }
9170             if(arg4) {
9171                 get_user_u64(loff_out, arg2);
9172                 ploff_out = &loff_out;
9173             }
9174             ret = get_errno(splice(arg1, ploff_in, arg3, ploff_out, arg5, arg6));
9175         }
9176         break;
9177 #endif
9178 #ifdef TARGET_NR_vmsplice
9179         case TARGET_NR_vmsplice:
9180         {
9181             struct iovec *vec = lock_iovec(VERIFY_READ, arg2, arg3, 1);
9182             if (vec != NULL) {
9183                 ret = get_errno(vmsplice(arg1, vec, arg3, arg4));
9184                 unlock_iovec(vec, arg2, arg3, 0);
9185             } else {
9186                 ret = -host_to_target_errno(errno);
9187             }
9188         }
9189         break;
9190 #endif
9191 #endif /* CONFIG_SPLICE */
9192 #ifdef CONFIG_EVENTFD
9193 #if defined(TARGET_NR_eventfd)
9194     case TARGET_NR_eventfd:
9195         ret = get_errno(eventfd(arg1, 0));
9196         break;
9197 #endif
9198 #if defined(TARGET_NR_eventfd2)
9199     case TARGET_NR_eventfd2:
9200     {
9201         int host_flags = arg2 & (~(TARGET_O_NONBLOCK | TARGET_O_CLOEXEC));
9202         if (arg2 & TARGET_O_NONBLOCK) {
9203             host_flags |= O_NONBLOCK;
9204         }
9205         if (arg2 & TARGET_O_CLOEXEC) {
9206             host_flags |= O_CLOEXEC;
9207         }
9208         ret = get_errno(eventfd(arg1, host_flags));
9209         break;
9210     }
9211 #endif
9212 #endif /* CONFIG_EVENTFD  */
9213 #if defined(CONFIG_FALLOCATE) && defined(TARGET_NR_fallocate)
9214     case TARGET_NR_fallocate:
9215 #if TARGET_ABI_BITS == 32
9216         ret = get_errno(fallocate(arg1, arg2, target_offset64(arg3, arg4),
9217                                   target_offset64(arg5, arg6)));
9218 #else
9219         ret = get_errno(fallocate(arg1, arg2, arg3, arg4));
9220 #endif
9221         break;
9222 #endif
9223 #if defined(CONFIG_SYNC_FILE_RANGE)
9224 #if defined(TARGET_NR_sync_file_range)
9225     case TARGET_NR_sync_file_range:
9226 #if TARGET_ABI_BITS == 32
9227 #if defined(TARGET_MIPS)
9228         ret = get_errno(sync_file_range(arg1, target_offset64(arg3, arg4),
9229                                         target_offset64(arg5, arg6), arg7));
9230 #else
9231         ret = get_errno(sync_file_range(arg1, target_offset64(arg2, arg3),
9232                                         target_offset64(arg4, arg5), arg6));
9233 #endif /* !TARGET_MIPS */
9234 #else
9235         ret = get_errno(sync_file_range(arg1, arg2, arg3, arg4));
9236 #endif
9237         break;
9238 #endif
9239 #if defined(TARGET_NR_sync_file_range2)
9240     case TARGET_NR_sync_file_range2:
9241         /* This is like sync_file_range but the arguments are reordered */
9242 #if TARGET_ABI_BITS == 32
9243         ret = get_errno(sync_file_range(arg1, target_offset64(arg3, arg4),
9244                                         target_offset64(arg5, arg6), arg2));
9245 #else
9246         ret = get_errno(sync_file_range(arg1, arg3, arg4, arg2));
9247 #endif
9248         break;
9249 #endif
9250 #endif
9251 #if defined(CONFIG_EPOLL)
9252 #if defined(TARGET_NR_epoll_create)
9253     case TARGET_NR_epoll_create:
9254         ret = get_errno(epoll_create(arg1));
9255         break;
9256 #endif
9257 #if defined(TARGET_NR_epoll_create1) && defined(CONFIG_EPOLL_CREATE1)
9258     case TARGET_NR_epoll_create1:
9259         ret = get_errno(epoll_create1(arg1));
9260         break;
9261 #endif
9262 #if defined(TARGET_NR_epoll_ctl)
9263     case TARGET_NR_epoll_ctl:
9264     {
9265         struct epoll_event ep;
9266         struct epoll_event *epp = 0;
9267         if (arg4) {
9268             struct target_epoll_event *target_ep;
9269             if (!lock_user_struct(VERIFY_READ, target_ep, arg4, 1)) {
9270                 goto efault;
9271             }
9272             ep.events = tswap32(target_ep->events);
9273             /* The epoll_data_t union is just opaque data to the kernel,
9274              * so we transfer all 64 bits across and need not worry what
9275              * actual data type it is.
9276              */
9277             ep.data.u64 = tswap64(target_ep->data.u64);
9278             unlock_user_struct(target_ep, arg4, 0);
9279             epp = &ep;
9280         }
9281         ret = get_errno(epoll_ctl(arg1, arg2, arg3, epp));
9282         break;
9283     }
9284 #endif
9285
9286 #if defined(TARGET_NR_epoll_pwait) && defined(CONFIG_EPOLL_PWAIT)
9287 #define IMPLEMENT_EPOLL_PWAIT
9288 #endif
9289 #if defined(TARGET_NR_epoll_wait) || defined(IMPLEMENT_EPOLL_PWAIT)
9290 #if defined(TARGET_NR_epoll_wait)
9291     case TARGET_NR_epoll_wait:
9292 #endif
9293 #if defined(IMPLEMENT_EPOLL_PWAIT)
9294     case TARGET_NR_epoll_pwait:
9295 #endif
9296     {
9297         struct target_epoll_event *target_ep;
9298         struct epoll_event *ep;
9299         int epfd = arg1;
9300         int maxevents = arg3;
9301         int timeout = arg4;
9302
9303         target_ep = lock_user(VERIFY_WRITE, arg2,
9304                               maxevents * sizeof(struct target_epoll_event), 1);
9305         if (!target_ep) {
9306             goto efault;
9307         }
9308
9309         ep = alloca(maxevents * sizeof(struct epoll_event));
9310
9311         switch (num) {
9312 #if defined(IMPLEMENT_EPOLL_PWAIT)
9313         case TARGET_NR_epoll_pwait:
9314         {
9315             target_sigset_t *target_set;
9316             sigset_t _set, *set = &_set;
9317
9318             if (arg5) {
9319                 target_set = lock_user(VERIFY_READ, arg5,
9320                                        sizeof(target_sigset_t), 1);
9321                 if (!target_set) {
9322                     unlock_user(target_ep, arg2, 0);
9323                     goto efault;
9324                 }
9325                 target_to_host_sigset(set, target_set);
9326                 unlock_user(target_set, arg5, 0);
9327             } else {
9328                 set = NULL;
9329             }
9330
9331             ret = get_errno(epoll_pwait(epfd, ep, maxevents, timeout, set));
9332             break;
9333         }
9334 #endif
9335 #if defined(TARGET_NR_epoll_wait)
9336         case TARGET_NR_epoll_wait:
9337             ret = get_errno(epoll_wait(epfd, ep, maxevents, timeout));
9338             break;
9339 #endif
9340         default:
9341             ret = -TARGET_ENOSYS;
9342         }
9343         if (!is_error(ret)) {
9344             int i;
9345             for (i = 0; i < ret; i++) {
9346                 target_ep[i].events = tswap32(ep[i].events);
9347                 target_ep[i].data.u64 = tswap64(ep[i].data.u64);
9348             }
9349         }
9350         unlock_user(target_ep, arg2, ret * sizeof(struct target_epoll_event));
9351         break;
9352     }
9353 #endif
9354 #endif
9355 #ifdef TARGET_NR_prlimit64
9356     case TARGET_NR_prlimit64:
9357     {
9358         /* args: pid, resource number, ptr to new rlimit, ptr to old rlimit */
9359         struct target_rlimit64 *target_rnew, *target_rold;
9360         struct host_rlimit64 rnew, rold, *rnewp = 0;
9361         if (arg3) {
9362             if (!lock_user_struct(VERIFY_READ, target_rnew, arg3, 1)) {
9363                 goto efault;
9364             }
9365             rnew.rlim_cur = tswap64(target_rnew->rlim_cur);
9366             rnew.rlim_max = tswap64(target_rnew->rlim_max);
9367             unlock_user_struct(target_rnew, arg3, 0);
9368             rnewp = &rnew;
9369         }
9370
9371         ret = get_errno(sys_prlimit64(arg1, arg2, rnewp, arg4 ? &rold : 0));
9372         if (!is_error(ret) && arg4) {
9373             if (!lock_user_struct(VERIFY_WRITE, target_rold, arg4, 1)) {
9374                 goto efault;
9375             }
9376             target_rold->rlim_cur = tswap64(rold.rlim_cur);
9377             target_rold->rlim_max = tswap64(rold.rlim_max);
9378             unlock_user_struct(target_rold, arg4, 1);
9379         }
9380         break;
9381     }
9382 #endif
9383 #ifdef TARGET_NR_gethostname
9384     case TARGET_NR_gethostname:
9385     {
9386         char *name = lock_user(VERIFY_WRITE, arg1, arg2, 0);
9387         if (name) {
9388             ret = get_errno(gethostname(name, arg2));
9389             unlock_user(name, arg1, arg2);
9390         } else {
9391             ret = -TARGET_EFAULT;
9392         }
9393         break;
9394     }
9395 #endif
9396 #ifdef TARGET_NR_atomic_cmpxchg_32
9397     case TARGET_NR_atomic_cmpxchg_32:
9398     {
9399         /* should use start_exclusive from main.c */
9400         abi_ulong mem_value;
9401         if (get_user_u32(mem_value, arg6)) {
9402             target_siginfo_t info;
9403             info.si_signo = SIGSEGV;
9404             info.si_errno = 0;
9405             info.si_code = TARGET_SEGV_MAPERR;
9406             info._sifields._sigfault._addr = arg6;
9407             queue_signal((CPUArchState *)cpu_env, info.si_signo, &info);
9408             ret = 0xdeadbeef;
9409
9410         }
9411         if (mem_value == arg2)
9412             put_user_u32(arg1, arg6);
9413         ret = mem_value;
9414         break;
9415     }
9416 #endif
9417 #ifdef TARGET_NR_atomic_barrier
9418     case TARGET_NR_atomic_barrier:
9419     {
9420         /* Like the kernel implementation and the qemu arm barrier, no-op this? */
9421         ret = 0;
9422         break;
9423     }
9424 #endif
9425
9426 #ifdef TARGET_NR_timer_create
9427     case TARGET_NR_timer_create:
9428     {
9429         /* args: clockid_t clockid, struct sigevent *sevp, timer_t *timerid */
9430
9431         struct sigevent host_sevp = { {0}, }, *phost_sevp = NULL;
9432         struct target_timer_t *ptarget_timer;
9433
9434         int clkid = arg1;
9435         int timer_index = next_free_host_timer();
9436
9437         if (timer_index < 0) {
9438             ret = -TARGET_EAGAIN;
9439         } else {
9440             timer_t *phtimer = g_posix_timers  + timer_index;
9441
9442             if (arg2) {
9443                 phost_sevp = &host_sevp;
9444                 ret = target_to_host_sigevent(phost_sevp, arg2);
9445                 if (ret != 0) {
9446                     break;
9447                 }
9448             }
9449
9450             ret = get_errno(timer_create(clkid, phost_sevp, phtimer));
9451             if (ret) {
9452                 phtimer = NULL;
9453             } else {
9454                 if (!lock_user_struct(VERIFY_WRITE, ptarget_timer, arg3, 1)) {
9455                     goto efault;
9456                 }
9457                 ptarget_timer->ptr = tswap32(0xcafe0000 | timer_index);
9458                 unlock_user_struct(ptarget_timer, arg3, 1);
9459             }
9460         }
9461         break;
9462     }
9463 #endif
9464
9465 #ifdef TARGET_NR_timer_settime
9466     case TARGET_NR_timer_settime:
9467     {
9468         /* args: timer_t timerid, int flags, const struct itimerspec *new_value,
9469          * struct itimerspec * old_value */
9470         arg1 &= 0xffff;
9471         if (arg3 == 0 || arg1 < 0 || arg1 >= ARRAY_SIZE(g_posix_timers)) {
9472             ret = -TARGET_EINVAL;
9473         } else {
9474             timer_t htimer = g_posix_timers[arg1];
9475             struct itimerspec hspec_new = {{0},}, hspec_old = {{0},};
9476
9477             target_to_host_itimerspec(&hspec_new, arg3);
9478             ret = get_errno(
9479                           timer_settime(htimer, arg2, &hspec_new, &hspec_old));
9480             host_to_target_itimerspec(arg2, &hspec_old);
9481         }
9482         break;
9483     }
9484 #endif
9485
9486 #ifdef TARGET_NR_timer_gettime
9487     case TARGET_NR_timer_gettime:
9488     {
9489         /* args: timer_t timerid, struct itimerspec *curr_value */
9490         arg1 &= 0xffff;
9491         if (!arg2) {
9492             return -TARGET_EFAULT;
9493         } else if (arg1 < 0 || arg1 >= ARRAY_SIZE(g_posix_timers)) {
9494             ret = -TARGET_EINVAL;
9495         } else {
9496             timer_t htimer = g_posix_timers[arg1];
9497             struct itimerspec hspec;
9498             ret = get_errno(timer_gettime(htimer, &hspec));
9499
9500             if (host_to_target_itimerspec(arg2, &hspec)) {
9501                 ret = -TARGET_EFAULT;
9502             }
9503         }
9504         break;
9505     }
9506 #endif
9507
9508 #ifdef TARGET_NR_timer_getoverrun
9509     case TARGET_NR_timer_getoverrun:
9510     {
9511         /* args: timer_t timerid */
9512         arg1 &= 0xffff;
9513         if (arg1 < 0 || arg1 >= ARRAY_SIZE(g_posix_timers)) {
9514             ret = -TARGET_EINVAL;
9515         } else {
9516             timer_t htimer = g_posix_timers[arg1];
9517             ret = get_errno(timer_getoverrun(htimer));
9518         }
9519         break;
9520     }
9521 #endif
9522
9523 #ifdef TARGET_NR_timer_delete
9524     case TARGET_NR_timer_delete:
9525     {
9526         /* args: timer_t timerid */
9527         arg1 &= 0xffff;
9528         if (arg1 < 0 || arg1 >= ARRAY_SIZE(g_posix_timers)) {
9529             ret = -TARGET_EINVAL;
9530         } else {
9531             timer_t htimer = g_posix_timers[arg1];
9532             ret = get_errno(timer_delete(htimer));
9533             g_posix_timers[arg1] = 0;
9534         }
9535         break;
9536     }
9537 #endif
9538
9539     default:
9540     unimplemented:
9541         gemu_log("qemu: Unsupported syscall: %d\n", num);
9542 #if defined(TARGET_NR_setxattr) || defined(TARGET_NR_get_thread_area) || defined(TARGET_NR_getdomainname) || defined(TARGET_NR_set_robust_list)
9543     unimplemented_nowarn:
9544 #endif
9545         ret = -TARGET_ENOSYS;
9546         break;
9547     }
9548 fail:
9549 #ifdef DEBUG
9550     gemu_log(" = " TARGET_ABI_FMT_ld "\n", ret);
9551 #endif
9552     if(do_strace)
9553         print_syscall_ret(num, ret);
9554     return ret;
9555 efault:
9556     ret = -TARGET_EFAULT;
9557     goto fail;
9558 }
This page took 0.546068 seconds and 4 git commands to generate.