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