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