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