2 * Copyright (c) 2014 Advanced Micro Devices, Inc.
3 * Copyright (c) 2012 ARM Limited
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.
15 * Copyright (c) 2001-2005 The Regents of The University of Michigan
16 * All rights reserved.
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.
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.
41 * Authors: Nathan Binkert
46 #include "sim/process.hh"
56 #include "base/intmath.hh"
57 #include "base/loader/object_file.hh"
58 #include "base/loader/symtab.hh"
59 #include "base/statistics.hh"
60 #include "config/the_isa.hh"
61 #include "cpu/thread_context.hh"
62 #include "mem/page_table.hh"
63 #include "mem/se_translating_port_proxy.hh"
64 #include "params/Process.hh"
65 #include "sim/emul_driver.hh"
66 #include "sim/syscall_desc.hh"
67 #include "sim/system.hh"
69 #if THE_ISA == ALPHA_ISA
70 #include "arch/alpha/linux/process.hh"
71 #elif THE_ISA == SPARC_ISA
72 #include "arch/sparc/linux/process.hh"
73 #include "arch/sparc/solaris/process.hh"
74 #elif THE_ISA == MIPS_ISA
75 #include "arch/mips/linux/process.hh"
76 #elif THE_ISA == ARM_ISA
77 #include "arch/arm/linux/process.hh"
78 #include "arch/arm/freebsd/process.hh"
79 #elif THE_ISA == X86_ISA
80 #include "arch/x86/linux/process.hh"
81 #elif THE_ISA == POWER_ISA
82 #include "arch/power/linux/process.hh"
83 #elif THE_ISA == RISCV_ISA
84 #include "arch/riscv/linux/process.hh"
86 #error "THE_ISA not set"
91 using namespace TheISA
;
93 // current number of allocated processes
94 int num_processes
= 0;
96 template<class IntType
>
98 AuxVector
<IntType
>::AuxVector(IntType type
, IntType val
)
100 a_type
= TheISA::htog(type
);
101 a_val
= TheISA::htog(val
);
104 template struct AuxVector
<uint32_t>;
105 template struct AuxVector
<uint64_t>;
108 openFile(const string
& filename
, int flags
, mode_t mode
)
110 int sim_fd
= open(filename
.c_str(), flags
, mode
);
113 fatal("Unable to open %s with mode %O", filename
, mode
);
117 openInputFile(const string
&filename
)
119 return openFile(filename
, O_RDONLY
, 0);
123 openOutputFile(const string
&filename
)
125 return openFile(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
, 0664);
128 Process::Process(ProcessParams
* params
, ObjectFile
* obj_file
)
129 : SimObject(params
), system(params
->system
),
130 brk_point(0), stack_base(0), stack_size(0), stack_min(0),
131 max_stack_size(params
->max_stack_size
),
132 next_thread_stack_base(0),
133 useArchPT(params
->useArchPT
),
134 kvmInSE(params
->kvmInSE
),
136 static_cast<PageTableBase
*>(new ArchPageTable(name(), params
->pid
,
138 static_cast<PageTableBase
*>(new FuncPageTable(name(), params
->pid
))),
139 initVirtMem(system
->getSystemPort(), this,
140 SETranslatingPortProxy::Always
),
141 fd_array(make_shared
<array
<FDEntry
, NUM_FDS
>>()),
143 {"cin", STDIN_FILENO
},
144 {"stdin", STDIN_FILENO
}},
146 {"cout", STDOUT_FILENO
},
147 {"stdout", STDOUT_FILENO
},
148 {"cerr", STDERR_FILENO
},
149 {"stderr", STDERR_FILENO
}},
151 argv(params
->cmd
), envp(params
->env
), cwd(params
->cwd
),
152 executable(params
->executable
),
153 _uid(params
->uid
), _euid(params
->euid
),
154 _gid(params
->gid
), _egid(params
->egid
),
155 _pid(params
->pid
), _ppid(params
->ppid
),
156 drivers(params
->drivers
)
159 std::map
<string
,int>::iterator it
;
161 // Search through the input options and set fd if match is found;
162 // otherwise, open an input file and seek to location.
163 FDEntry
*fde_stdin
= getFDEntry(STDIN_FILENO
);
164 if ((it
= imap
.find(params
->input
)) != imap
.end())
167 sim_fd
= openInputFile(params
->input
);
168 fde_stdin
->set(sim_fd
, params
->input
, O_RDONLY
, -1, false);
170 // Search through the output/error options and set fd if match is found;
171 // otherwise, open an output file and seek to location.
172 FDEntry
*fde_stdout
= getFDEntry(STDOUT_FILENO
);
173 if ((it
= oemap
.find(params
->output
)) != oemap
.end())
176 sim_fd
= openOutputFile(params
->output
);
177 fde_stdout
->set(sim_fd
, params
->output
, O_WRONLY
| O_CREAT
| O_TRUNC
,
180 FDEntry
*fde_stderr
= getFDEntry(STDERR_FILENO
);
181 if (params
->output
== params
->errout
)
182 // Reuse the same file descriptor if these match.
183 sim_fd
= fde_stdout
->fd
;
184 else if ((it
= oemap
.find(params
->errout
)) != oemap
.end())
187 sim_fd
= openOutputFile(params
->errout
);
188 fde_stderr
->set(sim_fd
, params
->errout
, O_WRONLY
| O_CREAT
| O_TRUNC
,
192 nxm_start
= nxm_end
= 0;
193 // other parameters will be initialized when the program is loaded
195 // load up symbols, if any... these may be used for debugging or
197 if (!debugSymbolTable
) {
198 debugSymbolTable
= new SymbolTable();
199 if (!objFile
->loadGlobalSymbols(debugSymbolTable
) ||
200 !objFile
->loadLocalSymbols(debugSymbolTable
) ||
201 !objFile
->loadWeakSymbols(debugSymbolTable
)) {
202 // didn't load any symbols
203 delete debugSymbolTable
;
204 debugSymbolTable
= NULL
;
213 SimObject::regStats();
215 using namespace Stats
;
218 .name(name() + ".num_syscalls")
219 .desc("Number of system calls")
224 Process::inheritFDArray(Process
*p
)
226 fd_array
= p
->fd_array
;
230 Process::findFreeContext()
232 for (int id
: contextIds
) {
233 ThreadContext
*tc
= system
->getThreadContext(id
);
234 if (tc
->status() == ThreadContext::Halted
)
243 if (contextIds
.empty())
244 fatal("Process %s is not associated with any HW contexts!\n", name());
246 // first thread context for this process... initialize & enable
247 ThreadContext
*tc
= system
->getThreadContext(contextIds
[0]);
249 // mark this context as active so it will start ticking.
252 pTable
->initState(tc
);
259 return DrainState::Drained
;
263 Process::allocFD(int sim_fd
, const string
& filename
, int flags
, int mode
,
266 for (int free_fd
= 0; free_fd
< fd_array
->size(); free_fd
++) {
267 FDEntry
*fde
= getFDEntry(free_fd
);
269 fde
->set(sim_fd
, filename
, flags
, mode
, pipe
);
274 fatal("Out of target file descriptors");
278 Process::resetFDEntry(int tgt_fd
)
280 FDEntry
*fde
= getFDEntry(tgt_fd
);
281 assert(fde
->fd
> -1);
287 Process::getSimFD(int tgt_fd
)
289 FDEntry
*entry
= getFDEntry(tgt_fd
);
290 return entry
? entry
->fd
: -1;
294 Process::getFDEntry(int tgt_fd
)
296 assert(0 <= tgt_fd
&& tgt_fd
< fd_array
->size());
297 return &(*fd_array
)[tgt_fd
];
301 Process::getTgtFD(int sim_fd
)
303 for (int index
= 0; index
< fd_array
->size(); index
++)
304 if ((*fd_array
)[index
].fd
== sim_fd
)
310 Process::allocateMem(Addr vaddr
, int64_t size
, bool clobber
)
312 int npages
= divCeil(size
, (int64_t)PageBytes
);
313 Addr paddr
= system
->allocPhysPages(npages
);
314 pTable
->map(vaddr
, paddr
, size
,
315 clobber
? PageTableBase::Clobber
: PageTableBase::Zero
);
319 Process::fixupStackFault(Addr vaddr
)
321 // Check if this is already on the stack and there's just no page there
323 if (vaddr
>= stack_min
&& vaddr
< stack_base
) {
324 allocateMem(roundDown(vaddr
, PageBytes
), PageBytes
);
328 // We've accessed the next page of the stack, so extend it to include
330 if (vaddr
< stack_min
&& vaddr
>= stack_base
- max_stack_size
) {
331 while (vaddr
< stack_min
) {
332 stack_min
-= TheISA::PageBytes
;
333 if (stack_base
- stack_min
> max_stack_size
)
334 fatal("Maximum stack size exceeded\n");
335 allocateMem(stack_min
, TheISA::PageBytes
);
336 inform("Increasing stack size by one page.");
344 Process::fixFileOffsets()
346 auto seek
= [] (FDEntry
*fde
)
348 if (lseek(fde
->fd
, fde
->fileOffset
, SEEK_SET
) < 0)
349 fatal("Unable to see to location in %s", fde
->filename
);
352 std::map
<string
,int>::iterator it
;
354 // Search through the input options and set fd if match is found;
355 // otherwise, open an input file and seek to location.
356 FDEntry
*fde_stdin
= getFDEntry(STDIN_FILENO
);
358 // Check if user has specified a different input file, and if so, use it
359 // instead of the file specified in the checkpoint. This also resets the
360 // file offset from the checkpointed value
361 string new_in
= ((ProcessParams
*)params())->input
;
362 if (new_in
!= fde_stdin
->filename
) {
363 warn("Using new input file (%s) rather than checkpointed (%s)\n",
364 new_in
, fde_stdin
->filename
);
365 fde_stdin
->filename
= new_in
;
366 fde_stdin
->fileOffset
= 0;
369 if ((it
= imap
.find(fde_stdin
->filename
)) != imap
.end()) {
370 fde_stdin
->fd
= it
->second
;
372 fde_stdin
->fd
= openInputFile(fde_stdin
->filename
);
376 // Search through the output/error options and set fd if match is found;
377 // otherwise, open an output file and seek to location.
378 FDEntry
*fde_stdout
= getFDEntry(STDOUT_FILENO
);
380 // Check if user has specified a different output file, and if so, use it
381 // instead of the file specified in the checkpoint. This also resets the
382 // file offset from the checkpointed value
383 string new_out
= ((ProcessParams
*)params())->output
;
384 if (new_out
!= fde_stdout
->filename
) {
385 warn("Using new output file (%s) rather than checkpointed (%s)\n",
386 new_out
, fde_stdout
->filename
);
387 fde_stdout
->filename
= new_out
;
388 fde_stdout
->fileOffset
= 0;
391 if ((it
= oemap
.find(fde_stdout
->filename
)) != oemap
.end()) {
392 fde_stdout
->fd
= it
->second
;
394 fde_stdout
->fd
= openOutputFile(fde_stdout
->filename
);
398 FDEntry
*fde_stderr
= getFDEntry(STDERR_FILENO
);
400 // Check if user has specified a different error file, and if so, use it
401 // instead of the file specified in the checkpoint. This also resets the
402 // file offset from the checkpointed value
403 string new_err
= ((ProcessParams
*)params())->errout
;
404 if (new_err
!= fde_stderr
->filename
) {
405 warn("Using new error file (%s) rather than checkpointed (%s)\n",
406 new_err
, fde_stderr
->filename
);
407 fde_stderr
->filename
= new_err
;
408 fde_stderr
->fileOffset
= 0;
411 if (fde_stdout
->filename
== fde_stderr
->filename
) {
412 // Reuse the same file descriptor if these match.
413 fde_stderr
->fd
= fde_stdout
->fd
;
414 } else if ((it
= oemap
.find(fde_stderr
->filename
)) != oemap
.end()) {
415 fde_stderr
->fd
= it
->second
;
417 fde_stderr
->fd
= openOutputFile(fde_stderr
->filename
);
421 for (int tgt_fd
= 3; tgt_fd
< fd_array
->size(); tgt_fd
++) {
422 FDEntry
*fde
= getFDEntry(tgt_fd
);
427 if (fde
->filename
== "PIPE-WRITE")
429 assert(fde
->filename
== "PIPE-READ");
433 fatal("Unable to create new pipe");
437 FDEntry
*fde_write
= getFDEntry(fde
->readPipeSource
);
438 assert(fde_write
->filename
== "PIPE-WRITE");
439 fde_write
->fd
= fds
[1];
441 fde
->fd
= openFile(fde
->filename
.c_str(), fde
->flags
, fde
->mode
);
448 Process::findFileOffsets()
450 for (auto& fde
: *fd_array
) {
452 fde
.fileOffset
= lseek(fde
.fd
, 0, SEEK_CUR
);
457 Process::setReadPipeSource(int read_pipe_fd
, int source_fd
)
459 FDEntry
*fde
= getFDEntry(read_pipe_fd
);
460 assert(source_fd
>= -1);
461 fde
->readPipeSource
= source_fd
;
465 Process::serialize(CheckpointOut
&cp
) const
467 SERIALIZE_SCALAR(brk_point
);
468 SERIALIZE_SCALAR(stack_base
);
469 SERIALIZE_SCALAR(stack_size
);
470 SERIALIZE_SCALAR(stack_min
);
471 SERIALIZE_SCALAR(next_thread_stack_base
);
472 SERIALIZE_SCALAR(mmap_end
);
473 SERIALIZE_SCALAR(nxm_start
);
474 SERIALIZE_SCALAR(nxm_end
);
475 pTable
->serialize(cp
);
476 for (int x
= 0; x
< fd_array
->size(); x
++) {
477 (*fd_array
)[x
].serializeSection(cp
, csprintf("FDEntry%d", x
));
483 Process::unserialize(CheckpointIn
&cp
)
485 UNSERIALIZE_SCALAR(brk_point
);
486 UNSERIALIZE_SCALAR(stack_base
);
487 UNSERIALIZE_SCALAR(stack_size
);
488 UNSERIALIZE_SCALAR(stack_min
);
489 UNSERIALIZE_SCALAR(next_thread_stack_base
);
490 UNSERIALIZE_SCALAR(mmap_end
);
491 UNSERIALIZE_SCALAR(nxm_start
);
492 UNSERIALIZE_SCALAR(nxm_end
);
493 pTable
->unserialize(cp
);
494 for (int x
= 0; x
< fd_array
->size(); x
++) {
495 FDEntry
*fde
= getFDEntry(x
);
496 fde
->unserializeSection(cp
, csprintf("FDEntry%d", x
));
499 // The above returns a bool so that you could do something if you don't
500 // find the param in the checkpoint if you wanted to, like set a default
501 // but in this case we'll just stick with the instantiated value if not
507 Process::map(Addr vaddr
, Addr paddr
, int size
, bool cacheable
)
509 pTable
->map(vaddr
, paddr
, size
,
510 cacheable
? PageTableBase::Zero
: PageTableBase::Uncacheable
);
516 Process::syscall(int64_t callnum
, ThreadContext
*tc
)
520 SyscallDesc
*desc
= getDesc(callnum
);
522 fatal("Syscall %d out of range", callnum
);
524 desc
->doSyscall(callnum
, this, tc
);
528 Process::getSyscallArg(ThreadContext
*tc
, int &i
, int width
)
530 return getSyscallArg(tc
, i
);
535 Process::findDriver(std::string filename
)
537 for (EmulatedDriver
*d
: drivers
) {
538 if (d
->match(filename
))
546 Process::updateBias()
548 ObjectFile
*interp
= objFile
->getInterpreter();
550 if (!interp
|| !interp
->relocatable())
553 // Determine how large the interpreters footprint will be in the process
555 Addr interp_mapsize
= roundUp(interp
->mapSize(), TheISA::PageBytes
);
557 // We are allocating the memory area; set the bias to the lowest address
558 // in the allocated memory region.
559 Addr ld_bias
= mmapGrowsDown() ? mmap_end
- interp_mapsize
: mmap_end
;
561 // Adjust the process mmap area to give the interpreter room; the real
562 // execve system call would just invoke the kernel's internal mmap
563 // functions to make these adjustments.
564 mmap_end
= mmapGrowsDown() ? ld_bias
: mmap_end
+ interp_mapsize
;
566 interp
->updateBias(ld_bias
);
571 Process::getInterpreter()
573 return objFile
->getInterpreter();
580 ObjectFile
*interp
= getInterpreter();
582 return interp
? interp
->bias() : objFile
->bias();
587 Process::getStartPC()
589 ObjectFile
*interp
= getInterpreter();
591 return interp
? interp
->entryPoint() : objFile
->entryPoint();
596 ProcessParams::create()
598 Process
*process
= NULL
;
600 // If not specified, set the executable parameter equal to the
601 // simulated system's zeroth command line parameter
602 if (executable
== "") {
606 ObjectFile
*obj_file
= createObjectFile(executable
);
607 if (obj_file
== NULL
) {
608 fatal("Can't load object file %s", executable
);
611 #if THE_ISA == ALPHA_ISA
612 if (obj_file
->getArch() != ObjectFile::Alpha
)
613 fatal("Object file architecture does not match compiled ISA (Alpha).");
615 switch (obj_file
->getOpSys()) {
616 case ObjectFile::UnknownOpSys
:
617 warn("Unknown operating system; assuming Linux.");
619 case ObjectFile::Linux
:
620 process
= new AlphaLinuxProcess(this, obj_file
);
624 fatal("Unknown/unsupported operating system.");
626 #elif THE_ISA == SPARC_ISA
627 if (obj_file
->getArch() != ObjectFile::SPARC64
&&
628 obj_file
->getArch() != ObjectFile::SPARC32
)
629 fatal("Object file architecture does not match compiled ISA (SPARC).");
630 switch (obj_file
->getOpSys()) {
631 case ObjectFile::UnknownOpSys
:
632 warn("Unknown operating system; assuming Linux.");
634 case ObjectFile::Linux
:
635 if (obj_file
->getArch() == ObjectFile::SPARC64
) {
636 process
= new Sparc64LinuxProcess(this, obj_file
);
638 process
= new Sparc32LinuxProcess(this, obj_file
);
643 case ObjectFile::Solaris
:
644 process
= new SparcSolarisProcess(this, obj_file
);
648 fatal("Unknown/unsupported operating system.");
650 #elif THE_ISA == X86_ISA
651 if (obj_file
->getArch() != ObjectFile::X86_64
&&
652 obj_file
->getArch() != ObjectFile::I386
)
653 fatal("Object file architecture does not match compiled ISA (x86).");
654 switch (obj_file
->getOpSys()) {
655 case ObjectFile::UnknownOpSys
:
656 warn("Unknown operating system; assuming Linux.");
658 case ObjectFile::Linux
:
659 if (obj_file
->getArch() == ObjectFile::X86_64
) {
660 process
= new X86_64LinuxProcess(this, obj_file
);
662 process
= new I386LinuxProcess(this, obj_file
);
667 fatal("Unknown/unsupported operating system.");
669 #elif THE_ISA == MIPS_ISA
670 if (obj_file
->getArch() != ObjectFile::Mips
)
671 fatal("Object file architecture does not match compiled ISA (MIPS).");
672 switch (obj_file
->getOpSys()) {
673 case ObjectFile::UnknownOpSys
:
674 warn("Unknown operating system; assuming Linux.");
676 case ObjectFile::Linux
:
677 process
= new MipsLinuxProcess(this, obj_file
);
681 fatal("Unknown/unsupported operating system.");
683 #elif THE_ISA == ARM_ISA
684 ObjectFile::Arch arch
= obj_file
->getArch();
685 if (arch
!= ObjectFile::Arm
&& arch
!= ObjectFile::Thumb
&&
686 arch
!= ObjectFile::Arm64
)
687 fatal("Object file architecture does not match compiled ISA (ARM).");
688 switch (obj_file
->getOpSys()) {
689 case ObjectFile::UnknownOpSys
:
690 warn("Unknown operating system; assuming Linux.");
692 case ObjectFile::Linux
:
693 if (arch
== ObjectFile::Arm64
) {
694 process
= new ArmLinuxProcess64(this, obj_file
,
695 obj_file
->getArch());
697 process
= new ArmLinuxProcess32(this, obj_file
,
698 obj_file
->getArch());
701 case ObjectFile::FreeBSD
:
702 if (arch
== ObjectFile::Arm64
) {
703 process
= new ArmFreebsdProcess64(this, obj_file
,
704 obj_file
->getArch());
706 process
= new ArmFreebsdProcess32(this, obj_file
,
707 obj_file
->getArch());
710 case ObjectFile::LinuxArmOABI
:
711 fatal("M5 does not support ARM OABI binaries. Please recompile with an"
714 fatal("Unknown/unsupported operating system.");
716 #elif THE_ISA == POWER_ISA
717 if (obj_file
->getArch() != ObjectFile::Power
)
718 fatal("Object file architecture does not match compiled ISA (Power).");
719 switch (obj_file
->getOpSys()) {
720 case ObjectFile::UnknownOpSys
:
721 warn("Unknown operating system; assuming Linux.");
723 case ObjectFile::Linux
:
724 process
= new PowerLinuxProcess(this, obj_file
);
728 fatal("Unknown/unsupported operating system.");
730 #elif THE_ISA == RISCV_ISA
731 if (obj_file
->getArch() != ObjectFile::Riscv
)
732 fatal("Object file architecture does not match compiled ISA (RISCV).");
733 switch (obj_file
->getOpSys()) {
734 case ObjectFile::UnknownOpSys
:
735 warn("Unknown operating system; assuming Linux.");
737 case ObjectFile::Linux
:
738 process
= new RiscvLinuxProcess(this, obj_file
);
741 fatal("Unknown/unsupported operating system.");
744 #error "THE_ISA not set"
748 fatal("Unknown error creating process object.");