summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorAndreas Sandberg <andreas.sandberg@arm.com>2018-02-08 20:13:13 +0000
committerAndreas Sandberg <andreas.sandberg@arm.com>2018-02-19 14:24:46 +0000
commit6039da55d87fb27b149ac3da0ebce41bb55a3bee (patch)
tree0accdc76afa3790eb04d878d89e5f5158fd25572 /src
parent80427ea030b521779521f57b092bc6b4afc86ab2 (diff)
downloadgem5-6039da55d87fb27b149ac3da0ebce41bb55a3bee.tar.xz
arch-arm: Add aarch64 semihosting support
Add basic support for Arm Semihosting 2.0 simulation calls [1]. These calls let the guest system call a simulator or debugger to request OS-like support when running bare metal code. With the exception of SYS_SYSTEM, this implementation supports all of the Semihosting 2.0 specification in aarch64. [1] https://developer.arm.com/docs/100863/latest/preface Change-Id: I08c153c18a4a4fb9f95d318e2a029724935192a7 Signed-off-by: Andreas Sandberg <andreas.sandberg@arm.com> Reviewed-by: Jack Travaglini <giacomo.travaglini@arm.com> Reviewed-by: Nikos Nikoleris <nikos.nikoleris@arm.com> Reviewed-on: https://gem5-review.googlesource.com/8147 Reviewed-by: Giacomo Travaglini <giacomo.travaglini@arm.com>
Diffstat (limited to 'src')
-rw-r--r--src/arch/arm/ArmSemihosting.py56
-rw-r--r--src/arch/arm/ArmSystem.py4
-rw-r--r--src/arch/arm/SConscript3
-rw-r--r--src/arch/arm/isa/formats/aarch64.isa4
-rw-r--r--src/arch/arm/isa/insts/misc64.isa21
-rw-r--r--src/arch/arm/semihosting.cc946
-rw-r--r--src/arch/arm/semihosting.hh348
-rw-r--r--src/arch/arm/system.cc24
-rw-r--r--src/arch/arm/system.hh21
9 files changed, 1423 insertions, 4 deletions
diff --git a/src/arch/arm/ArmSemihosting.py b/src/arch/arm/ArmSemihosting.py
new file mode 100644
index 000000000..1da4c4988
--- /dev/null
+++ b/src/arch/arm/ArmSemihosting.py
@@ -0,0 +1,56 @@
+# Copyright (c) 2018 ARM Limited
+# All rights reserved.
+#
+# The license below extends only to copyright in the software and shall
+# not be construed as granting a license to any other intellectual
+# property including but not limited to intellectual property relating
+# to a hardware implementation of the functionality of the software
+# licensed hereunder. You may use the software subject to the license
+# terms below provided that you ensure that this notice is replicated
+# unmodified and in its entirety in all distributions of the software,
+# modified or unmodified, in source code or in binary form.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met: redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer;
+# redistributions in binary form must reproduce the above copyright
+# notice, this list of conditions and the following disclaimer in the
+# documentation and/or other materials provided with the distribution;
+# neither the name of the copyright holders nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+# Authors: Andreas Sandberg
+
+from m5.params import *
+from m5.SimObject import *
+
+from Serial import SerialDevice
+from Terminal import Terminal
+
+class ArmSemihosting(SimObject):
+ type = 'ArmSemihosting'
+ cxx_header = "arch/arm/semihosting.hh"
+
+ cmd_line = Param.String("", "Command line to report to guest");
+
+ mem_reserve = Param.MemorySize("32MB",
+ "Amount of memory to reserve at the start of the address map. This "
+ "memory won't be used by the heap reported to an application.");
+ stack_size = Param.MemorySize("32MB", "Application stack size");
+
+ time = Param.Time('01/01/2009',
+ "System time to use ('Now' for actual time)")
diff --git a/src/arch/arm/ArmSystem.py b/src/arch/arm/ArmSystem.py
index 568747725..ec44331dd 100644
--- a/src/arch/arm/ArmSystem.py
+++ b/src/arch/arm/ArmSystem.py
@@ -41,6 +41,7 @@ from m5.SimObject import *
from m5.util.fdthelper import *
from System import System
+from ArmSemihosting import ArmSemihosting
class ArmMachineType(Enum):
map = {
@@ -79,6 +80,9 @@ class ArmSystem(System):
have_large_asid_64 = Param.Bool(False,
"True if ASID is 16 bits in AArch64 (ARMv8)")
+ semihosting = Param.ArmSemihosting(NULL,
+ "Enable support for the Arm semihosting by settings this parameter")
+
m5ops_base = Param.Addr(0,
"Base of the 64KiB PA range used for memory-mapped m5ops. Set to 0 "
"to disable.")
diff --git a/src/arch/arm/SConscript b/src/arch/arm/SConscript
index 3b68fb647..4d86eaa82 100644
--- a/src/arch/arm/SConscript
+++ b/src/arch/arm/SConscript
@@ -75,6 +75,7 @@ if env['TARGET_ISA'] == 'arm':
Source('pmu.cc')
Source('process.cc')
Source('remote_gdb.cc')
+ Source('semihosting.cc')
Source('stacktrace.cc')
Source('system.cc')
Source('table_walker.cc')
@@ -87,11 +88,13 @@ if env['TARGET_ISA'] == 'arm':
SimObject('ArmInterrupts.py')
SimObject('ArmISA.py')
SimObject('ArmNativeTrace.py')
+ SimObject('ArmSemihosting.py')
SimObject('ArmSystem.py')
SimObject('ArmTLB.py')
SimObject('ArmPMU.py')
DebugFlag('Arm')
+ DebugFlag('Semihosting')
DebugFlag('Decoder', "Instructions returned by the predecoder")
DebugFlag('Faults', "Trace Exceptions, interrupts, svc/swi")
DebugFlag('PMUVerbose', "Performance Monitor")
diff --git a/src/arch/arm/isa/formats/aarch64.isa b/src/arch/arm/isa/formats/aarch64.isa
index 0cb8e9c66..f39a1a5b9 100644
--- a/src/arch/arm/isa/formats/aarch64.isa
+++ b/src/arch/arm/isa/formats/aarch64.isa
@@ -1,4 +1,4 @@
-// Copyright (c) 2011-2016 ARM Limited
+// Copyright (c) 2011-2018 ARM Limited
// All rights reserved
//
// The license below extends only to copyright in the software and shall
@@ -256,7 +256,7 @@ namespace Aarch64
case 0x04:
return new Brk64(machInst);
case 0x08:
- return new FailUnimplemented("hlt", machInst);
+ return new Hlt64(machInst);
case 0x15:
return new FailUnimplemented("dcps1", machInst);
case 0x16:
diff --git a/src/arch/arm/isa/insts/misc64.isa b/src/arch/arm/isa/insts/misc64.isa
index 2483b75b0..faac5cfcf 100644
--- a/src/arch/arm/isa/insts/misc64.isa
+++ b/src/arch/arm/isa/insts/misc64.isa
@@ -1,6 +1,6 @@
// -*- mode:c++ -*-
-// Copyright (c) 2011-2013, 2016-2017 ARM Limited
+// Copyright (c) 2011-2013, 2016-2018 ARM Limited
// All rights reserved
//
// The license below extends only to copyright in the software and shall
@@ -174,4 +174,23 @@ let {{
header_output += BasicDeclare.subst(brkIop)
decoder_output += BasicConstructor64.subst(brkIop)
exec_output += BasicExecute.subst(brkIop)
+
+ hltCode = '''
+ ThreadContext *tc = xc->tcBase();
+ if (ArmSystem::haveSemihosting(tc) && bits(machInst, 20, 5) == 0xF000) {
+ X0 = ArmSystem::callSemihosting64(tc, X0 & mask(32), X1);
+ } else {
+ // HLT instructions aren't implemented, so treat them as undefined
+ // instructions.
+ fault = std::make_shared<UndefinedInstruction>(
+ machInst, false, mnemonic);
+ }
+
+ '''
+
+ hltIop = InstObjParams("hlt", "Hlt64", "ArmStaticInst",
+ hltCode, ["IsNonSpeculative"])
+ header_output += BasicDeclare.subst(hltIop)
+ decoder_output += BasicConstructor64.subst(hltIop)
+ exec_output += BasicExecute.subst(hltIop)
}};
diff --git a/src/arch/arm/semihosting.cc b/src/arch/arm/semihosting.cc
new file mode 100644
index 000000000..98b50f468
--- /dev/null
+++ b/src/arch/arm/semihosting.cc
@@ -0,0 +1,946 @@
+/*
+ * Copyright (c) 2018 ARM Limited
+ * All rights reserved
+ *
+ * The license below extends only to copyright in the software and shall
+ * not be construed as granting a license to any other intellectual
+ * property including but not limited to intellectual property relating
+ * to a hardware implementation of the functionality of the software
+ * licensed hereunder. You may use the software subject to the license
+ * terms below provided that you ensure that this notice is replicated
+ * unmodified and in its entirety in all distributions of the software,
+ * modified or unmodified, in source code or in binary form.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met: redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer;
+ * redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution;
+ * neither the name of the copyright holders nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Authors: Andreas Sandberg
+ */
+
+#include "arch/arm/semihosting.hh"
+
+#include <cstdio>
+
+#include "arch/arm/utility.hh"
+#include "base/logging.hh"
+#include "base/time.hh"
+#include "debug/Semihosting.hh"
+#include "dev/serial/serial.hh"
+#include "mem/physical.hh"
+#include "mem/port_proxy.hh"
+#include "params/ArmSemihosting.hh"
+#include "sim/byteswap.hh"
+#include "sim/sim_exit.hh"
+#include "sim/system.hh"
+
+const std::map<uint32_t, ArmSemihosting::SemiCall> ArmSemihosting::calls{
+ { 0x01, { "SYS_OPEN", &ArmSemihosting::callOpen, 3, 3 } },
+ { 0x02, { "SYS_CLOSE", &ArmSemihosting::callClose, 1, 1 } },
+
+ // Write(C|0) are special since we want to read the character
+ // manually. We therefore declare them as having 0 params.
+ { 0x03, { "SYS_WRITEC", &ArmSemihosting::callWriteC, 0, 0 } },
+ { 0x04, { "SYS_WRITE0", &ArmSemihosting::callWrite0, 1, 1 } },
+
+ { 0x05, { "SYS_WRITE", &ArmSemihosting::callWrite, 3, 3 } },
+ { 0x06, { "SYS_READ", &ArmSemihosting::callRead, 3, 3 } },
+ { 0x07, { "SYS_READC", &ArmSemihosting::callReadC, 0, 0 } },
+ { 0x08, { "SYS_ISERROR", &ArmSemihosting::callIsError, 1, 1 } },
+ { 0x09, { "SYS_ISTTY", &ArmSemihosting::callIsTTY, 1, 1 } },
+ { 0x0A, { "SYS_SEEK", &ArmSemihosting::callSeek, 2, 2 } },
+ { 0x0C, { "SYS_FLEN", &ArmSemihosting::callFLen, 1, 1 } },
+ { 0x0D, { "SYS_TMPNAM", &ArmSemihosting::callTmpNam, 3, 3 } },
+ { 0x0E, { "SYS_REMOVE", &ArmSemihosting::callRemove, 2, 2} },
+ { 0x0F, { "SYS_RENAME", &ArmSemihosting::callRename, 4, 4} },
+ { 0x10, { "SYS_CLOCK", &ArmSemihosting::callClock, 0, 0} },
+ { 0x11, { "SYS_TIME", &ArmSemihosting::callTime, 0, 0} },
+ { 0x12, { "SYS_SYSTEM", &ArmSemihosting::callSystem, 2, 2} },
+ { 0x13, { "SYS_ERRNO", &ArmSemihosting::callErrno, 0, 0 } },
+ { 0x15, { "SYS_GET_CMDLINE", &ArmSemihosting::callGetCmdLine, 1, 1} },
+ { 0x16, { "SYS_HEAPINFO", &ArmSemihosting::callHeapInfo, 1, 1} },
+
+ // Exit is special and requires custom handling in aarch32.
+ { 0x18, { "SYS_EXIT", &ArmSemihosting::callExit, 0, 2 } },
+ { 0x20, { "SYS_EXIT_EXTENDED", &ArmSemihosting::callExitExtended, 2, 2 } },
+
+ { 0x30, { "SYS_ELAPSED", &ArmSemihosting::callElapsed, 0, 0 } },
+ { 0x31, { "SYS_TICKFREQ", &ArmSemihosting::callTickFreq, 0, 0 } },
+};
+
+const std::vector<const char *> ArmSemihosting::fmodes{
+ "r", "rb", "r+", "r+b",
+ "w", "wb", "w+", "w+b",
+ "a", "ab", "a+", "a+b",
+};
+
+const std::map<uint64_t, const char *> ArmSemihosting::exitCodes{
+ { 0x20000, "semi:ADP_Stopped_BranchThroughZero" },
+ { 0x20001, "semi:ADP_Stopped_UndefinedInstr" },
+ { 0x20002, "semi:ADP_Stopped_SoftwareInterrupt" },
+ { 0x20003, "semi:ADP_Stopped_PrefetchAbort" },
+ { 0x20004, "semi:ADP_Stopped_DataAbort" },
+ { 0x20005, "semi:ADP_Stopped_AddressException" },
+ { 0x20006, "semi:ADP_Stopped_IRQ" },
+ { 0x20007, "semi:ADP_Stopped_FIQ" },
+
+ { 0x20020, "semi:ADP_Stopped_BreakPoint" },
+ { 0x20021, "semi:ADP_Stopped_WatchPoint" },
+ { 0x20022, "semi:ADP_Stopped_StepComplete" },
+ { 0x20023, "semi:ADP_Stopped_RunTimeErrorUnknown" },
+ { 0x20024, "semi:ADP_Stopped_InternalError" },
+ { 0x20025, "semi:ADP_Stopped_UserInterruption" },
+ { 0x20026, "semi:ADP_Stopped_ApplicationExit" },
+ { 0x20027, "semi:ADP_Stopped_StackOverflow" },
+ { 0x20028, "semi:ADP_Stopped_DivisionByZero" },
+ { 0x20029, "semi:ADP_Stopped_DivisionByZero" },
+};
+
+
+const std::vector<uint8_t> ArmSemihosting::features{
+ 0x53, 0x48, 0x46, 0x42, // Magic
+ 0x3, // EXT_EXIT_EXTENDED, EXT_STDOUT_STDERR
+};
+
+ArmSemihosting::ArmSemihosting(const ArmSemihostingParams *p)
+ : SimObject(p),
+ cmdLine(p->cmd_line),
+ memReserve(p->mem_reserve),
+ stackSize(p->stack_size),
+ timeBase([p]{ struct tm t = p->time; return mkutctime(&t); }()),
+ tickShift(calcTickShift()),
+ semiErrno(0)
+{
+ // Create an empty place-holder file for position 0 as semi-hosting
+ // calls typically expect non-zero file handles.
+ files.push_back(nullptr);
+
+ if (tickShift > 0)
+ inform("Semihosting: Shifting elapsed ticks by %i bits.",
+ tickShift);
+}
+
+uint64_t
+ArmSemihosting::call64(ThreadContext *tc, uint32_t op, uint64_t param)
+{
+ const SemiCall *call = getCall(op, true);
+ if (!call) {
+ warn("Unknown aarch64 semihosting call: op = 0x%x, param = 0x%x",
+ op, param);
+
+ return (uint64_t)-1;
+ } else if (!call->implemented64()) {
+ warn("Unimplemented aarch64 semihosting call: "
+ "%s (op = 0x%x, param = 0x%x)",
+ call->name, op, param);
+
+ return (uint64_t)-1;
+ }
+
+ std::vector<uint64_t> argv(call->argc64 + 1);
+ PortProxy &proxy = tc->getPhysProxy();
+ ByteOrder endian = ArmISA::byteOrder(tc);
+
+ DPRINTF(Semihosting, "Semihosting call64: %s(0x%x)\n", call->name, param);
+ argv[0] = param;
+ for (int i = 0; i < call->argc64; ++i) {
+ argv[i + 1] = proxy.readGtoH<uint64_t>(param + i * 8, endian);
+ DPRINTF(Semihosting, "\t: 0x%x\n", argv[i + 1]);
+ }
+
+ auto ret_errno = (this->*call->call)(tc, true, argv);
+ semiErrno = ret_errno.second;
+ DPRINTF(Semihosting, "\t ->: 0x%x, %i\n",
+ ret_errno.first, ret_errno.second);
+ return ret_errno.first;
+}
+
+uint32_t
+ArmSemihosting::call32(ThreadContext *tc, uint32_t op, uint32_t param)
+{
+ const SemiCall *call = getCall(op, false);
+ if (!call) {
+ warn("Unknown aarch32 semihosting call: op = 0x%x, param = 0x%x",
+ op, param);
+
+ return (uint32_t)-1;
+ } else if (!call->implemented32()) {
+ warn("Unimplemented aarch32 semihosting call: "
+ "%s (op = 0x%x, param = 0x%x)",
+ call->name, op, param);
+
+ return (uint32_t)-1;
+ }
+
+ std::vector<uint64_t> argv(call->argc32 + 1);
+ PortProxy &proxy = tc->getPhysProxy();
+ ByteOrder endian = ArmISA::byteOrder(tc);
+
+ DPRINTF(Semihosting, "Semihosting call32: %s(0x%x)\n", call->name, param);
+ argv[0] = param;
+ for (int i = 0; i < call->argc32; ++i) {
+ argv[i + 1] = proxy.readGtoH<uint32_t>(param + i * 4, endian);
+ DPRINTF(Semihosting, "\t: 0x%x\n", argv[i + 1]);
+ }
+
+ auto ret_errno = (this->*call->call)(tc, false, argv);
+ semiErrno = ret_errno.second;
+ DPRINTF(Semihosting, "\t ->: 0x%x, %i\n",
+ ret_errno.first, ret_errno.second);
+ return ret_errno.first;
+}
+
+void
+ArmSemihosting::serialize(CheckpointOut &cp) const
+{
+ SERIALIZE_SCALAR(semiErrno);
+
+ paramOut(cp, "num_files", files.size());
+ for (int i = 0; i < files.size(); i++) {
+ // File closed?
+ if (!files[i])
+ continue;
+
+ files[i]->serializeSection(cp, csprintf("file%i", i));
+ }
+}
+
+void
+ArmSemihosting::unserialize(CheckpointIn &cp)
+{
+ UNSERIALIZE_SCALAR(semiErrno);
+
+ size_t num_files;
+ paramIn(cp, "num_files", num_files);
+ files.resize(num_files);
+ for (int i = 0; i < num_files; i++)
+ files[i] = FileBase::create(*this, cp, csprintf("file%i", i));
+}
+
+std::string
+ArmSemihosting::readString(ThreadContext *tc, Addr ptr, size_t len)
+{
+ std::vector<char> buf(len + 1);
+
+ buf[len] = '\0';
+ tc->getPhysProxy().readBlob(ptr, (uint8_t *)buf.data(), len);
+
+ return std::string(buf.data());
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callOpen(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ const Addr name_base = argv[1];
+ const char *mode = argv[2] < fmodes.size() ? fmodes[argv[2]] : nullptr;
+ const Addr name_size = argv[3];
+
+ DPRINTF(Semihosting, "Semihosting SYS_OPEN(0x%x, %i[%s], %i)\n",
+ name_base, argv[2], mode ? mode : "-", name_size);
+ if (!mode || !name_base)
+ return retError(EINVAL);
+
+ std::string fname = readString(tc, name_base, name_size);
+
+ std::unique_ptr<ArmSemihosting::FileBase> file =
+ FileBase::create(*this, fname, mode);
+ int64_t ret = file->open();
+ DPRINTF(Semihosting, "Semihosting SYS_OPEN(\"%s\", %i[%s]): %i\n",
+ fname, argv[2], mode, ret);
+ if (ret < 0) {
+ return retError(-ret);
+ } else {
+ files.push_back(std::move(file));
+ return retOK(files.size() - 1);
+ }
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callClose(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ if (argv[1] > files.size()) {
+ DPRINTF(Semihosting, "Semihosting SYS_CLOSE(%i): Illegal file\n");
+ return retError(EBADF);
+ }
+
+ std::unique_ptr<FileBase> &file = files[argv[1]];
+ int64_t error = file->close();
+ DPRINTF(Semihosting, "Semihosting SYS_CLOSE(%i[%s]): %i\n",
+ argv[1], file->fileName(), error);
+ if (error < 0) {
+ return retError(-error);
+ } else {
+ // Zap the pointer and free the entry in the file table as
+ // well.
+ files[argv[1]].reset();
+ return retOK(0);
+ }
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callWriteC(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ const char c = tc->getPhysProxy().read<char>(argv[0]);
+
+ DPRINTF(Semihosting, "Semihosting SYS_WRITEC('%c')\n", c);
+ std::cout.put(c);
+
+ return retOK(0);
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callWrite0(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ DPRINTF(Semihosting, "Semihosting SYS_WRITE0(...)\n");
+ PortProxy &proxy = tc->getPhysProxy();
+ for (Addr addr = (Addr)argv[0]; ; ++addr) {
+ char data = proxy.read<char>(addr);
+ if (data == 0)
+ break;
+
+ std::cout.put(data);
+ }
+
+ return retOK(0);
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callWrite(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ if (argv[1] > files.size() || !files[argv[1]])
+ return RetErrno(argv[3], EBADF);
+
+ std::vector<uint8_t> buffer(argv[3]);
+ tc->getPhysProxy().readBlob(argv[2], buffer.data(), buffer.size());
+
+ int64_t ret = files[argv[1]]->write(buffer.data(), buffer.size());
+ if (ret < 0) {
+ // No bytes written (we're returning the number of bytes not
+ // written)
+ return RetErrno(argv[3], -ret);
+ } else {
+ // Return the number of bytes not written
+ return RetErrno(argv[3] - ret, 0);
+ }
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callRead(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ if (argv[1] > files.size() || !files[argv[1]])
+ return RetErrno(argv[3], EBADF);
+
+ std::vector<uint8_t> buffer(argv[3]);
+ int64_t ret = files[argv[1]]->read(buffer.data(), buffer.size());
+ if (ret < 0) {
+ return RetErrno(argv[3], -ret);
+ } else {
+ panic_if(ret > buffer.size(), "Read longer than buffer size.");
+
+ tc->getPhysProxy().writeBlob(argv[2], buffer.data(), ret);
+
+ // Return the number of bytes not written
+ return retOK(argv[3] - ret);
+ }
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callReadC(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ return retOK((char)std::cin.get());
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callIsError(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ // Sign extend from a 32 bit integer in aarch32 since the argument
+ // reader zero extends to a uint64_t.
+ const int64_t status = (int64_t)(aarch64 ? argv[1] :sext<32>(argv[1]));
+ // Assume there was an error if the status value is negative.
+ return retOK(status < 0 ? 1 : 0);
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callIsTTY(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ if (argv[1] > files.size() || !files[argv[1]])
+ return retError(EBADF);
+
+ int64_t ret = files[argv[1]]->isTTY();
+ if (ret < 0) {
+ return retError(-ret);
+ } else {
+ return retOK(ret ? 1 : 0);
+ }
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callSeek(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ if (argv[1] > files.size() || !files[argv[1]])
+ return retError(EBADF);
+
+ int64_t ret = files[argv[1]]->seek(argv[2]);
+ if (ret < 0) {
+ return retError(-ret);
+ } else {
+ return retOK(0);
+ }
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callFLen(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ if (argv[1] > files.size() || !files[argv[1]])
+ return retError(EBADF);
+
+ int64_t ret = files[argv[1]]->isTTY();
+ if (ret < 0) {
+ return retError(-ret);
+ } else {
+ return retOK(0);
+ }
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callTmpNam(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ const Addr guest_buf = argv[1];
+ //const uint64_t id = argv[2];
+ const uint64_t max_len = argv[3];
+
+ std::vector<char> buf(L_tmpnam);
+ char *path = tmpnam(buf.data());
+ if (!path)
+ return retError(EINVAL);
+
+ const size_t path_len = strlen(path);
+ if (path_len >= max_len)
+ return retError(ENOSPC);
+
+ tc->getPhysProxy().writeBlob(
+ guest_buf, (const uint8_t *)path, path_len + 1);
+ return retOK(0);
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callRemove(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ std::string fname = readString(tc, argv[1], argv[2]);
+
+ if (remove(fname.c_str()) != 0) {
+ return retError(errno);
+ } else {
+ return retOK(0);
+ }
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callRename(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ std::string from = readString(tc, argv[1], argv[2]);
+ std::string to = readString(tc, argv[3], argv[4]);
+
+ if (rename(from.c_str(), to.c_str()) != 0) {
+ return retError(errno);
+ } else {
+ return retOK(0);
+ }
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callClock(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ return retOK(curTick() / (SimClock::Int::s / 100));
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callTime(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ return retOK(timeBase + round(curTick() / SimClock::Float::s));
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callSystem(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ const std::string cmd = readString(tc, argv[1], argv[2]);
+ warn("Semihosting: SYS_SYSTEM not implemented. Guest tried to run: %s\n",
+ cmd);
+ return retError(EINVAL);
+
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callErrno(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ // Preserve errno by returning it in errno as well.
+ return RetErrno(semiErrno, semiErrno);
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callGetCmdLine(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ if (cmdLine.size() + 1 < argv[2]) {
+ PortProxy &proxy = tc->getPhysProxy();
+ ByteOrder endian = ArmISA::byteOrder(tc);
+ proxy.writeBlob(
+ (Addr)argv[1],
+ (const uint8_t *)cmdLine.c_str(), cmdLine.size() + 1);
+
+ if (aarch64)
+ proxy.writeHtoG<uint64_t>(argv[0] + 1 * 8, cmdLine.size(), endian);
+ else
+ proxy.writeHtoG<uint32_t>(argv[0] + 1 * 4, cmdLine.size(), endian);
+ return retOK(0);
+ } else {
+ return retError(0);
+ }
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callHeapInfo(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ const PhysicalMemory &phys = tc->getSystemPtr()->getPhysMem();
+ const AddrRangeList memories = phys.getConfAddrRanges();
+ fatal_if(memories.size() < 1, "No memories reported from System");
+ warn_if(memories.size() > 1, "Multiple physical memory ranges available. "
+ "Using first range heap/stack.");
+ const AddrRange memory = *memories.begin();
+ const Addr mem_start = memory.start() + memReserve;
+ Addr mem_end = memory.end();
+
+ // Make sure that 32-bit guests can access their memory.
+ if (!aarch64) {
+ const Addr phys_max = (1ULL << 32) - 1;
+ panic_if(mem_start > phys_max,
+ "Physical memory out of range for a 32-bit guest.");
+ if (mem_end > phys_max) {
+ warn("Some physical memory out of range for a 32-bit guest.");
+ mem_end = phys_max;
+ }
+ }
+
+ fatal_if(mem_start + stackSize >= mem_end,
+ "Physical memory too small to fit desired stack and a heap.");
+
+ const Addr heap_base = mem_start;
+ const Addr heap_limit = mem_end - stackSize + 1;
+ const Addr stack_base = (mem_end + 1) & ~0x7ULL; // 8 byte stack alignment
+ const Addr stack_limit = heap_limit;
+
+
+ inform("Reporting heap/stack info to guest:\n"
+ "\tHeap base: 0x%x\n"
+ "\tHeap limit: 0x%x\n"
+ "\tStack base: 0x%x\n"
+ "\tStack limit: 0x%x\n",
+ heap_base, heap_limit, stack_base, stack_limit);
+
+ Addr base = argv[1];
+ PortProxy &proxy = tc->getPhysProxy();
+ ByteOrder endian = ArmISA::byteOrder(tc);
+ if (aarch64) {
+ proxy.writeHtoG<uint64_t>(base + 0 * 8, heap_base, endian);
+ proxy.writeHtoG<uint64_t>(base + 1 * 8, heap_limit, endian);
+ proxy.writeHtoG<uint64_t>(base + 2 * 8, stack_base, endian);
+ proxy.writeHtoG<uint64_t>(base + 3 * 8, stack_limit, endian);
+ } else {
+ proxy.writeHtoG<uint32_t>(base + 0 * 4, heap_base, endian);
+ proxy.writeHtoG<uint32_t>(base + 1 * 4, heap_limit, endian);
+ proxy.writeHtoG<uint32_t>(base + 2 * 4, stack_base, endian);
+ proxy.writeHtoG<uint32_t>(base + 3 * 4, stack_limit, endian);
+ }
+
+ return retOK(0);
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callExit(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ if (aarch64) {
+ semiExit(argv[1], argv[2]);
+ } else {
+ semiExit(argv[0], 0);
+ }
+
+ return retOK(0);
+}
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callExitExtended(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ semiExit(argv[1], argv[2]);
+
+ return retOK(0);
+}
+
+void
+ArmSemihosting::semiExit(uint64_t code, uint64_t subcode)
+{
+ auto it = exitCodes.find(code);
+ if (it != exitCodes.end()) {
+ exitSimLoop(it->second, subcode);
+ } else {
+ exitSimLoop(csprintf("semi:0x%x", code), subcode);
+ }
+}
+
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callElapsed(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ PortProxy &proxy = tc->getPhysProxy();
+ ByteOrder endian = ArmISA::byteOrder(tc);
+ const uint64_t tick = semiTick(curTick());
+
+ if (aarch64) {
+ proxy.writeHtoG<uint64_t>(argv[0], tick, endian);
+ } else {
+ proxy.writeHtoG<uint32_t>(argv[0] + 0 * 4, tick, endian);
+ proxy.writeHtoG<uint32_t>(argv[0] + 1 * 4, tick >> 32, endian);
+ }
+
+ return retOK(0);
+}
+
+
+ArmSemihosting::RetErrno
+ArmSemihosting::callTickFreq(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv)
+{
+ return retOK(semiTick(SimClock::Frequency));
+}
+
+const ArmSemihosting::SemiCall *
+ArmSemihosting::getCall(uint32_t op, bool aarch64)
+{
+ auto it = calls.find(op);
+ if (it == calls.end())
+ return nullptr;
+ else {
+ return &it->second;
+ }
+}
+
+std::unique_ptr<ArmSemihosting::FileBase>
+ArmSemihosting::FileBase::create(
+ ArmSemihosting &parent, const std::string &fname, const char *mode)
+{
+ std::unique_ptr<FileBase> file;
+ if (fname == ":semihosting-features") {
+ file.reset(new FileFeatures(parent, fname.c_str(), mode));
+ } else {
+ file.reset(new File(parent, fname.c_str(), mode));
+ }
+
+ return file;
+}
+
+std::unique_ptr<ArmSemihosting::FileBase>
+ArmSemihosting::FileBase::create(ArmSemihosting &parent,
+ CheckpointIn &cp, const std::string &sec)
+{
+ std::unique_ptr<FileBase> file;
+ ScopedCheckpointSection _sec(cp, sec);
+
+ // Was the file open when the checkpoint was created?
+ if (!cp.sectionExists(Serializable::currentSection()))
+ return file;
+
+ std::string fname, mode;
+ paramIn(cp, "name", fname);
+ paramIn(cp, "mode", mode);
+ file = create(parent, fname, mode.c_str());
+ assert(file);
+ file->unserialize(cp);
+
+ return file;
+}
+
+void
+ArmSemihosting::FileBase::serialize(CheckpointOut &cp) const
+{
+ paramOut(cp, "name", _name);
+ SERIALIZE_SCALAR(mode);
+}
+
+void
+ArmSemihosting::FileBase::unserialize(CheckpointIn &cp)
+{
+ /* Unserialization of name and mode happens in
+ * ArmSemihosting::FileBase::create() */
+}
+
+int64_t
+ArmSemihosting::FileBase::read(uint8_t *buffer, uint64_t size)
+{
+ return -EINVAL;
+}
+
+int64_t
+ArmSemihosting::FileBase::write(const uint8_t *buffer, uint64_t size)
+{
+ return -EINVAL;
+}
+
+int64_t
+ArmSemihosting::FileBase::seek(uint64_t pos)
+{
+ return -EINVAL;
+}
+
+int64_t
+ArmSemihosting::FileBase::flen()
+{
+ return -EINVAL;
+}
+
+
+ArmSemihosting::FileFeatures::FileFeatures(
+ ArmSemihosting &_parent, const char *_name, const char *_mode)
+ : FileBase(_parent, _name, _mode)
+{
+}
+
+int64_t
+ArmSemihosting::FileFeatures::read(uint8_t *buffer, uint64_t size)
+{
+ int64_t len = 0;
+
+ for (; pos < size && pos < ArmSemihosting::features.size(); pos++)
+ buffer[len++] = ArmSemihosting::features[pos];
+
+ return len;
+}
+
+int64_t
+ArmSemihosting::FileFeatures::seek(uint64_t _pos)
+{
+ if (_pos < ArmSemihosting::features.size()) {
+ pos = _pos;
+ return 0;
+ } else {
+ return -ENXIO;
+ }
+}
+
+void
+ArmSemihosting::FileFeatures::serialize(CheckpointOut &cp) const
+{
+ FileBase::serialize(cp);
+ SERIALIZE_SCALAR(pos);
+}
+
+void
+ArmSemihosting::FileFeatures::unserialize(CheckpointIn &cp)
+{
+ FileBase::unserialize(cp);
+ UNSERIALIZE_SCALAR(pos);
+}
+
+
+
+ArmSemihosting::File::File(ArmSemihosting &_parent,
+ const char *_name, const char *_perms)
+ : FileBase(_parent, _name, _perms),
+ file(nullptr)
+{
+}
+
+ArmSemihosting::File::~File()
+{
+ if (file)
+ close();
+}
+
+int64_t
+ArmSemihosting::File::openImpl(bool in_cpt)
+{
+ panic_if(file, "Trying to open an already open file.\n");
+
+ if (_name == ":tt") {
+ if (mode[0] == 'r') {
+ file = stdin;
+ } else if (mode[0] == 'w') {
+ file = stdout;
+ } else if (mode[0] == 'a') {
+ file = stderr;
+ } else {
+ warn("Unknown file mode for the ':tt' special file");
+ return -EINVAL;
+ }
+ } else {
+ std::string real_mode(this->mode);
+ // Avoid truncating the file if we are restoring from a
+ // checkpoint.
+ if (in_cpt && real_mode[0] == 'w')
+ real_mode[0] = 'a';
+
+ file = fopen(_name.c_str(), real_mode.c_str());
+ }
+
+ return file ? 0 : -errno;
+}
+
+int64_t
+ArmSemihosting::File::close()
+{
+ panic_if(!file, "Trying to close an already closed file.\n");
+
+ if (needClose()) {
+ fclose(file);
+ }
+ file = nullptr;
+
+ return 0;
+}
+
+bool
+ArmSemihosting::File::isTTY() const
+{
+ return file == stdout || file == stderr || file == stdin;
+}
+
+int64_t
+ArmSemihosting::File::read(uint8_t *buffer, uint64_t size)
+{
+ panic_if(!file, "Trying to read from a closed file");
+
+ size_t ret = fread(buffer, 1, size, file);
+ if (ret == 0) {
+ // Error or EOF. Assume errors are due to invalid file
+ // operations (e.g., reading a write-only stream).
+ return ferror(file) ? -EINVAL : 0;
+ } else {
+ return ret;
+ }
+}
+
+int64_t
+ArmSemihosting::File::write(const uint8_t *buffer, uint64_t size)
+{
+ panic_if(!file, "Trying to write to a closed file");
+
+
+ size_t ret = fwrite(buffer, 1, size, file);
+ if (ret == 0) {
+ // Assume errors are due to invalid file operations (e.g.,
+ // writing a read-only stream).
+ return -EINVAL;
+ } else {
+ return ret;
+ }
+}
+
+int64_t
+ArmSemihosting::File::seek(uint64_t _pos)
+{
+ panic_if(!file, "Trying to seek in a closed file");
+
+ errno = 0;
+ if (fseek(file, _pos, SEEK_SET) == 0)
+ return 0;
+ else
+ return -errno;
+}
+
+int64_t
+ArmSemihosting::File::flen()
+{
+ errno = 0;
+ long pos = ftell(file);
+ if (pos < 0)
+ return -errno;
+
+ if (fseek(file, 0, SEEK_END) != 0)
+ return -errno;
+
+ long len = ftell(file);
+ if (len < 0)
+ return -errno;
+
+ if (fseek(file, pos, SEEK_SET) != 0)
+ return -errno;
+
+ return len;
+}
+
+
+void
+ArmSemihosting::File::serialize(CheckpointOut &cp) const
+{
+ FileBase::serialize(cp);
+
+ if (!isTTY()) {
+ long pos = file ? ftell(file) : 0;
+ panic_if(pos < 0, "Failed to get file position.");
+ SERIALIZE_SCALAR(pos);
+ }
+}
+
+void
+ArmSemihosting::File::unserialize(CheckpointIn &cp)
+{
+ FileBase::unserialize(cp);
+
+ if (openImpl(true) < 0) {
+ fatal("Failed to open file: %s", _name);
+ }
+
+ if (!isTTY()) {
+ long pos = 0;
+ UNSERIALIZE_SCALAR(pos);
+ if (fseek(file, pos, SEEK_SET) != 0) {
+ fatal("Failed seek to current position (%i) in '%s'", pos, _name);
+ }
+ }
+}
+
+
+ArmSemihosting *
+ArmSemihostingParams::create()
+{
+ return new ArmSemihosting(this);
+}
diff --git a/src/arch/arm/semihosting.hh b/src/arch/arm/semihosting.hh
new file mode 100644
index 000000000..a4aa845a3
--- /dev/null
+++ b/src/arch/arm/semihosting.hh
@@ -0,0 +1,348 @@
+/*
+ * Copyright (c) 2018 ARM Limited
+ * All rights reserved
+ *
+ * The license below extends only to copyright in the software and shall
+ * not be construed as granting a license to any other intellectual
+ * property including but not limited to intellectual property relating
+ * to a hardware implementation of the functionality of the software
+ * licensed hereunder. You may use the software subject to the license
+ * terms below provided that you ensure that this notice is replicated
+ * unmodified and in its entirety in all distributions of the software,
+ * modified or unmodified, in source code or in binary form.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met: redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer;
+ * redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution;
+ * neither the name of the copyright holders nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Authors: Andreas Sandberg
+ */
+#ifndef __ARCH_ARM_SEMIHOSTING_HH__
+#define __ARCH_ARM_SEMIHOSTING_HH__
+
+#include <cstdio>
+#include <map>
+#include <memory>
+#include <utility>
+#include <vector>
+
+#include "sim/sim_object.hh"
+
+struct ArmSemihostingParams;
+class SerialDevice;
+class ThreadContext;
+
+/**
+ * Semihosting for AArch32 and AArch64
+ *
+ * This class implements the Arm semihosting interface. This interface
+ * allows baremetal code access service, such as IO, from the
+ * simulator. It is conceptually a simplified version of gem5's more
+ * general syscall emulation mode.
+ *
+ * Exits calls (SYS_EXIT, SYS_EXIT_EXTENDED) from the guest get
+ * translated into simualtion exits. Well-known exit codes are
+ * translated to messages on the form 'semi:ADP_.*' while unknown
+ * codes are returned in hex ('semi:0x..'). The subcode is reported in
+ * the gem5 exit event.
+ */
+class ArmSemihosting : public SimObject
+{
+ public:
+ ArmSemihosting(const ArmSemihostingParams *p);
+
+ /** Perform an Arm Semihosting call from aarch64 code. */
+ uint64_t call64(ThreadContext *tc, uint32_t op, uint64_t param);
+ /** Perform an Arm Semihosting call from aarch32 code. */
+ uint32_t call32(ThreadContext *tc, uint32_t op, uint32_t param);
+
+ public: // SimObject and related interfaces
+ void serialize(CheckpointOut &cp) const override;
+ void unserialize(CheckpointIn &cp) override;
+
+ protected: // Configuration
+ const std::string cmdLine;
+ const Addr memReserve;
+ const Addr stackSize;
+
+ /**
+ * Base time when the simulation started. This is used to
+ * calculate the time of date when the guest call SYS_TIME.
+ */
+ const time_t timeBase;
+
+ /** Number of bits to right shift gem5 ticks to fit in a uint32_t */
+ const unsigned tickShift;
+
+ protected: // Internal state
+ typedef uint64_t SemiErrno;
+ SemiErrno semiErrno;
+
+ protected: // File IO
+ /**
+ * Internal state for open files
+ *
+ * This class describes the internal state of a file opened
+ * through the semihosting interface.
+ *
+ * A file instance is normally created using one of the
+ * ArmSemihosting::FileBase::create() factory methods. These
+ * methods handle some the magic file names in the Arm Semihosting
+ * specification and instantiate the right implementation. For the
+ * same, when unserializing a checkpoint, the create method must
+ * be used to unserialize a new instance of a file descriptor.
+ */
+ class FileBase : public Serializable
+ {
+ public:
+ FileBase(ArmSemihosting &_parent, const char *name, const char *_mode)
+ : parent(_parent), _name(name), mode(_mode) {}
+ virtual ~FileBase() {};
+
+ FileBase() = delete;
+ FileBase(FileBase &) = delete;
+
+ static std::unique_ptr<FileBase> create(
+ ArmSemihosting &parent, const std::string &fname,
+ const char *mode);
+ static std::unique_ptr<FileBase> create(
+ ArmSemihosting &parent, CheckpointIn &cp, const std::string &sec);
+
+ void serialize(CheckpointOut &cp) const override;
+ void unserialize(CheckpointIn &cp) override;
+
+ const std::string &fileName() { return _name; }
+
+ public:
+ /** @{
+ * Semihosting file IO interfaces
+ *
+ * These interfaces implement common IO functionality in the
+ * Semihosting interface.
+ *
+ * All functions return a negative value that corresponds to a
+ * UNIX errno value when they fail and >=0 on success.
+ */
+
+ /**
+ * Open the the file.
+ *
+ * @return <0 on error (-errno), 0 on success.
+ */
+ virtual int64_t open() { return 0; }
+
+ /**
+ * Close the file.
+ *
+ * @return <0 on error (-errno), 0 on success.
+ */
+ virtual int64_t close() { return 0; }
+
+ /**
+ * Check if a file corresponds to a TTY device.
+ *
+ * @return True if the file is a TTY, false otherwise.
+ */
+ virtual bool isTTY() const { return false; }
+
+ /**
+ * Read data from file.
+ *
+ * @return <0 on error (-errno), bytes read on success (0 for EOF).
+ */
+ virtual int64_t read(uint8_t *buffer, uint64_t size);
+
+ /**
+ * Write data to file.
+ *
+ * @return <0 on error (-errno), bytes written on success.
+ */
+ virtual int64_t write(const uint8_t *buffer, uint64_t size);
+
+ /**
+ * Seek to an absolute position in the file.
+ *
+ * @param pos Byte offset from start of file.
+ * @return <0 on error (-errno), 0 on success.
+ */
+ virtual int64_t seek(uint64_t pos);
+
+ /**
+ * Get the length of a file in bytes.
+ *
+ * @return <0 on error (-errno), length on success
+ */
+ virtual int64_t flen();
+
+ /** @} */
+
+ protected:
+ ArmSemihosting &parent;
+ std::string _name;
+ std::string mode;
+ };
+
+ /** Implementation of the ':semihosting-features' magic file. */
+ class FileFeatures : public FileBase
+ {
+ public:
+ FileFeatures(ArmSemihosting &_parent,
+ const char *name, const char *mode);
+
+ void serialize(CheckpointOut &cp) const override;
+ void unserialize(CheckpointIn &cp) override;
+
+ int64_t read(uint8_t *buffer, uint64_t size) override;
+ int64_t seek(uint64_t pos) override;
+
+ protected:
+ size_t pos;
+ };
+
+ class File : public FileBase
+ {
+ public:
+ File(ArmSemihosting &_parent, const char *name, const char *mode);
+ ~File();
+
+ void serialize(CheckpointOut &cp) const override;
+ void unserialize(CheckpointIn &cp) override;
+
+ int64_t open() override { return openImpl(false); }
+ int64_t close() override;
+ bool isTTY() const override;
+ int64_t read(uint8_t *buffer, uint64_t size) override;
+ int64_t write(const uint8_t *buffer, uint64_t size) override;
+ int64_t seek(uint64_t pos) override;
+ int64_t flen() override;
+
+ protected:
+ int64_t openImpl(bool unserialize);
+ bool needClose() const { return !isTTY(); }
+
+ FILE *file;
+ };
+
+ std::vector<std::unique_ptr<FileBase>> files;
+
+ protected: // Helper functions
+ unsigned calcTickShift() const {
+ int msb = findMsbSet(SimClock::Frequency);
+ return msb > 31 ? msb - 31 : 0;
+ }
+ uint64_t semiTick(Tick tick) const {
+ return tick >> tickShift;
+ }
+ void semiExit(uint64_t code, uint64_t subcode);
+ std::string readString(ThreadContext *tc, Addr ptr, size_t len);
+
+ private:
+ typedef std::pair<uint64_t, SemiErrno> RetErrno;
+ static constexpr RetErrno retError(SemiErrno e) {
+ return RetErrno((uint64_t)-1, e);
+ }
+
+ static constexpr RetErrno retOK(uint64_t r) {
+ return RetErrno(r, 0);
+ }
+
+ /**
+ * Semihosting call information structure.
+ *
+ * This structure describes how a semi-hosting call is
+ * implemented. It contains debug information (e.g., the name of
+ * the call), a pointer to the implementation, and information
+ * needed to read its parameters from guest memory.
+ */
+ struct SemiCall
+ {
+ /** Call name */
+ const char *name;
+
+ /**
+ * Pointer to call implementation
+ *
+ * @param tc ThreadContext pointer for caller
+ * @param aarch64 True if in aarc64 mode, false otherwise.
+ * @parma argv Argument vector. argv[0] always corresponds to
+ * the pointer to the argument list. Remaining
+ * entries are read as consecutive words starting
+ * at the address pointed to by argv[0].
+ * @return a (return value, errno) pair
+ */
+ RetErrno (ArmSemihosting::*call)(ThreadContext *tc, bool aarch64,
+ std::vector<uint64_t> &argv);
+
+ /** Number of aarch32 arguments to read from guest memory. -1
+ * if unimplemented.*/
+ int argc32;
+ /** Number of aarch32 arguments to read from guest memory. -1
+ * if unimplemented.*/
+ int argc64;
+
+ /** Is call implemented in aarch32? */
+ bool implemented32() const { return call && argc32 >= 0; }
+ /** Is call implemented in aarch64? */
+ bool implemented64() const { return call && argc64 >= 0; }
+ };
+
+#define SEMI_CALL(N) \
+ RetErrno call ## N (ThreadContext *tc, \
+ bool aarch64, std::vector<uint64_t> &argv)
+
+ SEMI_CALL(Open);
+ SEMI_CALL(Close);
+ SEMI_CALL(WriteC);
+ SEMI_CALL(Write0);
+ SEMI_CALL(Write);
+ SEMI_CALL(Read);
+ SEMI_CALL(ReadC);
+ SEMI_CALL(IsError);
+ SEMI_CALL(IsTTY);
+ SEMI_CALL(Seek);
+ SEMI_CALL(FLen);
+ SEMI_CALL(TmpNam);
+ SEMI_CALL(Remove);
+ SEMI_CALL(Rename);
+ SEMI_CALL(Clock);
+ SEMI_CALL(Time);
+ SEMI_CALL(System);
+ SEMI_CALL(Errno);
+ SEMI_CALL(GetCmdLine);
+ SEMI_CALL(HeapInfo);
+ SEMI_CALL(Exit);
+ SEMI_CALL(ExitExtended);
+
+ SEMI_CALL(Elapsed);
+ SEMI_CALL(TickFreq);
+
+#undef SEMI_CALL
+
+ static const SemiCall *getCall(uint32_t op, bool aarch64);
+
+ static const std::map<uint32_t, SemiCall> calls;
+ static const std::vector<const char *> fmodes;
+ static const std::map<uint64_t, const char *> exitCodes;
+ static const std::vector<uint8_t> features;
+};
+
+#endif // __ARCH_ARM_SEMIHOSTING_HH__
diff --git a/src/arch/arm/system.cc b/src/arch/arm/system.cc
index 50ac4aeeb..caef6dc8f 100644
--- a/src/arch/arm/system.cc
+++ b/src/arch/arm/system.cc
@@ -44,6 +44,7 @@
#include <iostream>
+#include "arch/arm/semihosting.hh"
#include "base/loader/object_file.hh"
#include "base/loader/symtab.hh"
#include "cpu/thread_context.hh"
@@ -70,6 +71,7 @@ ArmSystem::ArmSystem(Params *p)
_m5opRange(p->m5ops_base ?
RangeSize(p->m5ops_base, 0x10000) :
AddrRange(1, 0)), // Create an empty range if disabled
+ semihosting(p->semihosting),
multiProc(p->multi_proc)
{
// Check if the physical address range is valid
@@ -268,6 +270,28 @@ ArmSystem::haveLargeAsid64(ThreadContext *tc)
return getArmSystem(tc)->haveLargeAsid64();
}
+bool
+ArmSystem::haveSemihosting(ThreadContext *tc)
+{
+ return getArmSystem(tc)->haveSemihosting();
+}
+
+uint64_t
+ArmSystem::callSemihosting64(ThreadContext *tc,
+ uint32_t op, uint64_t param)
+{
+ ArmSystem *sys = getArmSystem(tc);
+ return sys->semihosting->call64(tc, op, param);
+}
+
+uint32_t
+ArmSystem::callSemihosting32(ThreadContext *tc,
+ uint32_t op, uint32_t param)
+{
+ ArmSystem *sys = getArmSystem(tc);
+ return sys->semihosting->call32(tc, op, param);
+}
+
ArmSystem *
ArmSystemParams::create()
{
diff --git a/src/arch/arm/system.hh b/src/arch/arm/system.hh
index 46103f42c..e7696a4fd 100644
--- a/src/arch/arm/system.hh
+++ b/src/arch/arm/system.hh
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010, 2012-2013, 2015-2017 ARM Limited
+ * Copyright (c) 2010, 2012-2013, 2015-2018 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
@@ -122,6 +122,11 @@ class ArmSystem : public System
*/
const AddrRange _m5opRange;
+ /**
+ * True if the Semihosting interface is enabled.
+ */
+ ArmSemihosting *const semihosting;
+
protected:
/**
* Get a boot loader that matches the kernel.
@@ -228,6 +233,9 @@ class ArmSystem : public System
*/
const AddrRange &m5opRange() const { return _m5opRange; }
+ /** Is Arm Semihosting support enabled? */
+ bool haveSemihosting() const { return semihosting != nullptr; }
+
/**
* Returns a valid ArmSystem pointer if using ARM ISA, it fails
* otherwise.
@@ -280,6 +288,17 @@ class ArmSystem : public System
/** Returns true if ASID is 16 bits for the system of a specific thread
* context while in AArch64 (ARMv8) */
static bool haveLargeAsid64(ThreadContext *tc);
+
+ /** Is Arm Semihosting support enabled? */
+ static bool haveSemihosting(ThreadContext *tc);
+
+ /** Make a Semihosting call from aarch64 */
+ static uint64_t callSemihosting64(ThreadContext *tc,
+ uint32_t op, uint64_t param);
+
+ /** Make a Semihosting call from aarch32 */
+ static uint32_t callSemihosting32(ThreadContext *tc,
+ uint32_t op, uint32_t param);
};
class GenericArmSystem : public ArmSystem