process.cc revision 14139:0ea736dea1ff
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 <climits>
54#include <csignal>
55#include <map>
56#include <string>
57#include <vector>
58
59#include "base/intmath.hh"
60#include "base/loader/object_file.hh"
61#include "base/loader/symtab.hh"
62#include "base/statistics.hh"
63#include "config/the_isa.hh"
64#include "cpu/thread_context.hh"
65#include "mem/page_table.hh"
66#include "mem/se_translating_port_proxy.hh"
67#include "params/Process.hh"
68#include "sim/emul_driver.hh"
69#include "sim/fd_array.hh"
70#include "sim/fd_entry.hh"
71#include "sim/redirect_path.hh"
72#include "sim/syscall_desc.hh"
73#include "sim/system.hh"
74
75using namespace std;
76using namespace TheISA;
77
78static std::string
79normalize(std::string& directory)
80{
81    if (directory.back() != '/')
82        directory += '/';
83    return directory;
84}
85
86Process::Process(ProcessParams *params, EmulationPageTable *pTable,
87                 ObjectFile *obj_file)
88    : SimObject(params), system(params->system),
89      useArchPT(params->useArchPT),
90      kvmInSE(params->kvmInSE),
91      useForClone(false),
92      pTable(pTable),
93      initVirtMem(system->getSystemPort(), this,
94                  SETranslatingPortProxy::Always),
95      objFile(obj_file),
96      argv(params->cmd), envp(params->env),
97      executable(params->executable),
98      tgtCwd(normalize(params->cwd)),
99      hostCwd(checkPathRedirect(tgtCwd)),
100      release(params->release),
101      _uid(params->uid), _euid(params->euid),
102      _gid(params->gid), _egid(params->egid),
103      _pid(params->pid), _ppid(params->ppid),
104      _pgid(params->pgid), drivers(params->drivers),
105      fds(make_shared<FDArray>(params->input, params->output, params->errout)),
106      childClearTID(0)
107{
108    if (_pid >= System::maxPID)
109        fatal("_pid is too large: %d", _pid);
110
111    auto ret_pair = system->PIDs.emplace(_pid);
112    if (!ret_pair.second)
113        fatal("_pid %d is already used", _pid);
114
115    /**
116     * Linux bundles together processes into this concept called a thread
117     * group. The thread group is responsible for recording which processes
118     * behave as threads within a process context. The thread group leader
119     * is the process who's tgid is equal to its pid. Other processes which
120     * belong to the thread group, but do not lead the thread group, are
121     * treated as child threads. These threads are created by the clone system
122     * call with options specified to create threads (differing from the
123     * options used to implement a fork). By default, set up the tgid/pid
124     * with a new, equivalent value. If CLONE_THREAD is specified, patch
125     * the tgid value with the old process' value.
126     */
127    _tgid = params->pid;
128
129    exitGroup = new bool();
130    sigchld = new bool();
131
132    if (!debugSymbolTable) {
133        debugSymbolTable = new SymbolTable();
134        if (!objFile->loadGlobalSymbols(debugSymbolTable) ||
135            !objFile->loadLocalSymbols(debugSymbolTable) ||
136            !objFile->loadWeakSymbols(debugSymbolTable)) {
137            delete debugSymbolTable;
138            debugSymbolTable = nullptr;
139        }
140    }
141}
142
143void
144Process::clone(ThreadContext *otc, ThreadContext *ntc,
145               Process *np, RegVal flags)
146{
147#ifndef CLONE_VM
148#define CLONE_VM 0
149#endif
150#ifndef CLONE_FILES
151#define CLONE_FILES 0
152#endif
153#ifndef CLONE_THREAD
154#define CLONE_THREAD 0
155#endif
156    if (CLONE_VM & flags) {
157        /**
158         * Share the process memory address space between the new process
159         * and the old process. Changes in one will be visible in the other
160         * due to the pointer use.
161         */
162        delete np->pTable;
163        np->pTable = pTable;
164        auto &proxy = dynamic_cast<SETranslatingPortProxy &>(
165                ntc->getVirtProxy());
166        proxy.setPageTable(np->pTable);
167
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        std::shared_ptr<FDArray> nfds = np->fds;
203        for (int tgt_fd = 0; tgt_fd < fds->getSize(); tgt_fd++) {
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 nullptr;
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();
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 ? EmulationPageTable::Clobber :
302                          EmulationPageTable::MappingFlags(0));
303}
304
305void
306Process::replicatePage(Addr vaddr, Addr new_paddr, ThreadContext *old_tc,
307                       ThreadContext *new_tc, bool allocate_page)
308{
309    if (allocate_page)
310        new_paddr = system->allocPhysPages(1);
311
312    // Read from old physical page.
313    uint8_t *buf_p = new uint8_t[PageBytes];
314    old_tc->getVirtProxy().readBlob(vaddr, buf_p, PageBytes);
315
316    // Create new mapping in process address space by clobbering existing
317    // mapping (if any existed) and then write to the new physical page.
318    bool clobber = true;
319    pTable->map(vaddr, new_paddr, PageBytes, clobber);
320    new_tc->getVirtProxy().writeBlob(vaddr, buf_p, PageBytes);
321    delete[] buf_p;
322}
323
324bool
325Process::fixupStackFault(Addr vaddr)
326{
327    Addr stack_min = memState->getStackMin();
328    Addr stack_base = memState->getStackBase();
329    Addr max_stack_size = memState->getMaxStackSize();
330
331    // Check if this is already on the stack and there's just no page there
332    // yet.
333    if (vaddr >= stack_min && vaddr < stack_base) {
334        allocateMem(roundDown(vaddr, PageBytes), PageBytes);
335        return true;
336    }
337
338    // We've accessed the next page of the stack, so extend it to include
339    // this address.
340    if (vaddr < stack_min && vaddr >= stack_base - max_stack_size) {
341        while (vaddr < stack_min) {
342            stack_min -= TheISA::PageBytes;
343            if (stack_base - stack_min > max_stack_size)
344                fatal("Maximum stack size exceeded\n");
345            allocateMem(stack_min, TheISA::PageBytes);
346            inform("Increasing stack size by one page.");
347        }
348        memState->setStackMin(stack_min);
349        return true;
350    }
351    return false;
352}
353
354void
355Process::serialize(CheckpointOut &cp) const
356{
357    memState->serialize(cp);
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}
366
367void
368Process::unserialize(CheckpointIn &cp)
369{
370    memState->unserialize(cp);
371    pTable->unserialize(cp);
372    /**
373     * Checkpoints for file descriptors currently do not work. Need to
374     * come back and fix them at a later date.
375     */
376    warn("Checkpoints for file descriptors currently do not work.");
377    // The above returns a bool so that you could do something if you don't
378    // find the param in the checkpoint if you wanted to, like set a default
379    // but in this case we'll just stick with the instantiated value if not
380    // found.
381}
382
383bool
384Process::map(Addr vaddr, Addr paddr, int size, bool cacheable)
385{
386    pTable->map(vaddr, paddr, size,
387                cacheable ? EmulationPageTable::MappingFlags(0) :
388                            EmulationPageTable::Uncacheable);
389    return true;
390}
391
392void
393Process::syscall(int64_t callnum, ThreadContext *tc, Fault *fault)
394{
395    numSyscalls++;
396
397    SyscallDesc *desc = getDesc(callnum);
398    if (desc == nullptr)
399        fatal("Syscall %d out of range", callnum);
400
401    desc->doSyscall(callnum, tc, fault);
402}
403
404RegVal
405Process::getSyscallArg(ThreadContext *tc, int &i, int width)
406{
407    return getSyscallArg(tc, i);
408}
409
410EmulatedDriver *
411Process::findDriver(std::string filename)
412{
413    for (EmulatedDriver *d : drivers) {
414        if (d->match(filename))
415            return d;
416    }
417
418    return nullptr;
419}
420
421std::string
422Process::checkPathRedirect(const std::string &filename)
423{
424    // If the input parameter contains a relative path, convert it.
425    // The target version of the current working directory is fine since
426    // we immediately convert it using redirect paths into a host version.
427    auto abs_path = absolutePath(filename, false);
428
429    for (auto path : system->redirectPaths) {
430        // Search through the redirect paths to see if a starting substring of
431        // our path falls into any buckets which need to redirected.
432        if (startswith(abs_path, path->appPath())) {
433            std::string tail = abs_path.substr(path->appPath().size());
434
435            // If this path needs to be redirected, search through a list
436            // of targets to see if we can match a valid file (or directory).
437            for (auto host_path : path->hostPaths()) {
438                if (access((host_path + tail).c_str(), R_OK) == 0) {
439                    // Return the valid match.
440                    return host_path + tail;
441                }
442            }
443            // The path needs to be redirected, but the file or directory
444            // does not exist on the host filesystem. Return the first
445            // host path as a default.
446            return path->hostPaths()[0] + tail;
447        }
448    }
449
450    // The path does not need to be redirected.
451    return abs_path;
452}
453
454void
455Process::updateBias()
456{
457    ObjectFile *interp = objFile->getInterpreter();
458
459    if (!interp || !interp->relocatable())
460        return;
461
462    // Determine how large the interpreters footprint will be in the process
463    // address space.
464    Addr interp_mapsize = roundUp(interp->mapSize(), TheISA::PageBytes);
465
466    // We are allocating the memory area; set the bias to the lowest address
467    // in the allocated memory region.
468    Addr mmap_end = memState->getMmapEnd();
469    Addr ld_bias = mmapGrowsDown() ? mmap_end - interp_mapsize : mmap_end;
470
471    // Adjust the process mmap area to give the interpreter room; the real
472    // execve system call would just invoke the kernel's internal mmap
473    // functions to make these adjustments.
474    mmap_end = mmapGrowsDown() ? ld_bias : mmap_end + interp_mapsize;
475    memState->setMmapEnd(mmap_end);
476
477    interp->updateBias(ld_bias);
478}
479
480ObjectFile *
481Process::getInterpreter()
482{
483    return objFile->getInterpreter();
484}
485
486Addr
487Process::getBias()
488{
489    ObjectFile *interp = getInterpreter();
490
491    return interp ? interp->bias() : objFile->bias();
492}
493
494Addr
495Process::getStartPC()
496{
497    ObjectFile *interp = getInterpreter();
498
499    return interp ? interp->entryPoint() : objFile->entryPoint();
500}
501
502std::string
503Process::absolutePath(const std::string &filename, bool host_filesystem)
504{
505    if (filename.empty() || startswith(filename, "/"))
506        return filename;
507
508    // Construct the absolute path given the current working directory for
509    // either the host filesystem or target filesystem. The distinction only
510    // matters if filesystem redirection is utilized in the simulation.
511    auto path_base = std::string();
512    if (host_filesystem) {
513        path_base = hostCwd;
514        assert(!hostCwd.empty());
515    } else {
516        path_base = tgtCwd;
517        assert(!tgtCwd.empty());
518    }
519
520    // Add a trailing '/' if the current working directory did not have one.
521    normalize(path_base);
522
523    // Append the filename onto the current working path.
524    auto absolute_path = path_base + filename;
525
526    return absolute_path;
527}
528
529Process *
530ProcessParams::create()
531{
532    // If not specified, set the executable parameter equal to the
533    // simulated system's zeroth command line parameter
534    if (executable == "") {
535        executable = cmd[0];
536    }
537
538    ObjectFile *obj_file = createObjectFile(executable);
539    fatal_if(!obj_file, "Cannot load object file %s.", executable);
540
541    Process *process = ObjectFile::tryLoaders(this, obj_file);
542    fatal_if(!process, "Unknown error creating process object.");
543
544    return process;
545}
546