Deleted Added
sdiff udiff text old ( 13893:0e863b6c441a ) new ( 14007:36f842f523c6 )
full compact
1/*
2 * Copyright (c) 2018 ARM Limited
3 * All rights reserved
4 *
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder. You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions are
16 * met: redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer;
18 * redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution;
21 * neither the name of the copyright holders nor the names of its
22 * contributors may be used to endorse or promote products derived from
23 * this software without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 *
37 * Authors: Andreas Sandberg
38 */
39
40#include "arch/arm/semihosting.hh"
41
42#include <cstdio>
43
44#include "arch/arm/utility.hh"
45#include "base/logging.hh"
46#include "base/time.hh"
47#include "debug/Semihosting.hh"
48#include "dev/serial/serial.hh"
49#include "mem/physical.hh"
50#include "mem/secure_port_proxy.hh"
51#include "params/ArmSemihosting.hh"
52#include "sim/byteswap.hh"
53#include "sim/sim_exit.hh"
54#include "sim/system.hh"
55
56const std::map<uint32_t, ArmSemihosting::SemiCall> ArmSemihosting::calls{
57 { 0x01, { "SYS_OPEN", &ArmSemihosting::callOpen, 3, 3 } },
58 { 0x02, { "SYS_CLOSE", &ArmSemihosting::callClose, 1, 1 } },
59
60 // Write(C|0) are special since we want to read the character
61 // manually. We therefore declare them as having 0 params.
62 { 0x03, { "SYS_WRITEC", &ArmSemihosting::callWriteC, 0, 0 } },
63 { 0x04, { "SYS_WRITE0", &ArmSemihosting::callWrite0, 1, 1 } },
64
65 { 0x05, { "SYS_WRITE", &ArmSemihosting::callWrite, 3, 3 } },
66 { 0x06, { "SYS_READ", &ArmSemihosting::callRead, 3, 3 } },
67 { 0x07, { "SYS_READC", &ArmSemihosting::callReadC, 0, 0 } },
68 { 0x08, { "SYS_ISERROR", &ArmSemihosting::callIsError, 1, 1 } },
69 { 0x09, { "SYS_ISTTY", &ArmSemihosting::callIsTTY, 1, 1 } },
70 { 0x0A, { "SYS_SEEK", &ArmSemihosting::callSeek, 2, 2 } },
71 { 0x0C, { "SYS_FLEN", &ArmSemihosting::callFLen, 1, 1 } },
72 { 0x0D, { "SYS_TMPNAM", &ArmSemihosting::callTmpNam, 3, 3 } },
73 { 0x0E, { "SYS_REMOVE", &ArmSemihosting::callRemove, 2, 2} },
74 { 0x0F, { "SYS_RENAME", &ArmSemihosting::callRename, 4, 4} },
75 { 0x10, { "SYS_CLOCK", &ArmSemihosting::callClock, 0, 0} },
76 { 0x11, { "SYS_TIME", &ArmSemihosting::callTime, 0, 0} },
77 { 0x12, { "SYS_SYSTEM", &ArmSemihosting::callSystem, 2, 2} },
78 { 0x13, { "SYS_ERRNO", &ArmSemihosting::callErrno, 0, 0 } },
79 { 0x15, { "SYS_GET_CMDLINE", &ArmSemihosting::callGetCmdLine, 2, 2} },
80 { 0x16, { "SYS_HEAPINFO", &ArmSemihosting::callHeapInfo, 1, 1} },
81
82 // Exit is special and requires custom handling in aarch32.
83 { 0x18, { "SYS_EXIT", &ArmSemihosting::callExit, 0, 2 } },
84 { 0x20, { "SYS_EXIT_EXTENDED", &ArmSemihosting::callExitExtended, 2, 2 } },
85
86 { 0x30, { "SYS_ELAPSED", &ArmSemihosting::callElapsed, 0, 0 } },
87 { 0x31, { "SYS_TICKFREQ", &ArmSemihosting::callTickFreq, 0, 0 } },
88};
89
90const std::vector<const char *> ArmSemihosting::fmodes{
91 "r", "rb", "r+", "r+b",
92 "w", "wb", "w+", "w+b",
93 "a", "ab", "a+", "a+b",
94};
95
96const std::map<uint64_t, const char *> ArmSemihosting::exitCodes{
97 { 0x20000, "semi:ADP_Stopped_BranchThroughZero" },
98 { 0x20001, "semi:ADP_Stopped_UndefinedInstr" },
99 { 0x20002, "semi:ADP_Stopped_SoftwareInterrupt" },
100 { 0x20003, "semi:ADP_Stopped_PrefetchAbort" },
101 { 0x20004, "semi:ADP_Stopped_DataAbort" },
102 { 0x20005, "semi:ADP_Stopped_AddressException" },
103 { 0x20006, "semi:ADP_Stopped_IRQ" },
104 { 0x20007, "semi:ADP_Stopped_FIQ" },
105
106 { 0x20020, "semi:ADP_Stopped_BreakPoint" },
107 { 0x20021, "semi:ADP_Stopped_WatchPoint" },
108 { 0x20022, "semi:ADP_Stopped_StepComplete" },
109 { 0x20023, "semi:ADP_Stopped_RunTimeErrorUnknown" },
110 { 0x20024, "semi:ADP_Stopped_InternalError" },
111 { 0x20025, "semi:ADP_Stopped_UserInterruption" },
112 { 0x20026, "semi:ADP_Stopped_ApplicationExit" },
113 { 0x20027, "semi:ADP_Stopped_StackOverflow" },
114 { 0x20028, "semi:ADP_Stopped_DivisionByZero" },
115 { 0x20029, "semi:ADP_Stopped_DivisionByZero" },
116};
117
118
119const std::vector<uint8_t> ArmSemihosting::features{
120 0x53, 0x48, 0x46, 0x42, // Magic
121 0x3, // EXT_EXIT_EXTENDED, EXT_STDOUT_STDERR
122};
123
124const std::map<const std::string, FILE *> ArmSemihosting::stdioMap{
125 {"cin", ::stdin},
126 {"stdin", ::stdin},
127 {"cout", ::stdout},
128 {"stdout", ::stdout},
129 {"cerr", ::stderr},
130 {"stderr", ::stderr},
131};
132
133ArmSemihosting::ArmSemihosting(const ArmSemihostingParams *p)
134 : SimObject(p),
135 cmdLine(p->cmd_line),
136 memReserve(p->mem_reserve),
137 stackSize(p->stack_size),
138 timeBase([p]{ struct tm t = p->time; return mkutctime(&t); }()),
139 tickShift(calcTickShift()),
140 semiErrno(0),
141 stdin(getSTDIO("stdin", p->stdin, "r")),
142 stdout(getSTDIO("stdout", p->stdout, "w")),
143 stderr(p->stderr == p->stdout ?
144 stdout : getSTDIO("stderr", p->stderr, "w"))
145{
146 // Create an empty place-holder file for position 0 as semi-hosting
147 // calls typically expect non-zero file handles.
148 files.push_back(nullptr);
149
150 if (tickShift > 0)
151 inform("Semihosting: Shifting elapsed ticks by %i bits.",
152 tickShift);
153}
154
155uint64_t
156ArmSemihosting::call64(ThreadContext *tc, uint32_t op, uint64_t param)
157{
158 const SemiCall *call = getCall(op, true);
159 if (!call) {
160 warn("Unknown aarch64 semihosting call: op = 0x%x, param = 0x%x",
161 op, param);
162
163 return (uint64_t)-1;
164 } else if (!call->implemented64()) {
165 warn("Unimplemented aarch64 semihosting call: "
166 "%s (op = 0x%x, param = 0x%x)",
167 call->name, op, param);
168
169 return (uint64_t)-1;
170 }
171
172 std::vector<uint64_t> argv(call->argc64 + 1);
173 PortProxy &proxy = physProxy(tc);
174 ByteOrder endian = ArmISA::byteOrder(tc);
175
176 DPRINTF(Semihosting, "Semihosting call64: %s(0x%x)\n", call->name, param);
177 argv[0] = param;
178 for (int i = 0; i < call->argc64; ++i) {
179 argv[i + 1] = proxy.read<uint64_t>(param + i * 8, endian);
180 DPRINTF(Semihosting, "\t: 0x%x\n", argv[i + 1]);
181 }
182
183 auto ret_errno = (this->*call->call)(tc, true, argv);
184 semiErrno = ret_errno.second;
185 DPRINTF(Semihosting, "\t ->: 0x%x, %i\n",
186 ret_errno.first, ret_errno.second);
187 return ret_errno.first;
188}
189
190uint32_t
191ArmSemihosting::call32(ThreadContext *tc, uint32_t op, uint32_t param)
192{
193 const SemiCall *call = getCall(op, false);
194 if (!call) {
195 warn("Unknown aarch32 semihosting call: op = 0x%x, param = 0x%x",
196 op, param);
197
198 return (uint32_t)-1;
199 } else if (!call->implemented32()) {
200 warn("Unimplemented aarch32 semihosting call: "
201 "%s (op = 0x%x, param = 0x%x)",
202 call->name, op, param);
203
204 return (uint32_t)-1;
205 }
206
207 std::vector<uint64_t> argv(call->argc32 + 1);
208 PortProxy &proxy = physProxy(tc);
209 ByteOrder endian = ArmISA::byteOrder(tc);
210
211 DPRINTF(Semihosting, "Semihosting call32: %s(0x%x)\n", call->name, param);
212 argv[0] = param;
213 for (int i = 0; i < call->argc32; ++i) {
214 argv[i + 1] = proxy.read<uint32_t>(param + i * 4, endian);
215 DPRINTF(Semihosting, "\t: 0x%x\n", argv[i + 1]);
216 }
217
218 auto ret_errno = (this->*call->call)(tc, false, argv);
219 semiErrno = ret_errno.second;
220 DPRINTF(Semihosting, "\t ->: 0x%x, %i\n",
221 ret_errno.first, ret_errno.second);
222 return ret_errno.first;
223}
224
225void
226ArmSemihosting::serialize(CheckpointOut &cp) const
227{
228 SERIALIZE_SCALAR(semiErrno);
229
230 paramOut(cp, "num_files", files.size());
231 for (int i = 0; i < files.size(); i++) {
232 // File closed?
233 if (!files[i])
234 continue;
235
236 files[i]->serializeSection(cp, csprintf("file%i", i));
237 }
238}
239
240void
241ArmSemihosting::unserialize(CheckpointIn &cp)
242{
243 UNSERIALIZE_SCALAR(semiErrno);
244
245 size_t num_files;
246 paramIn(cp, "num_files", num_files);
247 files.resize(num_files);
248 for (int i = 0; i < num_files; i++)
249 files[i] = FileBase::create(*this, cp, csprintf("file%i", i));
250}
251
252PortProxy &
253ArmSemihosting::physProxy(ThreadContext *tc)
254{
255 if (ArmISA::inSecureState(tc)) {
256 if (!physProxyS) {
257 System *sys = tc->getSystemPtr();
258 physProxyS.reset(new SecurePortProxy(
259 sys->getSystemPort(),
260 sys->cacheLineSize()));
261 }
262 return *physProxyS;
263 } else {
264 return tc->getPhysProxy();
265 }
266}
267
268
269std::string
270ArmSemihosting::readString(ThreadContext *tc, Addr ptr, size_t len)
271{
272 std::vector<char> buf(len + 1);
273
274 buf[len] = '\0';
275 physProxy(tc).readBlob(ptr, (uint8_t *)buf.data(), len);
276
277 return std::string(buf.data());
278}
279
280ArmSemihosting::RetErrno
281ArmSemihosting::callOpen(ThreadContext *tc, bool aarch64,
282 std::vector<uint64_t> &argv)
283{
284 const Addr name_base = argv[1];
285 const char *mode = argv[2] < fmodes.size() ? fmodes[argv[2]] : nullptr;
286 const Addr name_size = argv[3];
287
288 DPRINTF(Semihosting, "Semihosting SYS_OPEN(0x%x, %i[%s], %i)\n",
289 name_base, argv[2], mode ? mode : "-", name_size);
290 if (!mode || !name_base)
291 return retError(EINVAL);
292
293 std::string fname = readString(tc, name_base, name_size);
294
295 std::unique_ptr<ArmSemihosting::FileBase> file =
296 FileBase::create(*this, fname, mode);
297 int64_t ret = file->open();
298 DPRINTF(Semihosting, "Semihosting SYS_OPEN(\"%s\", %i[%s]): %i\n",
299 fname, argv[2], mode, ret);
300 if (ret < 0) {
301 return retError(-ret);
302 } else {
303 files.push_back(std::move(file));
304 return retOK(files.size() - 1);
305 }
306}
307
308ArmSemihosting::RetErrno
309ArmSemihosting::callClose(ThreadContext *tc, bool aarch64,
310 std::vector<uint64_t> &argv)
311{
312 if (argv[1] > files.size()) {
313 DPRINTF(Semihosting, "Semihosting SYS_CLOSE(%i): Illegal file\n");
314 return retError(EBADF);
315 }
316
317 std::unique_ptr<FileBase> &file = files[argv[1]];
318 int64_t error = file->close();
319 DPRINTF(Semihosting, "Semihosting SYS_CLOSE(%i[%s]): %i\n",
320 argv[1], file->fileName(), error);
321 if (error < 0) {
322 return retError(-error);
323 } else {
324 // Zap the pointer and free the entry in the file table as
325 // well.
326 files[argv[1]].reset();
327 return retOK(0);
328 }
329}
330
331ArmSemihosting::RetErrno
332ArmSemihosting::callWriteC(ThreadContext *tc, bool aarch64,
333 std::vector<uint64_t> &argv)
334{
335 const char c = physProxy(tc).read<char>(argv[0]);
336
337 DPRINTF(Semihosting, "Semihosting SYS_WRITEC('%c')\n", c);
338 std::cout.put(c);
339
340 return retOK(0);
341}
342
343ArmSemihosting::RetErrno
344ArmSemihosting::callWrite0(ThreadContext *tc, bool aarch64,
345 std::vector<uint64_t> &argv)
346{
347 DPRINTF(Semihosting, "Semihosting SYS_WRITE0(...)\n");
348 PortProxy &proxy = physProxy(tc);
349 for (Addr addr = (Addr)argv[0]; ; ++addr) {
350 char data = proxy.read<char>(addr);
351 if (data == 0)
352 break;
353
354 std::cout.put(data);
355 }
356
357 return retOK(0);
358}
359
360ArmSemihosting::RetErrno
361ArmSemihosting::callWrite(ThreadContext *tc, bool aarch64,
362 std::vector<uint64_t> &argv)
363{
364 if (argv[1] > files.size() || !files[argv[1]])
365 return RetErrno(argv[3], EBADF);
366
367 std::vector<uint8_t> buffer(argv[3]);
368 physProxy(tc).readBlob(argv[2], buffer.data(), buffer.size());
369
370 int64_t ret = files[argv[1]]->write(buffer.data(), buffer.size());
371 if (ret < 0) {
372 // No bytes written (we're returning the number of bytes not
373 // written)
374 return RetErrno(argv[3], -ret);
375 } else {
376 // Return the number of bytes not written
377 return RetErrno(argv[3] - ret, 0);
378 }
379}
380
381ArmSemihosting::RetErrno
382ArmSemihosting::callRead(ThreadContext *tc, bool aarch64,
383 std::vector<uint64_t> &argv)
384{
385 if (argv[1] > files.size() || !files[argv[1]])
386 return RetErrno(argv[3], EBADF);
387
388 std::vector<uint8_t> buffer(argv[3]);
389 int64_t ret = files[argv[1]]->read(buffer.data(), buffer.size());
390 if (ret < 0) {
391 return RetErrno(argv[3], -ret);
392 } else {
393 panic_if(ret > buffer.size(), "Read longer than buffer size.");
394
395 physProxy(tc).writeBlob(argv[2], buffer.data(), ret);
396
397 // Return the number of bytes not written
398 return retOK(argv[3] - ret);
399 }
400}
401
402ArmSemihosting::RetErrno
403ArmSemihosting::callReadC(ThreadContext *tc, bool aarch64,
404 std::vector<uint64_t> &argv)
405{
406 return retOK((char)std::cin.get());
407}
408
409ArmSemihosting::RetErrno
410ArmSemihosting::callIsError(ThreadContext *tc, bool aarch64,
411 std::vector<uint64_t> &argv)
412{
413 // Sign extend from a 32 bit integer in aarch32 since the argument
414 // reader zero extends to a uint64_t.
415 const int64_t status = (int64_t)(aarch64 ? argv[1] :sext<32>(argv[1]));
416 // Assume there was an error if the status value is negative.
417 return retOK(status < 0 ? 1 : 0);
418}
419
420ArmSemihosting::RetErrno
421ArmSemihosting::callIsTTY(ThreadContext *tc, bool aarch64,
422 std::vector<uint64_t> &argv)
423{
424 if (argv[1] > files.size() || !files[argv[1]])
425 return retError(EBADF);
426
427 int64_t ret = files[argv[1]]->isTTY();
428 if (ret < 0) {
429 return retError(-ret);
430 } else {
431 return retOK(ret ? 1 : 0);
432 }
433}
434
435ArmSemihosting::RetErrno
436ArmSemihosting::callSeek(ThreadContext *tc, bool aarch64,
437 std::vector<uint64_t> &argv)
438{
439 if (argv[1] > files.size() || !files[argv[1]])
440 return retError(EBADF);
441
442 int64_t ret = files[argv[1]]->seek(argv[2]);
443 if (ret < 0) {
444 return retError(-ret);
445 } else {
446 return retOK(0);
447 }
448}
449
450ArmSemihosting::RetErrno
451ArmSemihosting::callFLen(ThreadContext *tc, bool aarch64,
452 std::vector<uint64_t> &argv)
453{
454 if (argv[1] > files.size() || !files[argv[1]])
455 return retError(EBADF);
456
457 int64_t ret = files[argv[1]]->isTTY();
458 if (ret < 0) {
459 return retError(-ret);
460 } else {
461 return retOK(0);
462 }
463}
464
465ArmSemihosting::RetErrno
466ArmSemihosting::callTmpNam(ThreadContext *tc, bool aarch64,
467 std::vector<uint64_t> &argv)
468{
469 const Addr guest_buf = argv[1];
470 //const uint64_t id = argv[2];
471 const uint64_t max_len = argv[3];
472
473 std::vector<char> buf(L_tmpnam);
474 char *path = tmpnam(buf.data());
475 if (!path)
476 return retError(EINVAL);
477
478 const size_t path_len = strlen(path);
479 if (path_len >= max_len)
480 return retError(ENOSPC);
481
482 physProxy(tc).writeBlob(
483 guest_buf, (const uint8_t *)path, path_len + 1);
484 return retOK(0);
485}
486
487ArmSemihosting::RetErrno
488ArmSemihosting::callRemove(ThreadContext *tc, bool aarch64,
489 std::vector<uint64_t> &argv)
490{
491 std::string fname = readString(tc, argv[1], argv[2]);
492
493 if (remove(fname.c_str()) != 0) {
494 return retError(errno);
495 } else {
496 return retOK(0);
497 }
498}
499
500ArmSemihosting::RetErrno
501ArmSemihosting::callRename(ThreadContext *tc, bool aarch64,
502 std::vector<uint64_t> &argv)
503{
504 std::string from = readString(tc, argv[1], argv[2]);
505 std::string to = readString(tc, argv[3], argv[4]);
506
507 if (rename(from.c_str(), to.c_str()) != 0) {
508 return retError(errno);
509 } else {
510 return retOK(0);
511 }
512}
513
514ArmSemihosting::RetErrno
515ArmSemihosting::callClock(ThreadContext *tc, bool aarch64,
516 std::vector<uint64_t> &argv)
517{
518 return retOK(curTick() / (SimClock::Int::s / 100));
519}
520
521ArmSemihosting::RetErrno
522ArmSemihosting::callTime(ThreadContext *tc, bool aarch64,
523 std::vector<uint64_t> &argv)
524{
525 return retOK(timeBase + round(curTick() / SimClock::Float::s));
526}
527
528ArmSemihosting::RetErrno
529ArmSemihosting::callSystem(ThreadContext *tc, bool aarch64,
530 std::vector<uint64_t> &argv)
531{
532 const std::string cmd = readString(tc, argv[1], argv[2]);
533 warn("Semihosting: SYS_SYSTEM not implemented. Guest tried to run: %s\n",
534 cmd);
535 return retError(EINVAL);
536
537}
538
539ArmSemihosting::RetErrno
540ArmSemihosting::callErrno(ThreadContext *tc, bool aarch64,
541 std::vector<uint64_t> &argv)
542{
543 // Preserve errno by returning it in errno as well.
544 return RetErrno(semiErrno, semiErrno);
545}
546
547ArmSemihosting::RetErrno
548ArmSemihosting::callGetCmdLine(ThreadContext *tc, bool aarch64,
549 std::vector<uint64_t> &argv)
550{
551 if (cmdLine.size() + 1 < argv[2]) {
552 PortProxy &proxy = physProxy(tc);
553 ByteOrder endian = ArmISA::byteOrder(tc);
554 proxy.writeBlob(
555 (Addr)argv[1],
556 (const uint8_t *)cmdLine.c_str(), cmdLine.size() + 1);
557
558 if (aarch64)
559 proxy.write<uint64_t>(argv[0] + 1 * 8, cmdLine.size(), endian);
560 else
561 proxy.write<uint32_t>(argv[0] + 1 * 4, cmdLine.size(), endian);
562 return retOK(0);
563 } else {
564 return retError(0);
565 }
566}
567
568ArmSemihosting::RetErrno
569ArmSemihosting::callHeapInfo(ThreadContext *tc, bool aarch64,
570 std::vector<uint64_t> &argv)
571{
572 const PhysicalMemory &phys = tc->getSystemPtr()->getPhysMem();
573 const AddrRangeList memories = phys.getConfAddrRanges();
574 fatal_if(memories.size() < 1, "No memories reported from System");
575 warn_if(memories.size() > 1, "Multiple physical memory ranges available. "
576 "Using first range heap/stack.");
577 const AddrRange memory = *memories.begin();
578 const Addr mem_start = memory.start() + memReserve;
579 Addr mem_end = memory.end();
580
581 // Make sure that 32-bit guests can access their memory.
582 if (!aarch64) {
583 const Addr phys_max = (1ULL << 32) - 1;
584 panic_if(mem_start > phys_max,
585 "Physical memory out of range for a 32-bit guest.");
586 if (mem_end > phys_max) {
587 warn("Some physical memory out of range for a 32-bit guest.");
588 mem_end = phys_max;
589 }
590 }
591
592 fatal_if(mem_start + stackSize >= mem_end,
593 "Physical memory too small to fit desired stack and a heap.");
594
595 const Addr heap_base = mem_start;
596 const Addr heap_limit = mem_end - stackSize + 1;
597 const Addr stack_base = (mem_end + 1) & ~0x7ULL; // 8 byte stack alignment
598 const Addr stack_limit = heap_limit;
599
600
601 inform("Reporting heap/stack info to guest:\n"
602 "\tHeap base: 0x%x\n"
603 "\tHeap limit: 0x%x\n"
604 "\tStack base: 0x%x\n"
605 "\tStack limit: 0x%x\n",
606 heap_base, heap_limit, stack_base, stack_limit);
607
608 Addr base = argv[1];
609 PortProxy &proxy = physProxy(tc);
610 ByteOrder endian = ArmISA::byteOrder(tc);
611 if (aarch64) {
612 proxy.write<uint64_t>(base + 0 * 8, heap_base, endian);
613 proxy.write<uint64_t>(base + 1 * 8, heap_limit, endian);
614 proxy.write<uint64_t>(base + 2 * 8, stack_base, endian);
615 proxy.write<uint64_t>(base + 3 * 8, stack_limit, endian);
616 } else {
617 proxy.write<uint32_t>(base + 0 * 4, heap_base, endian);
618 proxy.write<uint32_t>(base + 1 * 4, heap_limit, endian);
619 proxy.write<uint32_t>(base + 2 * 4, stack_base, endian);
620 proxy.write<uint32_t>(base + 3 * 4, stack_limit, endian);
621 }
622
623 return retOK(0);
624}
625
626ArmSemihosting::RetErrno
627ArmSemihosting::callExit(ThreadContext *tc, bool aarch64,
628 std::vector<uint64_t> &argv)
629{
630 if (aarch64) {
631 semiExit(argv[1], argv[2]);
632 } else {
633 semiExit(argv[0], 0);
634 }
635
636 return retOK(0);
637}
638
639ArmSemihosting::RetErrno
640ArmSemihosting::callExitExtended(ThreadContext *tc, bool aarch64,
641 std::vector<uint64_t> &argv)
642{
643 semiExit(argv[1], argv[2]);
644
645 return retOK(0);
646}
647
648void
649ArmSemihosting::semiExit(uint64_t code, uint64_t subcode)
650{
651 auto it = exitCodes.find(code);
652 if (it != exitCodes.end()) {
653 exitSimLoop(it->second, subcode);
654 } else {
655 exitSimLoop(csprintf("semi:0x%x", code), subcode);
656 }
657}
658
659
660ArmSemihosting::RetErrno
661ArmSemihosting::callElapsed(ThreadContext *tc, bool aarch64,
662 std::vector<uint64_t> &argv)
663{
664 PortProxy &proxy = physProxy(tc);
665 ByteOrder endian = ArmISA::byteOrder(tc);
666 const uint64_t tick = semiTick(curTick());
667
668 if (aarch64) {
669 proxy.write<uint64_t>(argv[0], tick, endian);
670 } else {
671 proxy.write<uint32_t>(argv[0] + 0 * 4, tick, endian);
672 proxy.write<uint32_t>(argv[0] + 1 * 4, tick >> 32, endian);
673 }
674
675 return retOK(0);
676}
677
678
679ArmSemihosting::RetErrno
680ArmSemihosting::callTickFreq(ThreadContext *tc, bool aarch64,
681 std::vector<uint64_t> &argv)
682{
683 return retOK(semiTick(SimClock::Frequency));
684}
685
686const ArmSemihosting::SemiCall *
687ArmSemihosting::getCall(uint32_t op, bool aarch64)
688{
689 auto it = calls.find(op);
690 if (it == calls.end())
691 return nullptr;
692 else {
693 return &it->second;
694 }
695}
696
697FILE *
698ArmSemihosting::getSTDIO(const char *stream_name,
699 const std::string &name, const char *mode)
700{
701 auto it = stdioMap.find(name);
702 if (it == stdioMap.end()) {
703 FILE *f = fopen(name.c_str(), mode);
704 if (!f) {
705 fatal("Failed to open %s (%s): %s\n",
706 stream_name, name, strerror(errno));
707 }
708 return f;
709 } else {
710 return it->second;
711 }
712}
713
714std::unique_ptr<ArmSemihosting::FileBase>
715ArmSemihosting::FileBase::create(
716 ArmSemihosting &parent, const std::string &fname, const char *mode)
717{
718 std::unique_ptr<FileBase> file;
719 if (fname == ":semihosting-features") {
720 file.reset(new FileFeatures(parent, fname.c_str(), mode));
721 } else {
722 file.reset(new File(parent, fname.c_str(), mode));
723 }
724
725 return file;
726}
727
728std::unique_ptr<ArmSemihosting::FileBase>
729ArmSemihosting::FileBase::create(ArmSemihosting &parent,
730 CheckpointIn &cp, const std::string &sec)
731{
732 std::unique_ptr<FileBase> file;
733 ScopedCheckpointSection _sec(cp, sec);
734
735 // Was the file open when the checkpoint was created?
736 if (!cp.sectionExists(Serializable::currentSection()))
737 return file;
738
739 std::string fname, mode;
740 paramIn(cp, "name", fname);
741 paramIn(cp, "mode", mode);
742 file = create(parent, fname, mode.c_str());
743 assert(file);
744 file->unserialize(cp);
745
746 return file;
747}
748
749void
750ArmSemihosting::FileBase::serialize(CheckpointOut &cp) const
751{
752 paramOut(cp, "name", _name);
753 SERIALIZE_SCALAR(mode);
754}
755
756void
757ArmSemihosting::FileBase::unserialize(CheckpointIn &cp)
758{
759 /* Unserialization of name and mode happens in
760 * ArmSemihosting::FileBase::create() */
761}
762
763int64_t
764ArmSemihosting::FileBase::read(uint8_t *buffer, uint64_t size)
765{
766 return -EINVAL;
767}
768
769int64_t
770ArmSemihosting::FileBase::write(const uint8_t *buffer, uint64_t size)
771{
772 return -EINVAL;
773}
774
775int64_t
776ArmSemihosting::FileBase::seek(uint64_t pos)
777{
778 return -EINVAL;
779}
780
781int64_t
782ArmSemihosting::FileBase::flen()
783{
784 return -EINVAL;
785}
786
787
788ArmSemihosting::FileFeatures::FileFeatures(
789 ArmSemihosting &_parent, const char *_name, const char *_mode)
790 : FileBase(_parent, _name, _mode)
791{
792}
793
794int64_t
795ArmSemihosting::FileFeatures::read(uint8_t *buffer, uint64_t size)
796{
797 int64_t len = 0;
798
799 for (; pos < size && pos < ArmSemihosting::features.size(); pos++)
800 buffer[len++] = ArmSemihosting::features[pos];
801
802 return len;
803}
804
805int64_t
806ArmSemihosting::FileFeatures::seek(uint64_t _pos)
807{
808 if (_pos < ArmSemihosting::features.size()) {
809 pos = _pos;
810 return 0;
811 } else {
812 return -ENXIO;
813 }
814}
815
816void
817ArmSemihosting::FileFeatures::serialize(CheckpointOut &cp) const
818{
819 FileBase::serialize(cp);
820 SERIALIZE_SCALAR(pos);
821}
822
823void
824ArmSemihosting::FileFeatures::unserialize(CheckpointIn &cp)
825{
826 FileBase::unserialize(cp);
827 UNSERIALIZE_SCALAR(pos);
828}
829
830
831
832ArmSemihosting::File::File(ArmSemihosting &_parent,
833 const char *_name, const char *_perms)
834 : FileBase(_parent, _name, _perms),
835 file(nullptr)
836{
837}
838
839ArmSemihosting::File::~File()
840{
841 if (file)
842 close();
843}
844
845int64_t
846ArmSemihosting::File::openImpl(bool in_cpt)
847{
848 panic_if(file, "Trying to open an already open file.\n");
849
850 if (_name == ":tt") {
851 if (mode[0] == 'r') {
852 file = parent.stdin;
853 } else if (mode[0] == 'w') {
854 file = parent.stdout;
855 } else if (mode[0] == 'a') {
856 file = parent.stderr;
857 } else {
858 warn("Unknown file mode for the ':tt' special file");
859 return -EINVAL;
860 }
861 } else {
862 std::string real_mode(this->mode);
863 // Avoid truncating the file if we are restoring from a
864 // checkpoint.
865 if (in_cpt && real_mode[0] == 'w')
866 real_mode[0] = 'a';
867
868 file = fopen(_name.c_str(), real_mode.c_str());
869 }
870
871 return file ? 0 : -errno;
872}
873
874int64_t
875ArmSemihosting::File::close()
876{
877 panic_if(!file, "Trying to close an already closed file.\n");
878
879 if (needClose()) {
880 fclose(file);
881 }
882 file = nullptr;
883
884 return 0;
885}
886
887bool
888ArmSemihosting::File::isTTY() const
889{
890 return file == parent.stdout ||
891 file == parent.stderr ||
892 file == parent.stdin;
893}
894
895int64_t
896ArmSemihosting::File::read(uint8_t *buffer, uint64_t size)
897{
898 panic_if(!file, "Trying to read from a closed file");
899
900 size_t ret = fread(buffer, 1, size, file);
901 if (ret == 0) {
902 // Error or EOF. Assume errors are due to invalid file
903 // operations (e.g., reading a write-only stream).
904 return ferror(file) ? -EINVAL : 0;
905 } else {
906 return ret;
907 }
908}
909
910int64_t
911ArmSemihosting::File::write(const uint8_t *buffer, uint64_t size)
912{
913 panic_if(!file, "Trying to write to a closed file");
914
915
916 size_t ret = fwrite(buffer, 1, size, file);
917 if (ret == 0) {
918 // Assume errors are due to invalid file operations (e.g.,
919 // writing a read-only stream).
920 return -EINVAL;
921 } else {
922 return ret;
923 }
924}
925
926int64_t
927ArmSemihosting::File::seek(uint64_t _pos)
928{
929 panic_if(!file, "Trying to seek in a closed file");
930
931 errno = 0;
932 if (fseek(file, _pos, SEEK_SET) == 0)
933 return 0;
934 else
935 return -errno;
936}
937
938int64_t
939ArmSemihosting::File::flen()
940{
941 errno = 0;
942 long pos = ftell(file);
943 if (pos < 0)
944 return -errno;
945
946 if (fseek(file, 0, SEEK_END) != 0)
947 return -errno;
948
949 long len = ftell(file);
950 if (len < 0)
951 return -errno;
952
953 if (fseek(file, pos, SEEK_SET) != 0)
954 return -errno;
955
956 return len;
957}
958
959
960void
961ArmSemihosting::File::serialize(CheckpointOut &cp) const
962{
963 FileBase::serialize(cp);
964
965 if (!isTTY()) {
966 long pos = file ? ftell(file) : 0;
967 panic_if(pos < 0, "Failed to get file position.");
968 SERIALIZE_SCALAR(pos);
969 }
970}
971
972void
973ArmSemihosting::File::unserialize(CheckpointIn &cp)
974{
975 FileBase::unserialize(cp);
976
977 if (openImpl(true) < 0) {
978 fatal("Failed to open file: %s", _name);
979 }
980
981 if (!isTTY()) {
982 long pos = 0;
983 UNSERIALIZE_SCALAR(pos);
984 if (fseek(file, pos, SEEK_SET) != 0) {
985 fatal("Failed seek to current position (%i) in '%s'", pos, _name);
986 }
987 }
988}
989
990
991ArmSemihosting *
992ArmSemihostingParams::create()
993{
994 return new ArmSemihosting(this);
995}