process.cc revision 11911:fecd8de0ec8e
1/*
2 * Copyright (c) 2014-2016 Advanced Micro Devices, Inc.
3 * Copyright (c) 2012 ARM Limited
4 * All rights reserved
5 *
6 * The license below extends only to copyright in the software and shall
7 * not be construed as granting a license to any other intellectual
8 * property including but not limited to intellectual property relating
9 * to a hardware implementation of the functionality of the software
10 * licensed hereunder.  You may use the software subject to the license
11 * terms below provided that you ensure that this notice is replicated
12 * unmodified and in its entirety in all distributions of the software,
13 * modified or unmodified, in source code or in binary form.
14 *
15 * Copyright (c) 2001-2005 The Regents of The University of Michigan
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * Authors: Nathan Binkert
42 *          Steve Reinhardt
43 *          Ali Saidi
44 *          Brandon Potter
45 */
46
47#include "sim/process.hh"
48
49#include <fcntl.h>
50#include <unistd.h>
51
52#include <array>
53#include <csignal>
54#include <map>
55#include <string>
56#include <vector>
57
58#include "base/intmath.hh"
59#include "base/loader/object_file.hh"
60#include "base/loader/symtab.hh"
61#include "base/statistics.hh"
62#include "config/the_isa.hh"
63#include "cpu/thread_context.hh"
64#include "mem/page_table.hh"
65#include "mem/se_translating_port_proxy.hh"
66#include "params/Process.hh"
67#include "sim/emul_driver.hh"
68#include "sim/fd_array.hh"
69#include "sim/fd_entry.hh"
70#include "sim/syscall_desc.hh"
71#include "sim/system.hh"
72
73#if THE_ISA == ALPHA_ISA
74#include "arch/alpha/linux/process.hh"
75
76#elif THE_ISA == SPARC_ISA
77#include "arch/sparc/linux/process.hh"
78#include "arch/sparc/solaris/process.hh"
79
80#elif THE_ISA == MIPS_ISA
81#include "arch/mips/linux/process.hh"
82
83#elif THE_ISA == ARM_ISA
84#include "arch/arm/freebsd/process.hh"
85#include "arch/arm/linux/process.hh"
86
87#elif THE_ISA == X86_ISA
88#include "arch/x86/linux/process.hh"
89
90#elif THE_ISA == POWER_ISA
91#include "arch/power/linux/process.hh"
92
93#elif THE_ISA == RISCV_ISA
94#include "arch/riscv/linux/process.hh"
95
96#else
97#error "THE_ISA not set"
98#endif
99
100
101using namespace std;
102using namespace TheISA;
103
104Process::Process(ProcessParams * params, ObjectFile * obj_file)
105    : SimObject(params), system(params->system),
106      useArchPT(params->useArchPT),
107      kvmInSE(params->kvmInSE),
108      pTable(useArchPT ?
109        static_cast<PageTableBase *>(new ArchPageTable(name(), params->pid,
110            system)) :
111        static_cast<PageTableBase *>(new FuncPageTable(name(), params->pid))),
112      initVirtMem(system->getSystemPort(), this,
113                  SETranslatingPortProxy::Always),
114      objFile(obj_file),
115      argv(params->cmd), envp(params->env), cwd(params->cwd),
116      executable(params->executable),
117      _uid(params->uid), _euid(params->euid),
118      _gid(params->gid), _egid(params->egid),
119      _pid(params->pid), _ppid(params->ppid),
120      _pgid(params->pgid), drivers(params->drivers),
121      fds(make_shared<FDArray>(params->input, params->output, params->errout)),
122      childClearTID(0)
123{
124    if (_pid >= System::maxPID)
125        fatal("_pid is too large: %d", _pid);
126
127    auto ret_pair = system->PIDs.emplace(_pid);
128    if (!ret_pair.second)
129        fatal("_pid %d is already used", _pid);
130
131    /**
132     * Linux bundles together processes into this concept called a thread
133     * group. The thread group is responsible for recording which processes
134     * behave as threads within a process context. The thread group leader
135     * is the process who's tgid is equal to its pid. Other processes which
136     * belong to the thread group, but do not lead the thread group, are
137     * treated as child threads. These threads are created by the clone system
138     * call with options specified to create threads (differing from the
139     * options used to implement a fork). By default, set up the tgid/pid
140     * with a new, equivalent value. If CLONE_THREAD is specified, patch
141     * the tgid value with the old process' value.
142     */
143    _tgid = params->pid;
144
145    exitGroup = new bool();
146    sigchld = new bool();
147
148    if (!debugSymbolTable) {
149        debugSymbolTable = new SymbolTable();
150        if (!objFile->loadGlobalSymbols(debugSymbolTable) ||
151            !objFile->loadLocalSymbols(debugSymbolTable) ||
152            !objFile->loadWeakSymbols(debugSymbolTable)) {
153            delete debugSymbolTable;
154            debugSymbolTable = NULL;
155        }
156    }
157}
158
159void
160Process::clone(ThreadContext *otc, ThreadContext *ntc,
161               Process *np, TheISA::IntReg flags)
162{
163    if (CLONE_VM & flags) {
164        /**
165         * Share the process memory address space between the new process
166         * and the old process. Changes in one will be visible in the other
167         * due to the pointer use.
168         */
169        delete np->pTable;
170        np->pTable = pTable;
171        ntc->getMemProxy().setPageTable(np->pTable);
172
173        np->memState = memState;
174    } else {
175        /**
176         * Duplicate the process memory address space. The state needs to be
177         * copied over (rather than using pointers to share everything).
178         */
179        typedef std::vector<pair<Addr,Addr>> MapVec;
180        MapVec mappings;
181        pTable->getMappings(&mappings);
182
183        for (auto map : mappings) {
184            Addr paddr, vaddr = map.first;
185            bool alloc_page = !(np->pTable->translate(vaddr, paddr));
186            np->replicatePage(vaddr, paddr, otc, ntc, alloc_page);
187        }
188
189        *np->memState = *memState;
190    }
191
192    if (CLONE_FILES & flags) {
193        /**
194         * The parent and child file descriptors are shared because the
195         * two FDArray pointers are pointing to the same FDArray. Opening
196         * and closing file descriptors will be visible to both processes.
197         */
198        np->fds = fds;
199    } else {
200        /**
201         * Copy the file descriptors from the old process into the new
202         * child process. The file descriptors entry can be opened and
203         * closed independently of the other process being considered. The
204         * host file descriptors are also dup'd so that the flags for the
205         * host file descriptor is independent of the other process.
206         */
207        for (int tgt_fd = 0; tgt_fd < fds->getSize(); tgt_fd++) {
208            std::shared_ptr<FDArray> nfds = np->fds;
209            std::shared_ptr<FDEntry> this_fde = (*fds)[tgt_fd];
210            if (!this_fde) {
211                nfds->setFDEntry(tgt_fd, nullptr);
212                continue;
213            }
214            nfds->setFDEntry(tgt_fd, this_fde->clone());
215
216            auto this_hbfd = std::dynamic_pointer_cast<HBFDEntry>(this_fde);
217            if (!this_hbfd)
218                continue;
219
220            int this_sim_fd = this_hbfd->getSimFD();
221            if (this_sim_fd <= 2)
222                continue;
223
224            int np_sim_fd = dup(this_sim_fd);
225            assert(np_sim_fd != -1);
226
227            auto nhbfd = std::dynamic_pointer_cast<HBFDEntry>((*nfds)[tgt_fd]);
228            nhbfd->setSimFD(np_sim_fd);
229        }
230    }
231
232    if (CLONE_THREAD & flags) {
233        np->_tgid = _tgid;
234        delete np->exitGroup;
235        np->exitGroup = exitGroup;
236    }
237
238    np->argv.insert(np->argv.end(), argv.begin(), argv.end());
239    np->envp.insert(np->envp.end(), envp.begin(), envp.end());
240}
241
242void
243Process::regStats()
244{
245    SimObject::regStats();
246
247    using namespace Stats;
248
249    numSyscalls
250        .name(name() + ".numSyscalls")
251        .desc("Number of system calls")
252        ;
253}
254
255ThreadContext *
256Process::findFreeContext()
257{
258    for (auto &it : system->threadContexts) {
259        if (ThreadContext::Halted == it->status())
260            return it;
261    }
262    return NULL;
263}
264
265void
266Process::revokeThreadContext(int context_id)
267{
268    std::vector<ContextID>::iterator it;
269    for (it = contextIds.begin(); it != contextIds.end(); it++) {
270        if (*it == context_id) {
271            contextIds.erase(it);
272            return;
273        }
274    }
275    warn("Unable to find thread context to revoke");
276}
277
278void
279Process::initState()
280{
281    if (contextIds.empty())
282        fatal("Process %s is not associated with any HW contexts!\n", name());
283
284    // first thread context for this process... initialize & enable
285    ThreadContext *tc = system->getThreadContext(contextIds[0]);
286
287    // mark this context as active so it will start ticking.
288    tc->activate();
289
290    pTable->initState(tc);
291}
292
293DrainState
294Process::drain()
295{
296    fds->updateFileOffsets();
297    return DrainState::Drained;
298}
299
300void
301Process::allocateMem(Addr vaddr, int64_t size, bool clobber)
302{
303    int npages = divCeil(size, (int64_t)PageBytes);
304    Addr paddr = system->allocPhysPages(npages);
305    pTable->map(vaddr, paddr, size,
306                clobber ? PageTableBase::Clobber : PageTableBase::Zero);
307}
308
309void
310Process::replicatePage(Addr vaddr, Addr new_paddr, ThreadContext *old_tc,
311                       ThreadContext *new_tc, bool allocate_page)
312{
313    if (allocate_page)
314        new_paddr = system->allocPhysPages(1);
315
316    // Read from old physical page.
317    uint8_t *buf_p = new uint8_t[PageBytes];
318    old_tc->getMemProxy().readBlob(vaddr, buf_p, PageBytes);
319
320    // Create new mapping in process address space by clobbering existing
321    // mapping (if any existed) and then write to the new physical page.
322    bool clobber = true;
323    pTable->map(vaddr, new_paddr, PageBytes, clobber);
324    new_tc->getMemProxy().writeBlob(vaddr, buf_p, PageBytes);
325    delete[] buf_p;
326}
327
328bool
329Process::fixupStackFault(Addr vaddr)
330{
331    Addr stack_min = memState->getStackMin();
332    Addr stack_base = memState->getStackBase();
333    Addr max_stack_size = memState->getMaxStackSize();
334
335    // Check if this is already on the stack and there's just no page there
336    // yet.
337    if (vaddr >= stack_min && vaddr < stack_base) {
338        allocateMem(roundDown(vaddr, PageBytes), PageBytes);
339        return true;
340    }
341
342    // We've accessed the next page of the stack, so extend it to include
343    // this address.
344    if (vaddr < stack_min && vaddr >= stack_base - max_stack_size) {
345        while (vaddr < stack_min) {
346            stack_min -= TheISA::PageBytes;
347            if (stack_base - stack_min > max_stack_size)
348                fatal("Maximum stack size exceeded\n");
349            allocateMem(stack_min, TheISA::PageBytes);
350            inform("Increasing stack size by one page.");
351        }
352        memState->setStackMin(stack_min);
353        return true;
354    }
355    return false;
356}
357
358void
359Process::serialize(CheckpointOut &cp) const
360{
361    pTable->serialize(cp);
362    /**
363     * Checkpoints for file descriptors currently do not work. Need to
364     * come back and fix them at a later date.
365     */
366
367    warn("Checkpoints for file descriptors currently do not work.");
368#if 0
369    for (int x = 0; x < fds->getSize(); x++)
370        (*fds)[x].serializeSection(cp, csprintf("FDEntry%d", x));
371#endif
372
373}
374
375void
376Process::unserialize(CheckpointIn &cp)
377{
378    pTable->unserialize(cp);
379    /**
380     * Checkpoints for file descriptors currently do not work. Need to
381     * come back and fix them at a later date.
382     */
383    warn("Checkpoints for file descriptors currently do not work.");
384#if 0
385    for (int x = 0; x < fds->getSize(); x++)
386        (*fds)[x]->unserializeSection(cp, csprintf("FDEntry%d", x));
387    fds->restoreFileOffsets();
388#endif
389    // The above returns a bool so that you could do something if you don't
390    // find the param in the checkpoint if you wanted to, like set a default
391    // but in this case we'll just stick with the instantiated value if not
392    // found.
393}
394
395bool
396Process::map(Addr vaddr, Addr paddr, int size, bool cacheable)
397{
398    pTable->map(vaddr, paddr, size,
399                cacheable ? PageTableBase::Zero : PageTableBase::Uncacheable);
400    return true;
401}
402
403void
404Process::syscall(int64_t callnum, ThreadContext *tc, Fault *fault)
405{
406    numSyscalls++;
407
408    SyscallDesc *desc = getDesc(callnum);
409    if (desc == NULL)
410        fatal("Syscall %d out of range", callnum);
411
412    desc->doSyscall(callnum, this, tc, fault);
413}
414
415IntReg
416Process::getSyscallArg(ThreadContext *tc, int &i, int width)
417{
418    return getSyscallArg(tc, i);
419}
420
421EmulatedDriver *
422Process::findDriver(std::string filename)
423{
424    for (EmulatedDriver *d : drivers) {
425        if (d->match(filename))
426            return d;
427    }
428
429    return NULL;
430}
431
432void
433Process::updateBias()
434{
435    ObjectFile *interp = objFile->getInterpreter();
436
437    if (!interp || !interp->relocatable())
438        return;
439
440    // Determine how large the interpreters footprint will be in the process
441    // address space.
442    Addr interp_mapsize = roundUp(interp->mapSize(), TheISA::PageBytes);
443
444    // We are allocating the memory area; set the bias to the lowest address
445    // in the allocated memory region.
446    Addr mmap_end = memState->getMmapEnd();
447    Addr ld_bias = mmapGrowsDown() ? mmap_end - interp_mapsize : mmap_end;
448
449    // Adjust the process mmap area to give the interpreter room; the real
450    // execve system call would just invoke the kernel's internal mmap
451    // functions to make these adjustments.
452    mmap_end = mmapGrowsDown() ? ld_bias : mmap_end + interp_mapsize;
453    memState->setMmapEnd(mmap_end);
454
455    interp->updateBias(ld_bias);
456}
457
458ObjectFile *
459Process::getInterpreter()
460{
461    return objFile->getInterpreter();
462}
463
464Addr
465Process::getBias()
466{
467    ObjectFile *interp = getInterpreter();
468
469    return interp ? interp->bias() : objFile->bias();
470}
471
472Addr
473Process::getStartPC()
474{
475    ObjectFile *interp = getInterpreter();
476
477    return interp ? interp->entryPoint() : objFile->entryPoint();
478}
479
480Process *
481ProcessParams::create()
482{
483    Process *process = NULL;
484
485    // If not specified, set the executable parameter equal to the
486    // simulated system's zeroth command line parameter
487    if (executable == "") {
488        executable = cmd[0];
489    }
490
491    ObjectFile *obj_file = createObjectFile(executable);
492    if (obj_file == NULL) {
493        fatal("Can't load object file %s", executable);
494    }
495
496#if THE_ISA == ALPHA_ISA
497    if (obj_file->getArch() != ObjectFile::Alpha)
498        fatal("Object file architecture does not match compiled ISA (Alpha).");
499
500    switch (obj_file->getOpSys()) {
501      case ObjectFile::UnknownOpSys:
502        warn("Unknown operating system; assuming Linux.");
503        // fall through
504      case ObjectFile::Linux:
505        process = new AlphaLinuxProcess(this, obj_file);
506        break;
507
508      default:
509        fatal("Unknown/unsupported operating system.");
510    }
511#elif THE_ISA == SPARC_ISA
512    if (obj_file->getArch() != ObjectFile::SPARC64 &&
513        obj_file->getArch() != ObjectFile::SPARC32)
514        fatal("Object file architecture does not match compiled ISA (SPARC).");
515    switch (obj_file->getOpSys()) {
516      case ObjectFile::UnknownOpSys:
517        warn("Unknown operating system; assuming Linux.");
518        // fall through
519      case ObjectFile::Linux:
520        if (obj_file->getArch() == ObjectFile::SPARC64) {
521            process = new Sparc64LinuxProcess(this, obj_file);
522        } else {
523            process = new Sparc32LinuxProcess(this, obj_file);
524        }
525        break;
526
527      case ObjectFile::Solaris:
528        process = new SparcSolarisProcess(this, obj_file);
529        break;
530
531      default:
532        fatal("Unknown/unsupported operating system.");
533    }
534#elif THE_ISA == X86_ISA
535    if (obj_file->getArch() != ObjectFile::X86_64 &&
536        obj_file->getArch() != ObjectFile::I386)
537        fatal("Object file architecture does not match compiled ISA (x86).");
538    switch (obj_file->getOpSys()) {
539      case ObjectFile::UnknownOpSys:
540        warn("Unknown operating system; assuming Linux.");
541        // fall through
542      case ObjectFile::Linux:
543        if (obj_file->getArch() == ObjectFile::X86_64) {
544            process = new X86_64LinuxProcess(this, obj_file);
545        } else {
546            process = new I386LinuxProcess(this, obj_file);
547        }
548        break;
549
550      default:
551        fatal("Unknown/unsupported operating system.");
552    }
553#elif THE_ISA == MIPS_ISA
554    if (obj_file->getArch() != ObjectFile::Mips)
555        fatal("Object file architecture does not match compiled ISA (MIPS).");
556    switch (obj_file->getOpSys()) {
557      case ObjectFile::UnknownOpSys:
558        warn("Unknown operating system; assuming Linux.");
559        // fall through
560      case ObjectFile::Linux:
561        process = new MipsLinuxProcess(this, obj_file);
562        break;
563
564      default:
565        fatal("Unknown/unsupported operating system.");
566    }
567#elif THE_ISA == ARM_ISA
568    ObjectFile::Arch arch = obj_file->getArch();
569    if (arch != ObjectFile::Arm && arch != ObjectFile::Thumb &&
570        arch != ObjectFile::Arm64)
571        fatal("Object file architecture does not match compiled ISA (ARM).");
572    switch (obj_file->getOpSys()) {
573      case ObjectFile::UnknownOpSys:
574        warn("Unknown operating system; assuming Linux.");
575        // fall through
576      case ObjectFile::Linux:
577        if (arch == ObjectFile::Arm64) {
578            process = new ArmLinuxProcess64(this, obj_file,
579                                            obj_file->getArch());
580        } else {
581            process = new ArmLinuxProcess32(this, obj_file,
582                                            obj_file->getArch());
583        }
584        break;
585      case ObjectFile::FreeBSD:
586        if (arch == ObjectFile::Arm64) {
587            process = new ArmFreebsdProcess64(this, obj_file,
588                                              obj_file->getArch());
589        } else {
590            process = new ArmFreebsdProcess32(this, obj_file,
591                                              obj_file->getArch());
592        }
593        break;
594      case ObjectFile::LinuxArmOABI:
595        fatal("M5 does not support ARM OABI binaries. Please recompile with an"
596              " EABI compiler.");
597      default:
598        fatal("Unknown/unsupported operating system.");
599    }
600#elif THE_ISA == POWER_ISA
601    if (obj_file->getArch() != ObjectFile::Power)
602        fatal("Object file architecture does not match compiled ISA (Power).");
603    switch (obj_file->getOpSys()) {
604      case ObjectFile::UnknownOpSys:
605        warn("Unknown operating system; assuming Linux.");
606        // fall through
607      case ObjectFile::Linux:
608        process = new PowerLinuxProcess(this, obj_file);
609        break;
610
611      default:
612        fatal("Unknown/unsupported operating system.");
613    }
614#elif THE_ISA == RISCV_ISA
615    if (obj_file->getArch() != ObjectFile::Riscv)
616        fatal("Object file architecture does not match compiled ISA (RISCV).");
617    switch (obj_file->getOpSys()) {
618      case ObjectFile::UnknownOpSys:
619        warn("Unknown operating system; assuming Linux.");
620        // fall through
621      case ObjectFile::Linux:
622        process = new RiscvLinuxProcess(this, obj_file);
623        break;
624      default:
625        fatal("Unknown/unsupported operating system.");
626    }
627#else
628#error "THE_ISA not set"
629#endif
630
631    if (process == NULL)
632        fatal("Unknown error creating process object.");
633    return process;
634}
635
636std::string
637Process::fullPath(const std::string &file_name)
638{
639    if (file_name[0] == '/' || cwd.empty())
640        return file_name;
641
642    std::string full = cwd;
643
644    if (cwd[cwd.size() - 1] != '/')
645        full += '/';
646
647    return full + file_name;
648}
649