syscall_emul.cc revision 14024
1/*
2 * Copyright (c) 2003-2005 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Steve Reinhardt
29 *          Ali Saidi
30 */
31
32#include "sim/syscall_emul.hh"
33
34#include <fcntl.h>
35#include <sys/syscall.h>
36#include <unistd.h>
37
38#include <csignal>
39#include <iostream>
40#include <mutex>
41#include <string>
42
43#include "arch/utility.hh"
44#include "base/chunk_generator.hh"
45#include "base/trace.hh"
46#include "config/the_isa.hh"
47#include "cpu/thread_context.hh"
48#include "dev/net/dist_iface.hh"
49#include "mem/page_table.hh"
50#include "sim/byteswap.hh"
51#include "sim/process.hh"
52#include "sim/sim_exit.hh"
53#include "sim/syscall_debug_macros.hh"
54#include "sim/syscall_desc.hh"
55#include "sim/system.hh"
56
57using namespace std;
58using namespace TheISA;
59
60void
61warnUnsupportedOS(std::string syscall_name)
62{
63    warn("Cannot invoke %s on host operating system.", syscall_name);
64}
65
66SyscallReturn
67unimplementedFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
68{
69    fatal("syscall %s (#%d) unimplemented.", desc->name(), callnum);
70
71    return 1;
72}
73
74
75SyscallReturn
76ignoreFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
77{
78    if (desc->needWarning()) {
79        warn("ignoring syscall %s(...)%s", desc->name(), desc->warnOnce() ?
80             "\n      (further warnings will be suppressed)" : "");
81    }
82
83    return 0;
84}
85
86static void
87exitFutexWake(ThreadContext *tc, Addr addr, uint64_t tgid)
88{
89    // Clear value at address pointed to by thread's childClearTID field.
90    BufferArg ctidBuf(addr, sizeof(long));
91    long *ctid = (long *)ctidBuf.bufferPtr();
92    *ctid = 0;
93    ctidBuf.copyOut(tc->getVirtProxy());
94
95    FutexMap &futex_map = tc->getSystemPtr()->futexMap;
96    // Wake one of the waiting threads.
97    futex_map.wakeup(addr, tgid, 1);
98}
99
100static SyscallReturn
101exitImpl(SyscallDesc *desc, int callnum, ThreadContext *tc, bool group)
102{
103    int index = 0;
104    auto p = tc->getProcessPtr();
105    int status = p->getSyscallArg(tc, index);
106
107    System *sys = tc->getSystemPtr();
108
109    if (group)
110        *p->exitGroup = true;
111
112    if (p->childClearTID)
113        exitFutexWake(tc, p->childClearTID, p->tgid());
114
115    bool last_thread = true;
116    Process *parent = nullptr, *tg_lead = nullptr;
117    for (int i = 0; last_thread && i < sys->numContexts(); i++) {
118        Process *walk;
119        if (!(walk = sys->threadContexts[i]->getProcessPtr()))
120            continue;
121
122        /**
123         * Threads in a thread group require special handing. For instance,
124         * we send the SIGCHLD signal so that it appears that it came from
125         * the head of the group. We also only delete file descriptors if
126         * we are the last thread in the thread group.
127         */
128        if (walk->pid() == p->tgid())
129            tg_lead = walk;
130
131        if ((sys->threadContexts[i]->status() != ThreadContext::Halted) &&
132            (sys->threadContexts[i]->status() != ThreadContext::Halting) &&
133            (walk != p)) {
134            /**
135             * Check if we share thread group with the pointer; this denotes
136             * that we are not the last thread active in the thread group.
137             * Note that setting this to false also prevents further
138             * iterations of the loop.
139             */
140            if (walk->tgid() == p->tgid()) {
141                /**
142                 * If p is trying to exit_group and both walk and p are in
143                 * the same thread group (i.e., sharing the same tgid),
144                 * we need to halt walk's thread context. After all threads
145                 * except p are halted, p becomes the last thread in the
146                 * group.
147                 *
148                 * If p is not doing exit_group and there exists another
149                 * active thread context in the group, last_thread is
150                 * set to false to prevent the parent thread from killing
151                 * all threads in the group.
152                 */
153                if (*(p->exitGroup)) {
154                    sys->threadContexts[i]->halt();
155                } else {
156                    last_thread = false;
157                }
158            }
159
160            /**
161             * A corner case exists which involves execve(). After execve(),
162             * the execve will enable SIGCHLD in the process. The problem
163             * occurs when the exiting process is the root process in the
164             * system; there is no parent to receive the signal. We obviate
165             * this problem by setting the root process' ppid to zero in the
166             * Python configuration files. We really should handle the
167             * root/execve specific case more gracefully.
168             */
169            if (*p->sigchld && (p->ppid() != 0) && (walk->pid() == p->ppid()))
170                parent = walk;
171        }
172    }
173
174    if (last_thread) {
175        if (parent) {
176            assert(tg_lead);
177            sys->signalList.push_back(BasicSignal(tg_lead, parent, SIGCHLD));
178        }
179
180        /**
181         * Run though FD array of the exiting process and close all file
182         * descriptors except for the standard file descriptors.
183         * (The standard file descriptors are shared with gem5.)
184         */
185        for (int i = 0; i < p->fds->getSize(); i++) {
186            if ((*p->fds)[i])
187                p->fds->closeFDEntry(i);
188        }
189    }
190
191    tc->halt();
192
193    /**
194     * check to see if there is no more active thread in the system. If so,
195     * exit the simulation loop
196     */
197    int activeContexts = 0;
198    for (auto &system: sys->systemList)
199        activeContexts += system->numRunningContexts();
200
201    if (activeContexts == 0) {
202        /**
203         * Even though we are terminating the final thread context, dist-gem5
204         * requires the simulation to remain active and provide
205         * synchronization messages to the switch process. So we just halt
206         * the last thread context and return. The simulation will be
207         * terminated by dist-gem5 in a coordinated manner once all nodes
208         * have signaled their readiness to exit. For non dist-gem5
209         * simulations, readyToExit() always returns true.
210         */
211        if (!DistIface::readyToExit(0)) {
212            return status;
213        }
214
215        exitSimLoop("exiting with last active thread context", status & 0xff);
216        return status;
217    }
218
219    return status;
220}
221
222SyscallReturn
223exitFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
224{
225    return exitImpl(desc, callnum, tc, false);
226}
227
228SyscallReturn
229exitGroupFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
230{
231    return exitImpl(desc, callnum, tc, true);
232}
233
234SyscallReturn
235getpagesizeFunc(SyscallDesc *desc, int num, ThreadContext *tc)
236{
237    return (int)PageBytes;
238}
239
240
241SyscallReturn
242brkFunc(SyscallDesc *desc, int num, ThreadContext *tc)
243{
244    // change brk addr to first arg
245    int index = 0;
246    auto p = tc->getProcessPtr();
247    Addr new_brk = p->getSyscallArg(tc, index);
248
249    std::shared_ptr<MemState> mem_state = p->memState;
250    Addr brk_point = mem_state->getBrkPoint();
251
252    // in Linux at least, brk(0) returns the current break value
253    // (note that the syscall and the glibc function have different behavior)
254    if (new_brk == 0)
255        return brk_point;
256
257    if (new_brk > brk_point) {
258        // might need to allocate some new pages
259        for (ChunkGenerator gen(brk_point,
260                                new_brk - brk_point,
261                                PageBytes); !gen.done(); gen.next()) {
262            if (!p->pTable->translate(gen.addr()))
263                p->allocateMem(roundDown(gen.addr(), PageBytes), PageBytes);
264
265            // if the address is already there, zero it out
266            else {
267                uint8_t zero = 0;
268                PortProxy &tp = tc->getVirtProxy();
269
270                // split non-page aligned accesses
271                Addr next_page = roundUp(gen.addr(), PageBytes);
272                uint32_t size_needed = next_page - gen.addr();
273                tp.memsetBlob(gen.addr(), zero, size_needed);
274                if (gen.addr() + PageBytes > next_page &&
275                    next_page < new_brk &&
276                    p->pTable->translate(next_page)) {
277                    size_needed = PageBytes - size_needed;
278                    tp.memsetBlob(next_page, zero, size_needed);
279                }
280            }
281        }
282    }
283
284    mem_state->setBrkPoint(new_brk);
285    DPRINTF_SYSCALL(Verbose, "brk: break point changed to: %#X\n",
286                    mem_state->getBrkPoint());
287    return mem_state->getBrkPoint();
288}
289
290SyscallReturn
291setTidAddressFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
292{
293    int index = 0;
294    auto process = tc->getProcessPtr();
295    uint64_t tidPtr = process->getSyscallArg(tc, index);
296
297    process->childClearTID = tidPtr;
298    return process->pid();
299}
300
301SyscallReturn
302closeFunc(SyscallDesc *desc, int num, ThreadContext *tc)
303{
304    int index = 0;
305    auto p = tc->getProcessPtr();
306    int tgt_fd = p->getSyscallArg(tc, index);
307
308    return p->fds->closeFDEntry(tgt_fd);
309}
310
311SyscallReturn
312lseekFunc(SyscallDesc *desc, int num, ThreadContext *tc)
313{
314    int index = 0;
315    auto p = tc->getProcessPtr();
316    int tgt_fd = p->getSyscallArg(tc, index);
317    uint64_t offs = p->getSyscallArg(tc, index);
318    int whence = p->getSyscallArg(tc, index);
319
320    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
321    if (!ffdp)
322        return -EBADF;
323    int sim_fd = ffdp->getSimFD();
324
325    off_t result = lseek(sim_fd, offs, whence);
326
327    return (result == (off_t)-1) ? -errno : result;
328}
329
330
331SyscallReturn
332_llseekFunc(SyscallDesc *desc, int num, ThreadContext *tc)
333{
334    int index = 0;
335    auto p = tc->getProcessPtr();
336    int tgt_fd = p->getSyscallArg(tc, index);
337    uint64_t offset_high = p->getSyscallArg(tc, index);
338    uint32_t offset_low = p->getSyscallArg(tc, index);
339    Addr result_ptr = p->getSyscallArg(tc, index);
340    int whence = p->getSyscallArg(tc, index);
341
342    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
343    if (!ffdp)
344        return -EBADF;
345    int sim_fd = ffdp->getSimFD();
346
347    uint64_t offset = (offset_high << 32) | offset_low;
348
349    uint64_t result = lseek(sim_fd, offset, whence);
350    result = TheISA::htog(result);
351
352    if (result == (off_t)-1)
353        return -errno;
354    // Assuming that the size of loff_t is 64 bits on the target platform
355    BufferArg result_buf(result_ptr, sizeof(result));
356    memcpy(result_buf.bufferPtr(), &result, sizeof(result));
357    result_buf.copyOut(tc->getVirtProxy());
358    return 0;
359}
360
361
362SyscallReturn
363munmapFunc(SyscallDesc *desc, int num, ThreadContext *tc)
364{
365    // With mmap more fully implemented, it might be worthwhile to bite
366    // the bullet and implement munmap. Should allow us to reuse simulated
367    // memory.
368    return 0;
369}
370
371
372const char *hostname = "m5.eecs.umich.edu";
373
374SyscallReturn
375gethostnameFunc(SyscallDesc *desc, int num, ThreadContext *tc)
376{
377    int index = 0;
378    auto p = tc->getProcessPtr();
379    Addr buf_ptr = p->getSyscallArg(tc, index);
380    int name_len = p->getSyscallArg(tc, index);
381    BufferArg name(buf_ptr, name_len);
382
383    strncpy((char *)name.bufferPtr(), hostname, name_len);
384
385    name.copyOut(tc->getVirtProxy());
386
387    return 0;
388}
389
390SyscallReturn
391getcwdFunc(SyscallDesc *desc, int num, ThreadContext *tc)
392{
393    int result = 0;
394    int index = 0;
395    auto p = tc->getProcessPtr();
396    Addr buf_ptr = p->getSyscallArg(tc, index);
397    unsigned long size = p->getSyscallArg(tc, index);
398    BufferArg buf(buf_ptr, size);
399
400    // Is current working directory defined?
401    string cwd = p->tgtCwd;
402    if (!cwd.empty()) {
403        if (cwd.length() >= size) {
404            // Buffer too small
405            return -ERANGE;
406        }
407        strncpy((char *)buf.bufferPtr(), cwd.c_str(), size);
408        result = cwd.length();
409    } else {
410        if (getcwd((char *)buf.bufferPtr(), size)) {
411            result = strlen((char *)buf.bufferPtr());
412        } else {
413            result = -1;
414        }
415    }
416
417    buf.copyOut(tc->getVirtProxy());
418
419    return (result == -1) ? -errno : result;
420}
421
422SyscallReturn
423readlinkFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
424{
425    return readlinkFunc(desc, callnum, tc, 0);
426}
427
428SyscallReturn
429readlinkFunc(SyscallDesc *desc, int num, ThreadContext *tc, int index)
430{
431    string path;
432    auto p = tc->getProcessPtr();
433
434    if (!tc->getVirtProxy().tryReadString(path, p->getSyscallArg(tc, index)))
435        return -EFAULT;
436
437    // Adjust path for cwd and redirection
438    path = p->checkPathRedirect(path);
439
440    Addr buf_ptr = p->getSyscallArg(tc, index);
441    size_t bufsiz = p->getSyscallArg(tc, index);
442
443    BufferArg buf(buf_ptr, bufsiz);
444
445    int result = -1;
446    if (path != "/proc/self/exe") {
447        result = readlink(path.c_str(), (char *)buf.bufferPtr(), bufsiz);
448    } else {
449        // Emulate readlink() called on '/proc/self/exe' should return the
450        // absolute path of the binary running in the simulated system (the
451        // Process' executable). It is possible that using this path in
452        // the simulated system will result in unexpected behavior if:
453        //  1) One binary runs another (e.g., -c time -o "my_binary"), and
454        //     called binary calls readlink().
455        //  2) The host's full path to the running benchmark changes from one
456        //     simulation to another. This can result in different simulated
457        //     performance since the simulated system will process the binary
458        //     path differently, even if the binary itself does not change.
459
460        // Get the absolute canonical path to the running application
461        char real_path[PATH_MAX];
462        char *check_real_path = realpath(p->progName(), real_path);
463        if (!check_real_path) {
464            fatal("readlink('/proc/self/exe') unable to resolve path to "
465                  "executable: %s", p->progName());
466        }
467        strncpy((char*)buf.bufferPtr(), real_path, bufsiz);
468        size_t real_path_len = strlen(real_path);
469        if (real_path_len > bufsiz) {
470            // readlink will truncate the contents of the
471            // path to ensure it is no more than bufsiz
472            result = bufsiz;
473        } else {
474            result = real_path_len;
475        }
476
477        // Issue a warning about potential unexpected results
478        warn_once("readlink() called on '/proc/self/exe' may yield unexpected "
479                  "results in various settings.\n      Returning '%s'\n",
480                  (char*)buf.bufferPtr());
481    }
482
483    buf.copyOut(tc->getVirtProxy());
484
485    return (result == -1) ? -errno : result;
486}
487
488SyscallReturn
489unlinkFunc(SyscallDesc *desc, int num, ThreadContext *tc)
490{
491    return unlinkHelper(desc, num, tc, 0);
492}
493
494SyscallReturn
495unlinkHelper(SyscallDesc *desc, int num, ThreadContext *tc, int index)
496{
497    string path;
498    auto p = tc->getProcessPtr();
499
500    if (!tc->getVirtProxy().tryReadString(path, p->getSyscallArg(tc, index)))
501        return -EFAULT;
502
503    path = p->checkPathRedirect(path);
504
505    int result = unlink(path.c_str());
506    return (result == -1) ? -errno : result;
507}
508
509SyscallReturn
510linkFunc(SyscallDesc *desc, int num, ThreadContext *tc)
511{
512    string path;
513    string new_path;
514    auto p = tc->getProcessPtr();
515
516    int index = 0;
517    auto &virt_mem = tc->getVirtProxy();
518    if (!virt_mem.tryReadString(path, p->getSyscallArg(tc, index)))
519        return -EFAULT;
520    if (!virt_mem.tryReadString(new_path, p->getSyscallArg(tc, index)))
521        return -EFAULT;
522
523    path = p->absolutePath(path, true);
524    new_path = p->absolutePath(new_path, true);
525
526    int result = link(path.c_str(), new_path.c_str());
527    return (result == -1) ? -errno : result;
528}
529
530SyscallReturn
531symlinkFunc(SyscallDesc *desc, int num, ThreadContext *tc)
532{
533    string path;
534    string new_path;
535    auto p = tc->getProcessPtr();
536
537    int index = 0;
538    auto &virt_mem = tc->getVirtProxy();
539    if (!virt_mem.tryReadString(path, p->getSyscallArg(tc, index)))
540        return -EFAULT;
541    if (!virt_mem.tryReadString(new_path, p->getSyscallArg(tc, index)))
542        return -EFAULT;
543
544    path = p->absolutePath(path, true);
545    new_path = p->absolutePath(new_path, true);
546
547    int result = symlink(path.c_str(), new_path.c_str());
548    return (result == -1) ? -errno : result;
549}
550
551SyscallReturn
552mkdirFunc(SyscallDesc *desc, int num, ThreadContext *tc)
553{
554    auto p = tc->getProcessPtr();
555    int index = 0;
556    std::string path;
557    if (!tc->getVirtProxy().tryReadString(path, p->getSyscallArg(tc, index)))
558        return -EFAULT;
559
560    path = p->checkPathRedirect(path);
561    mode_t mode = p->getSyscallArg(tc, index);
562
563    auto result = mkdir(path.c_str(), mode);
564    return (result == -1) ? -errno : result;
565}
566
567SyscallReturn
568renameFunc(SyscallDesc *desc, int num, ThreadContext *tc)
569{
570    string old_name;
571    auto p = tc->getProcessPtr();
572
573    int index = 0;
574    if (!tc->getVirtProxy().tryReadString(
575                old_name, p->getSyscallArg(tc, index))) {
576        return -EFAULT;
577    }
578
579    string new_name;
580
581    if (!tc->getVirtProxy().tryReadString(
582                new_name, p->getSyscallArg(tc, index))) {
583        return -EFAULT;
584    }
585
586    // Adjust path for cwd and redirection
587    old_name = p->checkPathRedirect(old_name);
588    new_name = p->checkPathRedirect(new_name);
589
590    int64_t result = rename(old_name.c_str(), new_name.c_str());
591    return (result == -1) ? -errno : result;
592}
593
594SyscallReturn
595truncateFunc(SyscallDesc *desc, int num, ThreadContext *tc)
596{
597    string path;
598    auto p = tc->getProcessPtr();
599
600    int index = 0;
601    if (!tc->getVirtProxy().tryReadString(path, p->getSyscallArg(tc, index)))
602        return -EFAULT;
603
604    off_t length = p->getSyscallArg(tc, index);
605
606    // Adjust path for cwd and redirection
607    path = p->checkPathRedirect(path);
608
609    int result = truncate(path.c_str(), length);
610    return (result == -1) ? -errno : result;
611}
612
613SyscallReturn
614ftruncateFunc(SyscallDesc *desc, int num, ThreadContext *tc)
615{
616    int index = 0;
617    auto p = tc->getProcessPtr();
618    int tgt_fd = p->getSyscallArg(tc, index);
619    off_t length = p->getSyscallArg(tc, index);
620
621    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
622    if (!ffdp)
623        return -EBADF;
624    int sim_fd = ffdp->getSimFD();
625
626    int result = ftruncate(sim_fd, length);
627    return (result == -1) ? -errno : result;
628}
629
630SyscallReturn
631truncate64Func(SyscallDesc *desc, int num, ThreadContext *tc)
632{
633    int index = 0;
634    auto process = tc->getProcessPtr();
635    string path;
636
637    if (!tc->getVirtProxy().tryReadString(
638                path, process->getSyscallArg(tc, index))) {
639        return -EFAULT;
640    }
641
642    int64_t length = process->getSyscallArg(tc, index, 64);
643
644    // Adjust path for cwd and redirection
645    path = process->checkPathRedirect(path);
646
647#if NO_STAT64
648    int result = truncate(path.c_str(), length);
649#else
650    int result = truncate64(path.c_str(), length);
651#endif
652    return (result == -1) ? -errno : result;
653}
654
655SyscallReturn
656ftruncate64Func(SyscallDesc *desc, int num, ThreadContext *tc)
657{
658    int index = 0;
659    auto p = tc->getProcessPtr();
660    int tgt_fd = p->getSyscallArg(tc, index);
661    int64_t length = p->getSyscallArg(tc, index, 64);
662
663    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
664    if (!ffdp)
665        return -EBADF;
666    int sim_fd = ffdp->getSimFD();
667
668#if NO_STAT64
669    int result = ftruncate(sim_fd, length);
670#else
671    int result = ftruncate64(sim_fd, length);
672#endif
673    return (result == -1) ? -errno : result;
674}
675
676SyscallReturn
677umaskFunc(SyscallDesc *desc, int num, ThreadContext *tc)
678{
679    // Letting the simulated program change the simulator's umask seems like
680    // a bad idea.  Compromise by just returning the current umask but not
681    // changing anything.
682    mode_t oldMask = umask(0);
683    umask(oldMask);
684    return (int)oldMask;
685}
686
687SyscallReturn
688chownFunc(SyscallDesc *desc, int num, ThreadContext *tc)
689{
690    string path;
691    auto p = tc->getProcessPtr();
692
693    int index = 0;
694    if (!tc->getVirtProxy().tryReadString(path, p->getSyscallArg(tc, index)))
695        return -EFAULT;
696
697    /* XXX endianess */
698    uint32_t owner = p->getSyscallArg(tc, index);
699    uid_t hostOwner = owner;
700    uint32_t group = p->getSyscallArg(tc, index);
701    gid_t hostGroup = group;
702
703    // Adjust path for cwd and redirection
704    path = p->checkPathRedirect(path);
705
706    int result = chown(path.c_str(), hostOwner, hostGroup);
707    return (result == -1) ? -errno : result;
708}
709
710SyscallReturn
711fchownFunc(SyscallDesc *desc, int num, ThreadContext *tc)
712{
713    int index = 0;
714    auto p = tc->getProcessPtr();
715    int tgt_fd = p->getSyscallArg(tc, index);
716
717    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
718    if (!ffdp)
719        return -EBADF;
720    int sim_fd = ffdp->getSimFD();
721
722    /* XXX endianess */
723    uint32_t owner = p->getSyscallArg(tc, index);
724    uid_t hostOwner = owner;
725    uint32_t group = p->getSyscallArg(tc, index);
726    gid_t hostGroup = group;
727
728    int result = fchown(sim_fd, hostOwner, hostGroup);
729    return (result == -1) ? -errno : result;
730}
731
732/**
733 * FIXME: The file description is not shared among file descriptors created
734 * with dup. Really, it's difficult to maintain fields like file offset or
735 * flags since an update to such a field won't be reflected in the metadata
736 * for the fd entries that we maintain for checkpoint restoration.
737 */
738SyscallReturn
739dupFunc(SyscallDesc *desc, int num, ThreadContext *tc)
740{
741    int index = 0;
742    auto p = tc->getProcessPtr();
743    int tgt_fd = p->getSyscallArg(tc, index);
744
745    auto old_hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
746    if (!old_hbfdp)
747        return -EBADF;
748    int sim_fd = old_hbfdp->getSimFD();
749
750    int result = dup(sim_fd);
751    if (result == -1)
752        return -errno;
753
754    auto new_hbfdp = std::dynamic_pointer_cast<HBFDEntry>(old_hbfdp->clone());
755    new_hbfdp->setSimFD(result);
756    new_hbfdp->setCOE(false);
757    return p->fds->allocFD(new_hbfdp);
758}
759
760SyscallReturn
761dup2Func(SyscallDesc *desc, int num, ThreadContext *tc)
762{
763    int index = 0;
764    auto p = tc->getProcessPtr();
765    int old_tgt_fd = p->getSyscallArg(tc, index);
766    auto old_hbp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[old_tgt_fd]);
767    if (!old_hbp)
768        return -EBADF;
769    int old_sim_fd = old_hbp->getSimFD();
770
771    /**
772     * We need a valid host file descriptor number to be able to pass into
773     * the second parameter for dup2 (newfd), but we don't know what the
774     * viable numbers are; we execute the open call to retrieve one.
775     */
776    int res_fd = dup2(old_sim_fd, open("/dev/null", O_RDONLY));
777    if (res_fd == -1)
778        return -errno;
779
780    int new_tgt_fd = p->getSyscallArg(tc, index);
781    auto new_hbp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[new_tgt_fd]);
782    if (new_hbp)
783        p->fds->closeFDEntry(new_tgt_fd);
784    new_hbp = std::dynamic_pointer_cast<HBFDEntry>(old_hbp->clone());
785    new_hbp->setSimFD(res_fd);
786    new_hbp->setCOE(false);
787
788    return p->fds->allocFD(new_hbp);
789}
790
791SyscallReturn
792fcntlFunc(SyscallDesc *desc, int num, ThreadContext *tc)
793{
794    int arg;
795    int index = 0;
796    auto p = tc->getProcessPtr();
797    int tgt_fd = p->getSyscallArg(tc, index);
798    int cmd = p->getSyscallArg(tc, index);
799
800    auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
801    if (!hbfdp)
802        return -EBADF;
803    int sim_fd = hbfdp->getSimFD();
804
805    int coe = hbfdp->getCOE();
806
807    switch (cmd) {
808      case F_GETFD:
809        return coe & FD_CLOEXEC;
810
811      case F_SETFD: {
812        arg = p->getSyscallArg(tc, index);
813        arg ? hbfdp->setCOE(true) : hbfdp->setCOE(false);
814        return 0;
815      }
816
817      // Rely on the host to maintain the file status flags for this file
818      // description rather than maintain it ourselves. Admittedly, this
819      // is suboptimal (and possibly error prone), but it is difficult to
820      // maintain the flags by tracking them across the different descriptors
821      // (that refer to this file description) caused by clone, dup, and
822      // subsequent fcntls.
823      case F_GETFL:
824      case F_SETFL: {
825        arg = p->getSyscallArg(tc, index);
826        int rv = fcntl(sim_fd, cmd, arg);
827        return (rv == -1) ? -errno : rv;
828      }
829
830      default:
831        warn("fcntl: unsupported command %d\n", cmd);
832        return 0;
833    }
834}
835
836SyscallReturn
837fcntl64Func(SyscallDesc *desc, int num, ThreadContext *tc)
838{
839    int index = 0;
840    auto p = tc->getProcessPtr();
841    int tgt_fd = p->getSyscallArg(tc, index);
842
843    auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
844    if (!hbfdp)
845        return -EBADF;
846    int sim_fd = hbfdp->getSimFD();
847
848    int cmd = p->getSyscallArg(tc, index);
849    switch (cmd) {
850      case 33: //F_GETLK64
851        warn("fcntl64(%d, F_GETLK64) not supported, error returned\n", tgt_fd);
852        return -EMFILE;
853
854      case 34: // F_SETLK64
855      case 35: // F_SETLKW64
856        warn("fcntl64(%d, F_SETLK(W)64) not supported, error returned\n",
857             tgt_fd);
858        return -EMFILE;
859
860      default:
861        // not sure if this is totally valid, but we'll pass it through
862        // to the underlying OS
863        warn("fcntl64(%d, %d) passed through to host\n", tgt_fd, cmd);
864        return fcntl(sim_fd, cmd);
865    }
866}
867
868SyscallReturn
869pipeImpl(SyscallDesc *desc, int callnum, ThreadContext *tc, bool pseudoPipe)
870{
871    int sim_fds[2], tgt_fds[2];
872    auto p = tc->getProcessPtr();
873
874    int pipe_retval = pipe(sim_fds);
875    if (pipe_retval == -1)
876        return -errno;
877
878    auto rend = PipeFDEntry::EndType::read;
879    auto rpfd = std::make_shared<PipeFDEntry>(sim_fds[0], O_WRONLY, rend);
880    tgt_fds[0] = p->fds->allocFD(rpfd);
881
882    auto wend = PipeFDEntry::EndType::write;
883    auto wpfd = std::make_shared<PipeFDEntry>(sim_fds[1], O_RDONLY, wend);
884    tgt_fds[1] = p->fds->allocFD(wpfd);
885
886    /**
887     * Now patch the read object to record the target file descriptor chosen
888     * as the write end of the pipe.
889     */
890    rpfd->setPipeReadSource(tgt_fds[1]);
891
892    /**
893     * Alpha Linux convention for pipe() is that fd[0] is returned as
894     * the return value of the function, and fd[1] is returned in r20.
895     */
896    if (pseudoPipe) {
897        tc->setIntReg(SyscallPseudoReturnReg, tgt_fds[1]);
898        return tgt_fds[0];
899    }
900
901    int index = 0;
902    Addr tgt_addr = p->getSyscallArg(tc, index);
903
904    /**
905     * Copy the target file descriptors into buffer space and then copy
906     * the buffer space back into the target address space.
907     */
908    BufferArg tgt_handle(tgt_addr, sizeof(int[2]));
909    int *buf_ptr = (int*)tgt_handle.bufferPtr();
910    buf_ptr[0] = tgt_fds[0];
911    buf_ptr[1] = tgt_fds[1];
912    tgt_handle.copyOut(tc->getVirtProxy());
913    return 0;
914}
915
916SyscallReturn
917pipePseudoFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
918{
919    return pipeImpl(desc, callnum, tc, true);
920}
921
922SyscallReturn
923pipeFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
924{
925    return pipeImpl(desc, callnum, tc, false);
926}
927
928SyscallReturn
929setpgidFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
930{
931    int index = 0;
932    auto process = tc->getProcessPtr();
933    int pid = process->getSyscallArg(tc, index);
934    int pgid = process->getSyscallArg(tc, index);
935
936    if (pgid < 0)
937        return -EINVAL;
938
939    if (pid == 0) {
940        process->setpgid(process->pid());
941        return 0;
942    }
943
944    Process *matched_ph = nullptr;
945    System *sysh = tc->getSystemPtr();
946
947    // Retrieves process pointer from active/suspended thread contexts.
948    for (int i = 0; i < sysh->numContexts(); i++) {
949        if (sysh->threadContexts[i]->status() != ThreadContext::Halted) {
950            Process *temp_h = sysh->threadContexts[i]->getProcessPtr();
951            Process *walk_ph = (Process*)temp_h;
952
953            if (walk_ph && walk_ph->pid() == process->pid())
954                matched_ph = walk_ph;
955        }
956    }
957
958    assert(matched_ph);
959    matched_ph->setpgid((pgid == 0) ? matched_ph->pid() : pgid);
960
961    return 0;
962}
963
964SyscallReturn
965getpidPseudoFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
966{
967    // Make up a PID.  There's no interprocess communication in
968    // fake_syscall mode, so there's no way for a process to know it's
969    // not getting a unique value.
970
971    auto process = tc->getProcessPtr();
972    tc->setIntReg(SyscallPseudoReturnReg, process->ppid());
973    return process->pid();
974}
975
976
977SyscallReturn
978getuidPseudoFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
979{
980    // Make up a UID and EUID... it shouldn't matter, and we want the
981    // simulation to be deterministic.
982
983    // EUID goes in r20.
984    auto process = tc->getProcessPtr();
985    tc->setIntReg(SyscallPseudoReturnReg, process->euid()); // EUID
986    return process->uid(); // UID
987}
988
989
990SyscallReturn
991getgidPseudoFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
992{
993    // Get current group ID.  EGID goes in r20.
994    auto process = tc->getProcessPtr();
995    tc->setIntReg(SyscallPseudoReturnReg, process->egid()); // EGID
996    return process->gid();
997}
998
999
1000SyscallReturn
1001setuidFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
1002{
1003    // can't fathom why a benchmark would call this.
1004    int index = 0;
1005    auto process = tc->getProcessPtr();
1006    warn("Ignoring call to setuid(%d)\n", process->getSyscallArg(tc, index));
1007    return 0;
1008}
1009
1010SyscallReturn
1011getpidFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
1012{
1013    auto process = tc->getProcessPtr();
1014    return process->tgid();
1015}
1016
1017SyscallReturn
1018gettidFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
1019{
1020    auto process = tc->getProcessPtr();
1021    return process->pid();
1022}
1023
1024SyscallReturn
1025getppidFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
1026{
1027    auto process = tc->getProcessPtr();
1028    return process->ppid();
1029}
1030
1031SyscallReturn
1032getuidFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
1033{
1034    auto process = tc->getProcessPtr();
1035    return process->uid();              // UID
1036}
1037
1038SyscallReturn
1039geteuidFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
1040{
1041    auto process = tc->getProcessPtr();
1042    return process->euid();             // UID
1043}
1044
1045SyscallReturn
1046getgidFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
1047{
1048    auto process = tc->getProcessPtr();
1049    return process->gid();
1050}
1051
1052SyscallReturn
1053getegidFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
1054{
1055    auto process = tc->getProcessPtr();
1056    return process->egid();
1057}
1058
1059SyscallReturn
1060fallocateFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
1061{
1062#if defined(__linux__)
1063    int index = 0;
1064    auto p = tc->getProcessPtr();
1065    int tgt_fd = p->getSyscallArg(tc, index);
1066    int mode = p->getSyscallArg(tc, index);
1067    off_t offset = p->getSyscallArg(tc, index);
1068    off_t len = p->getSyscallArg(tc, index);
1069
1070    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1071    if (!ffdp)
1072        return -EBADF;
1073    int sim_fd = ffdp->getSimFD();
1074
1075    int result = fallocate(sim_fd, mode, offset, len);
1076    if (result < 0)
1077        return -errno;
1078    return 0;
1079#else
1080    warnUnsupportedOS("fallocate");
1081    return -1;
1082#endif
1083}
1084
1085SyscallReturn
1086accessFunc(SyscallDesc *desc, int callnum, ThreadContext *tc, int index)
1087{
1088    string path;
1089    auto p = tc->getProcessPtr();
1090    if (!tc->getVirtProxy().tryReadString(path, p->getSyscallArg(tc, index)))
1091        return -EFAULT;
1092
1093    // Adjust path for cwd and redirection
1094    path = p->checkPathRedirect(path);
1095
1096    mode_t mode = p->getSyscallArg(tc, index);
1097
1098    int result = access(path.c_str(), mode);
1099    return (result == -1) ? -errno : result;
1100}
1101
1102SyscallReturn
1103accessFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
1104{
1105    return accessFunc(desc, callnum, tc, 0);
1106}
1107
1108SyscallReturn
1109mknodFunc(SyscallDesc *desc, int num, ThreadContext *tc)
1110{
1111    auto p = tc->getProcessPtr();
1112    int index = 0;
1113    std::string path;
1114    if (!tc->getVirtProxy().tryReadString(path, p->getSyscallArg(tc, index)))
1115        return -EFAULT;
1116
1117    path = p->checkPathRedirect(path);
1118    mode_t mode = p->getSyscallArg(tc, index);
1119    dev_t dev = p->getSyscallArg(tc, index);
1120
1121    auto result = mknod(path.c_str(), mode, dev);
1122    return (result == -1) ? -errno : result;
1123}
1124
1125SyscallReturn
1126chdirFunc(SyscallDesc *desc, int num, ThreadContext *tc)
1127{
1128    auto p = tc->getProcessPtr();
1129    int index = 0;
1130    std::string path;
1131    if (!tc->getVirtProxy().tryReadString(path, p->getSyscallArg(tc, index)))
1132        return -EFAULT;
1133
1134    std::string tgt_cwd;
1135    if (startswith(path, "/")) {
1136        tgt_cwd = path;
1137    } else {
1138        char buf[PATH_MAX];
1139        tgt_cwd = realpath((p->tgtCwd + "/" + path).c_str(), buf);
1140    }
1141    std::string host_cwd = p->checkPathRedirect(tgt_cwd);
1142
1143    int result = chdir(host_cwd.c_str());
1144
1145    if (result == -1)
1146        return -errno;
1147
1148    p->hostCwd = host_cwd;
1149    p->tgtCwd = tgt_cwd;
1150    return result;
1151}
1152
1153SyscallReturn
1154rmdirFunc(SyscallDesc *desc, int num, ThreadContext *tc)
1155{
1156    auto p = tc->getProcessPtr();
1157    int index = 0;
1158    std::string path;
1159    if (!tc->getVirtProxy().tryReadString(path, p->getSyscallArg(tc, index)))
1160        return -EFAULT;
1161
1162    path = p->checkPathRedirect(path);
1163
1164    auto result = rmdir(path.c_str());
1165    return (result == -1) ? -errno : result;
1166}
1167
1168#if defined(SYS_getdents) || defined(SYS_getdents64)
1169template<typename DE, int SYS_NUM>
1170static SyscallReturn
1171getdentsImpl(SyscallDesc *desc, int callnum, ThreadContext *tc)
1172{
1173    int index = 0;
1174    auto p = tc->getProcessPtr();
1175    int tgt_fd = p->getSyscallArg(tc, index);
1176    Addr buf_ptr = p->getSyscallArg(tc, index);
1177    unsigned count = p->getSyscallArg(tc, index);
1178
1179    auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
1180    if (!hbfdp)
1181        return -EBADF;
1182    int sim_fd = hbfdp->getSimFD();
1183
1184    BufferArg buf_arg(buf_ptr, count);
1185    auto status = syscall(SYS_NUM, sim_fd, buf_arg.bufferPtr(), count);
1186
1187    if (status == -1)
1188        return -errno;
1189
1190    unsigned traversed = 0;
1191    while (traversed < status) {
1192        DE *buffer = (DE*)((Addr)buf_arg.bufferPtr() + traversed);
1193
1194        auto host_reclen = buffer->d_reclen;
1195
1196        /**
1197         * Convert the byte ordering from the host to the target before
1198         * passing the data back into the target's address space to preserve
1199         * endianness.
1200         */
1201        buffer->d_ino = htog(buffer->d_ino);
1202        buffer->d_off = htog(buffer->d_off);
1203        buffer->d_reclen = htog(buffer->d_reclen);
1204
1205        traversed += host_reclen;
1206    }
1207
1208    buf_arg.copyOut(tc->getVirtProxy());
1209    return status;
1210}
1211#endif
1212
1213#if defined(SYS_getdents)
1214SyscallReturn
1215getdentsFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
1216{
1217    typedef struct linux_dirent {
1218        unsigned long d_ino;
1219        unsigned long d_off;
1220        unsigned short d_reclen;
1221        char dname[];
1222    } LinDent;
1223
1224    return getdentsImpl<LinDent, SYS_getdents>(desc, callnum, tc);
1225}
1226#endif
1227
1228#if defined(SYS_getdents64)
1229SyscallReturn
1230getdents64Func(SyscallDesc *desc, int callnum, ThreadContext *tc)
1231{
1232    typedef struct linux_dirent64 {
1233        ino64_t d_ino;
1234        off64_t d_off;
1235        unsigned short d_reclen;
1236        char dname[];
1237    } LinDent64;
1238
1239    return getdentsImpl<LinDent64, SYS_getdents64>(desc, callnum, tc);
1240}
1241#endif
1242
1243SyscallReturn
1244shutdownFunc(SyscallDesc *desc, int num, ThreadContext *tc)
1245{
1246    int index = 0;
1247    auto p = tc->getProcessPtr();
1248    int tgt_fd = p->getSyscallArg(tc, index);
1249    int how = p->getSyscallArg(tc, index);
1250
1251    auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
1252    if (!sfdp)
1253        return -EBADF;
1254    int sim_fd = sfdp->getSimFD();
1255
1256    int retval = shutdown(sim_fd, how);
1257
1258    return (retval == -1) ? -errno : retval;
1259}
1260
1261SyscallReturn
1262bindFunc(SyscallDesc *desc, int num, ThreadContext *tc)
1263{
1264    int index = 0;
1265    auto p = tc->getProcessPtr();
1266    int tgt_fd = p->getSyscallArg(tc, index);
1267    Addr buf_ptr = p->getSyscallArg(tc, index);
1268    int addrlen = p->getSyscallArg(tc, index);
1269
1270    BufferArg bufSock(buf_ptr, addrlen);
1271    bufSock.copyIn(tc->getVirtProxy());
1272
1273    auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
1274    if (!sfdp)
1275        return -EBADF;
1276    int sim_fd = sfdp->getSimFD();
1277
1278    int status = ::bind(sim_fd,
1279                        (struct sockaddr *)bufSock.bufferPtr(),
1280                        addrlen);
1281
1282    return (status == -1) ? -errno : status;
1283}
1284
1285SyscallReturn
1286listenFunc(SyscallDesc *desc, int num, ThreadContext *tc)
1287{
1288    int index = 0;
1289    auto p = tc->getProcessPtr();
1290    int tgt_fd = p->getSyscallArg(tc, index);
1291    int backlog = p->getSyscallArg(tc, index);
1292
1293    auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
1294    if (!sfdp)
1295        return -EBADF;
1296    int sim_fd = sfdp->getSimFD();
1297
1298    int status = listen(sim_fd, backlog);
1299
1300    return (status == -1) ? -errno : status;
1301}
1302
1303SyscallReturn
1304connectFunc(SyscallDesc *desc, int num, ThreadContext *tc)
1305{
1306    int index = 0;
1307    auto p = tc->getProcessPtr();
1308    int tgt_fd = p->getSyscallArg(tc, index);
1309    Addr buf_ptr = p->getSyscallArg(tc, index);
1310    int addrlen = p->getSyscallArg(tc, index);
1311
1312    BufferArg addr(buf_ptr, addrlen);
1313    addr.copyIn(tc->getVirtProxy());
1314
1315    auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
1316    if (!sfdp)
1317        return -EBADF;
1318    int sim_fd = sfdp->getSimFD();
1319
1320    int status = connect(sim_fd,
1321                         (struct sockaddr *)addr.bufferPtr(),
1322                         (socklen_t)addrlen);
1323
1324    return (status == -1) ? -errno : status;
1325}
1326
1327SyscallReturn
1328recvfromFunc(SyscallDesc *desc, int num, ThreadContext *tc)
1329{
1330    int index = 0;
1331    auto p = tc->getProcessPtr();
1332    int tgt_fd = p->getSyscallArg(tc, index);
1333    Addr bufrPtr = p->getSyscallArg(tc, index);
1334    size_t bufrLen = p->getSyscallArg(tc, index);
1335    int flags = p->getSyscallArg(tc, index);
1336    Addr addrPtr = p->getSyscallArg(tc, index);
1337    Addr addrlenPtr = p->getSyscallArg(tc, index);
1338
1339    auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
1340    if (!sfdp)
1341        return -EBADF;
1342    int sim_fd = sfdp->getSimFD();
1343
1344    // Reserve buffer space.
1345    BufferArg bufrBuf(bufrPtr, bufrLen);
1346
1347    // Get address length.
1348    socklen_t addrLen = 0;
1349    if (addrlenPtr != 0) {
1350        // Read address length parameter.
1351        BufferArg addrlenBuf(addrlenPtr, sizeof(socklen_t));
1352        addrlenBuf.copyIn(tc->getVirtProxy());
1353        addrLen = *((socklen_t *)addrlenBuf.bufferPtr());
1354    }
1355
1356    struct sockaddr sa, *sap = NULL;
1357    if (addrLen != 0) {
1358        BufferArg addrBuf(addrPtr, addrLen);
1359        addrBuf.copyIn(tc->getVirtProxy());
1360        memcpy(&sa, (struct sockaddr *)addrBuf.bufferPtr(),
1361               sizeof(struct sockaddr));
1362        sap = &sa;
1363    }
1364
1365    ssize_t recvd_size = recvfrom(sim_fd,
1366                                  (void *)bufrBuf.bufferPtr(),
1367                                  bufrLen, flags, sap, (socklen_t *)&addrLen);
1368
1369    if (recvd_size == -1)
1370        return -errno;
1371
1372    // Pass the received data out.
1373    bufrBuf.copyOut(tc->getVirtProxy());
1374
1375    // Copy address to addrPtr and pass it on.
1376    if (sap != NULL) {
1377        BufferArg addrBuf(addrPtr, addrLen);
1378        memcpy(addrBuf.bufferPtr(), sap, sizeof(sa));
1379        addrBuf.copyOut(tc->getVirtProxy());
1380    }
1381
1382    // Copy len to addrlenPtr and pass it on.
1383    if (addrLen != 0) {
1384        BufferArg addrlenBuf(addrlenPtr, sizeof(socklen_t));
1385        *(socklen_t *)addrlenBuf.bufferPtr() = addrLen;
1386        addrlenBuf.copyOut(tc->getVirtProxy());
1387    }
1388
1389    return recvd_size;
1390}
1391
1392SyscallReturn
1393sendtoFunc(SyscallDesc *desc, int num, ThreadContext *tc)
1394{
1395    int index = 0;
1396    auto p = tc->getProcessPtr();
1397    int tgt_fd = p->getSyscallArg(tc, index);
1398    Addr bufrPtr = p->getSyscallArg(tc, index);
1399    size_t bufrLen = p->getSyscallArg(tc, index);
1400    int flags = p->getSyscallArg(tc, index);
1401    Addr addrPtr = p->getSyscallArg(tc, index);
1402    socklen_t addrLen = p->getSyscallArg(tc, index);
1403
1404    auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
1405    if (!sfdp)
1406        return -EBADF;
1407    int sim_fd = sfdp->getSimFD();
1408
1409    // Reserve buffer space.
1410    BufferArg bufrBuf(bufrPtr, bufrLen);
1411    bufrBuf.copyIn(tc->getVirtProxy());
1412
1413    struct sockaddr sa, *sap = nullptr;
1414    memset(&sa, 0, sizeof(sockaddr));
1415    if (addrLen != 0) {
1416        BufferArg addrBuf(addrPtr, addrLen);
1417        addrBuf.copyIn(tc->getVirtProxy());
1418        memcpy(&sa, (sockaddr*)addrBuf.bufferPtr(), addrLen);
1419        sap = &sa;
1420    }
1421
1422    ssize_t sent_size = sendto(sim_fd,
1423                               (void *)bufrBuf.bufferPtr(),
1424                               bufrLen, flags, sap, (socklen_t)addrLen);
1425
1426    return (sent_size == -1) ? -errno : sent_size;
1427}
1428
1429SyscallReturn
1430recvmsgFunc(SyscallDesc *desc, int num, ThreadContext *tc)
1431{
1432    int index = 0;
1433    auto p = tc->getProcessPtr();
1434    int tgt_fd = p->getSyscallArg(tc, index);
1435    Addr msgPtr = p->getSyscallArg(tc, index);
1436    int flags = p->getSyscallArg(tc, index);
1437
1438    auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
1439    if (!sfdp)
1440        return -EBADF;
1441    int sim_fd = sfdp->getSimFD();
1442
1443     /**
1444      *  struct msghdr {
1445      *     void         *msg_name;       // optional address
1446      *    socklen_t     msg_namelen;    // size of address
1447      *    struct iovec *msg_iov;        // iovec array
1448      *    size_t        msg_iovlen;     // number entries in msg_iov
1449      *    i                             // entries correspond to buffer
1450      *    void         *msg_control;    // ancillary data
1451      *    size_t        msg_controllen; // ancillary data buffer len
1452      *    int           msg_flags;      // flags on received message
1453      *  };
1454      *
1455      *  struct iovec {
1456      *    void  *iov_base;              // starting address
1457      *    size_t iov_len;               // number of bytes to transfer
1458      *  };
1459      */
1460
1461    /**
1462     * The plan with this system call is to replace all of the pointers in the
1463     * structure and the substructure with BufferArg class pointers. We will
1464     * copy every field from the structures into our BufferArg classes.
1465     */
1466    BufferArg msgBuf(msgPtr, sizeof(struct msghdr));
1467    msgBuf.copyIn(tc->getVirtProxy());
1468    struct msghdr *msgHdr = (struct msghdr *)msgBuf.bufferPtr();
1469
1470    /**
1471     * We will use these address place holders to retain the pointers which
1472     * we are going to replace with our own buffers in our simulator address
1473     * space.
1474     */
1475    Addr msg_name_phold = 0;
1476    Addr msg_iov_phold = 0;
1477    Addr iovec_base_phold[msgHdr->msg_iovlen];
1478    Addr msg_control_phold = 0;
1479
1480    /**
1481     * Record msg_name pointer then replace with buffer pointer.
1482     */
1483    BufferArg *nameBuf = NULL;
1484    if (msgHdr->msg_name) {
1485        /*1*/msg_name_phold = (Addr)msgHdr->msg_name;
1486        /*2*/nameBuf = new BufferArg(msg_name_phold, msgHdr->msg_namelen);
1487        /*3*/nameBuf->copyIn(tc->getVirtProxy());
1488        /*4*/msgHdr->msg_name = nameBuf->bufferPtr();
1489    }
1490
1491    /**
1492     * Record msg_iov pointer then replace with buffer pointer. Also, setup
1493     * an array of buffer pointers for the iovec structs record and replace
1494     * their pointers with buffer pointers.
1495     */
1496    BufferArg *iovBuf = NULL;
1497    BufferArg *iovecBuf[msgHdr->msg_iovlen];
1498    for (int i = 0; i < msgHdr->msg_iovlen; i++) {
1499        iovec_base_phold[i] = 0;
1500        iovecBuf[i] = NULL;
1501    }
1502
1503    if (msgHdr->msg_iov) {
1504        /*1*/msg_iov_phold = (Addr)msgHdr->msg_iov;
1505        /*2*/iovBuf = new BufferArg(msg_iov_phold, msgHdr->msg_iovlen *
1506                                    sizeof(struct iovec));
1507        /*3*/iovBuf->copyIn(tc->getVirtProxy());
1508        for (int i = 0; i < msgHdr->msg_iovlen; i++) {
1509            if (((struct iovec *)iovBuf->bufferPtr())[i].iov_base) {
1510                /*1*/iovec_base_phold[i] =
1511                     (Addr)((struct iovec *)iovBuf->bufferPtr())[i].iov_base;
1512                /*2*/iovecBuf[i] = new BufferArg(iovec_base_phold[i],
1513                     ((struct iovec *)iovBuf->bufferPtr())[i].iov_len);
1514                /*3*/iovecBuf[i]->copyIn(tc->getVirtProxy());
1515                /*4*/((struct iovec *)iovBuf->bufferPtr())[i].iov_base =
1516                     iovecBuf[i]->bufferPtr();
1517            }
1518        }
1519        /*4*/msgHdr->msg_iov = (struct iovec *)iovBuf->bufferPtr();
1520    }
1521
1522    /**
1523     * Record msg_control pointer then replace with buffer pointer.
1524     */
1525    BufferArg *controlBuf = NULL;
1526    if (msgHdr->msg_control) {
1527        /*1*/msg_control_phold = (Addr)msgHdr->msg_control;
1528        /*2*/controlBuf = new BufferArg(msg_control_phold,
1529                                        CMSG_ALIGN(msgHdr->msg_controllen));
1530        /*3*/controlBuf->copyIn(tc->getVirtProxy());
1531        /*4*/msgHdr->msg_control = controlBuf->bufferPtr();
1532    }
1533
1534    ssize_t recvd_size = recvmsg(sim_fd, msgHdr, flags);
1535
1536    if (recvd_size < 0)
1537        return -errno;
1538
1539    if (msgHdr->msg_name) {
1540        nameBuf->copyOut(tc->getVirtProxy());
1541        delete(nameBuf);
1542        msgHdr->msg_name = (void *)msg_name_phold;
1543    }
1544
1545    if (msgHdr->msg_iov) {
1546        for (int i = 0; i< msgHdr->msg_iovlen; i++) {
1547            if (((struct iovec *)iovBuf->bufferPtr())[i].iov_base) {
1548                iovecBuf[i]->copyOut(tc->getVirtProxy());
1549                delete iovecBuf[i];
1550                ((struct iovec *)iovBuf->bufferPtr())[i].iov_base =
1551                (void *)iovec_base_phold[i];
1552            }
1553        }
1554        iovBuf->copyOut(tc->getVirtProxy());
1555        delete iovBuf;
1556        msgHdr->msg_iov = (struct iovec *)msg_iov_phold;
1557    }
1558
1559    if (msgHdr->msg_control) {
1560        controlBuf->copyOut(tc->getVirtProxy());
1561        delete(controlBuf);
1562        msgHdr->msg_control = (void *)msg_control_phold;
1563    }
1564
1565    msgBuf.copyOut(tc->getVirtProxy());
1566
1567    return recvd_size;
1568}
1569
1570SyscallReturn
1571sendmsgFunc(SyscallDesc *desc, int num, ThreadContext *tc)
1572{
1573    int index = 0;
1574    auto p = tc->getProcessPtr();
1575    int tgt_fd = p->getSyscallArg(tc, index);
1576    Addr msgPtr = p->getSyscallArg(tc, index);
1577    int flags = p->getSyscallArg(tc, index);
1578
1579    auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
1580    if (!sfdp)
1581        return -EBADF;
1582    int sim_fd = sfdp->getSimFD();
1583
1584    /**
1585     * Reserve buffer space.
1586     */
1587    BufferArg msgBuf(msgPtr, sizeof(struct msghdr));
1588    msgBuf.copyIn(tc->getVirtProxy());
1589    struct msghdr msgHdr = *((struct msghdr *)msgBuf.bufferPtr());
1590
1591    /**
1592     * Assuming msgHdr.msg_iovlen >= 1, then there is no point calling
1593     * recvmsg without a buffer.
1594     */
1595    struct iovec *iovPtr = msgHdr.msg_iov;
1596    BufferArg iovBuf((Addr)iovPtr, sizeof(struct iovec) * msgHdr.msg_iovlen);
1597    iovBuf.copyIn(tc->getVirtProxy());
1598    struct iovec *iov = (struct iovec *)iovBuf.bufferPtr();
1599    msgHdr.msg_iov = iov;
1600
1601    /**
1602     * Cannot instantiate buffers till inside the loop.
1603     * Create array to hold buffer addresses, to be used during copyIn of
1604     * send data.
1605     */
1606    BufferArg **bufferArray = (BufferArg **)malloc(msgHdr.msg_iovlen
1607                                                   * sizeof(BufferArg *));
1608
1609    /**
1610     * Iterate through the iovec structures:
1611     * Get the base buffer addreses, reserve iov_len amount of space for each.
1612     * Put the buf address into the bufferArray for later retrieval.
1613     */
1614    for (int iovIndex = 0 ; iovIndex < msgHdr.msg_iovlen; iovIndex++) {
1615        Addr basePtr = (Addr) iov[iovIndex].iov_base;
1616        bufferArray[iovIndex] = new BufferArg(basePtr, iov[iovIndex].iov_len);
1617        bufferArray[iovIndex]->copyIn(tc->getVirtProxy());
1618        iov[iovIndex].iov_base = bufferArray[iovIndex]->bufferPtr();
1619    }
1620
1621    ssize_t sent_size = sendmsg(sim_fd, &msgHdr, flags);
1622    int local_errno = errno;
1623
1624    /**
1625     * Free dynamically allocated memory.
1626     */
1627    for (int iovIndex = 0 ; iovIndex < msgHdr.msg_iovlen; iovIndex++) {
1628        BufferArg *baseBuf = ( BufferArg *)bufferArray[iovIndex];
1629        delete(baseBuf);
1630    }
1631
1632    /**
1633     * Malloced above.
1634     */
1635    free(bufferArray);
1636
1637    return (sent_size < 0) ? -local_errno : sent_size;
1638}
1639
1640SyscallReturn
1641getsockoptFunc(SyscallDesc *desc, int num, ThreadContext *tc)
1642{
1643    // union of all possible return value types from getsockopt
1644    union val {
1645        int i_val;
1646        long l_val;
1647        struct linger linger_val;
1648        struct timeval timeval_val;
1649    } val;
1650
1651    int index = 0;
1652    auto p = tc->getProcessPtr();
1653    int tgt_fd = p->getSyscallArg(tc, index);
1654    int level = p->getSyscallArg(tc, index);
1655    int optname = p->getSyscallArg(tc, index);
1656    Addr valPtr = p->getSyscallArg(tc, index);
1657    Addr lenPtr = p->getSyscallArg(tc, index);
1658
1659    auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
1660    if (!sfdp)
1661        return -EBADF;
1662    int sim_fd = sfdp->getSimFD();
1663
1664    socklen_t len = sizeof(val);
1665    int status = getsockopt(sim_fd, level, optname, &val, &len);
1666
1667    if (status == -1)
1668        return -errno;
1669
1670    // copy val to valPtr and pass it on
1671    BufferArg valBuf(valPtr, sizeof(val));
1672    memcpy(valBuf.bufferPtr(), &val, sizeof(val));
1673    valBuf.copyOut(tc->getVirtProxy());
1674
1675    // copy len to lenPtr and pass  it on
1676    BufferArg lenBuf(lenPtr, sizeof(len));
1677    memcpy(lenBuf.bufferPtr(), &len, sizeof(len));
1678    lenBuf.copyOut(tc->getVirtProxy());
1679
1680    return status;
1681}
1682
1683SyscallReturn
1684getsocknameFunc(SyscallDesc *desc, int num, ThreadContext *tc)
1685{
1686    int index = 0;
1687    auto p = tc->getProcessPtr();
1688    int tgt_fd = p->getSyscallArg(tc, index);
1689    Addr addrPtr = p->getSyscallArg(tc, index);
1690    Addr lenPtr = p->getSyscallArg(tc, index);
1691
1692    auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
1693    if (!sfdp)
1694        return -EBADF;
1695    int sim_fd = sfdp->getSimFD();
1696
1697    // lenPtr is an in-out paramenter:
1698    // sending the address length in, conveying the final length out
1699
1700    // Read in the value of len from the passed pointer.
1701    BufferArg lenBuf(lenPtr, sizeof(socklen_t));
1702    lenBuf.copyIn(tc->getVirtProxy());
1703    socklen_t len = *(socklen_t *)lenBuf.bufferPtr();
1704
1705    struct sockaddr sa;
1706    int status = getsockname(sim_fd, &sa, &len);
1707
1708    if (status == -1)
1709        return -errno;
1710
1711    // Copy address to addrPtr and pass it on.
1712    BufferArg addrBuf(addrPtr, sizeof(sa));
1713    memcpy(addrBuf.bufferPtr(), &sa, sizeof(sa));
1714    addrBuf.copyOut(tc->getVirtProxy());
1715
1716    // Copy len to lenPtr and pass  it on.
1717    *(socklen_t *)lenBuf.bufferPtr() = len;
1718    lenBuf.copyOut(tc->getVirtProxy());
1719
1720    return status;
1721}
1722
1723SyscallReturn
1724getpeernameFunc(SyscallDesc *desc, int num, ThreadContext *tc)
1725{
1726    int index = 0;
1727    auto p = tc->getProcessPtr();
1728    int tgt_fd = p->getSyscallArg(tc, index);
1729    Addr sockAddrPtr = p->getSyscallArg(tc, index);
1730    Addr addrlenPtr = p->getSyscallArg(tc, index);
1731
1732    auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
1733    if (!sfdp)
1734        return -EBADF;
1735    int sim_fd = sfdp->getSimFD();
1736
1737    BufferArg bufAddrlen(addrlenPtr, sizeof(unsigned));
1738    bufAddrlen.copyIn(tc->getVirtProxy());
1739    BufferArg bufSock(sockAddrPtr, *(unsigned *)bufAddrlen.bufferPtr());
1740
1741    int retval = getpeername(sim_fd,
1742                             (struct sockaddr *)bufSock.bufferPtr(),
1743                             (unsigned *)bufAddrlen.bufferPtr());
1744
1745    if (retval != -1) {
1746        bufSock.copyOut(tc->getVirtProxy());
1747        bufAddrlen.copyOut(tc->getVirtProxy());
1748    }
1749
1750    return (retval == -1) ? -errno : retval;
1751}
1752
1753SyscallReturn
1754setsockoptFunc(SyscallDesc *desc, int num, ThreadContext *tc)
1755{
1756    int index = 0;
1757    auto p = tc->getProcessPtr();
1758    int tgt_fd = p->getSyscallArg(tc, index);
1759    int level = p->getSyscallArg(tc, index);
1760    int optname = p->getSyscallArg(tc, index);
1761    Addr valPtr = p->getSyscallArg(tc, index);
1762    socklen_t len = p->getSyscallArg(tc, index);
1763
1764    BufferArg valBuf(valPtr, len);
1765    valBuf.copyIn(tc->getVirtProxy());
1766
1767    auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
1768    if (!sfdp)
1769        return -EBADF;
1770    int sim_fd = sfdp->getSimFD();
1771
1772    int status = setsockopt(sim_fd, level, optname,
1773                            (struct sockaddr *)valBuf.bufferPtr(), len);
1774
1775    return (status == -1) ? -errno : status;
1776}
1777
1778