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