semihosting.cc revision 12531:3141027bd11a
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/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, 1, 1} },
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
124ArmSemihosting::ArmSemihosting(const ArmSemihostingParams *p)
125    : SimObject(p),
126      cmdLine(p->cmd_line),
127      memReserve(p->mem_reserve),
128      stackSize(p->stack_size),
129      timeBase([p]{ struct tm t = p->time; return mkutctime(&t); }()),
130      tickShift(calcTickShift()),
131      semiErrno(0)
132{
133    // Create an empty place-holder file for position 0 as semi-hosting
134    // calls typically expect non-zero file handles.
135    files.push_back(nullptr);
136
137    if (tickShift > 0)
138        inform("Semihosting: Shifting elapsed ticks by %i bits.",
139               tickShift);
140}
141
142uint64_t
143ArmSemihosting::call64(ThreadContext *tc, uint32_t op, uint64_t param)
144{
145    const SemiCall *call = getCall(op, true);
146    if (!call) {
147        warn("Unknown aarch64 semihosting call: op = 0x%x, param = 0x%x",
148             op, param);
149
150        return (uint64_t)-1;
151    } else if (!call->implemented64()) {
152        warn("Unimplemented aarch64 semihosting call: "
153             "%s (op = 0x%x, param = 0x%x)",
154             call->name, op, param);
155
156        return (uint64_t)-1;
157    }
158
159    std::vector<uint64_t> argv(call->argc64 + 1);
160    PortProxy &proxy = tc->getPhysProxy();
161    ByteOrder endian = ArmISA::byteOrder(tc);
162
163    DPRINTF(Semihosting, "Semihosting call64: %s(0x%x)\n", call->name, param);
164    argv[0] = param;
165    for (int i = 0; i < call->argc64; ++i) {
166        argv[i + 1] = proxy.readGtoH<uint64_t>(param + i * 8, endian);
167        DPRINTF(Semihosting, "\t: 0x%x\n", argv[i + 1]);
168    }
169
170    auto ret_errno = (this->*call->call)(tc, true, argv);
171    semiErrno = ret_errno.second;
172    DPRINTF(Semihosting, "\t ->: 0x%x, %i\n",
173            ret_errno.first, ret_errno.second);
174    return ret_errno.first;
175}
176
177uint32_t
178ArmSemihosting::call32(ThreadContext *tc, uint32_t op, uint32_t param)
179{
180    const SemiCall *call = getCall(op, false);
181    if (!call) {
182        warn("Unknown aarch32 semihosting call: op = 0x%x, param = 0x%x",
183             op, param);
184
185        return (uint32_t)-1;
186    } else if (!call->implemented32()) {
187        warn("Unimplemented aarch32 semihosting call: "
188             "%s (op = 0x%x, param = 0x%x)",
189             call->name, op, param);
190
191        return (uint32_t)-1;
192    }
193
194    std::vector<uint64_t> argv(call->argc32 + 1);
195    PortProxy &proxy = tc->getPhysProxy();
196    ByteOrder endian = ArmISA::byteOrder(tc);
197
198    DPRINTF(Semihosting, "Semihosting call32: %s(0x%x)\n", call->name, param);
199    argv[0] = param;
200    for (int i = 0; i < call->argc32; ++i) {
201        argv[i + 1] = proxy.readGtoH<uint32_t>(param + i * 4, endian);
202        DPRINTF(Semihosting, "\t: 0x%x\n", argv[i + 1]);
203    }
204
205    auto ret_errno = (this->*call->call)(tc, false, argv);
206    semiErrno = ret_errno.second;
207    DPRINTF(Semihosting, "\t ->: 0x%x, %i\n",
208            ret_errno.first, ret_errno.second);
209    return ret_errno.first;
210}
211
212void
213ArmSemihosting::serialize(CheckpointOut &cp) const
214{
215    SERIALIZE_SCALAR(semiErrno);
216
217    paramOut(cp, "num_files", files.size());
218    for (int i = 0; i < files.size(); i++) {
219        // File closed?
220        if (!files[i])
221            continue;
222
223        files[i]->serializeSection(cp, csprintf("file%i", i));
224    }
225}
226
227void
228ArmSemihosting::unserialize(CheckpointIn &cp)
229{
230    UNSERIALIZE_SCALAR(semiErrno);
231
232    size_t num_files;
233    paramIn(cp, "num_files", num_files);
234    files.resize(num_files);
235    for (int i = 0; i < num_files; i++)
236        files[i] = FileBase::create(*this, cp, csprintf("file%i", i));
237}
238
239std::string
240ArmSemihosting::readString(ThreadContext *tc, Addr ptr, size_t len)
241{
242    std::vector<char> buf(len + 1);
243
244    buf[len] = '\0';
245    tc->getPhysProxy().readBlob(ptr, (uint8_t *)buf.data(), len);
246
247    return std::string(buf.data());
248}
249
250ArmSemihosting::RetErrno
251ArmSemihosting::callOpen(ThreadContext *tc, bool aarch64,
252                         std::vector<uint64_t> &argv)
253{
254    const Addr name_base = argv[1];
255    const char *mode = argv[2] < fmodes.size() ? fmodes[argv[2]] : nullptr;
256    const Addr name_size = argv[3];
257
258    DPRINTF(Semihosting, "Semihosting SYS_OPEN(0x%x, %i[%s], %i)\n",
259            name_base, argv[2], mode ? mode : "-", name_size);
260    if (!mode || !name_base)
261        return retError(EINVAL);
262
263    std::string fname = readString(tc, name_base, name_size);
264
265    std::unique_ptr<ArmSemihosting::FileBase> file =
266        FileBase::create(*this, fname, mode);
267    int64_t ret = file->open();
268    DPRINTF(Semihosting, "Semihosting SYS_OPEN(\"%s\", %i[%s]): %i\n",
269            fname, argv[2], mode, ret);
270    if (ret < 0) {
271        return retError(-ret);
272    } else {
273        files.push_back(std::move(file));
274        return retOK(files.size() - 1);
275    }
276}
277
278ArmSemihosting::RetErrno
279ArmSemihosting::callClose(ThreadContext *tc, bool aarch64,
280                          std::vector<uint64_t> &argv)
281{
282    if (argv[1] > files.size()) {
283        DPRINTF(Semihosting, "Semihosting SYS_CLOSE(%i): Illegal file\n");
284        return retError(EBADF);
285    }
286
287    std::unique_ptr<FileBase> &file = files[argv[1]];
288    int64_t error = file->close();
289    DPRINTF(Semihosting, "Semihosting SYS_CLOSE(%i[%s]): %i\n",
290            argv[1], file->fileName(), error);
291    if (error < 0) {
292        return retError(-error);
293    } else {
294        // Zap the pointer and free the entry in the file table as
295        // well.
296        files[argv[1]].reset();
297        return retOK(0);
298    }
299}
300
301ArmSemihosting::RetErrno
302ArmSemihosting::callWriteC(ThreadContext *tc, bool aarch64,
303                           std::vector<uint64_t> &argv)
304{
305    const char c = tc->getPhysProxy().read<char>(argv[0]);
306
307    DPRINTF(Semihosting, "Semihosting SYS_WRITEC('%c')\n", c);
308    std::cout.put(c);
309
310    return retOK(0);
311}
312
313ArmSemihosting::RetErrno
314ArmSemihosting::callWrite0(ThreadContext *tc, bool aarch64,
315                           std::vector<uint64_t> &argv)
316{
317    DPRINTF(Semihosting, "Semihosting SYS_WRITE0(...)\n");
318    PortProxy &proxy = tc->getPhysProxy();
319    for (Addr addr = (Addr)argv[0]; ; ++addr) {
320        char data = proxy.read<char>(addr);
321        if (data == 0)
322            break;
323
324        std::cout.put(data);
325    }
326
327    return retOK(0);
328}
329
330ArmSemihosting::RetErrno
331ArmSemihosting::callWrite(ThreadContext *tc, bool aarch64,
332                          std::vector<uint64_t> &argv)
333{
334    if (argv[1] > files.size() || !files[argv[1]])
335        return RetErrno(argv[3], EBADF);
336
337    std::vector<uint8_t> buffer(argv[3]);
338    tc->getPhysProxy().readBlob(argv[2], buffer.data(), buffer.size());
339
340    int64_t ret = files[argv[1]]->write(buffer.data(), buffer.size());
341    if (ret < 0) {
342        // No bytes written (we're returning the number of bytes not
343        // written)
344        return RetErrno(argv[3], -ret);
345    } else {
346        // Return the number of bytes not written
347        return RetErrno(argv[3] - ret, 0);
348    }
349}
350
351ArmSemihosting::RetErrno
352ArmSemihosting::callRead(ThreadContext *tc, bool aarch64,
353                         std::vector<uint64_t> &argv)
354{
355    if (argv[1] > files.size() || !files[argv[1]])
356        return RetErrno(argv[3], EBADF);
357
358    std::vector<uint8_t> buffer(argv[3]);
359    int64_t ret = files[argv[1]]->read(buffer.data(), buffer.size());
360    if (ret < 0) {
361        return RetErrno(argv[3], -ret);
362    } else {
363        panic_if(ret > buffer.size(), "Read longer than buffer size.");
364
365        tc->getPhysProxy().writeBlob(argv[2], buffer.data(), ret);
366
367        // Return the number of bytes not written
368        return retOK(argv[3] - ret);
369    }
370}
371
372ArmSemihosting::RetErrno
373ArmSemihosting::callReadC(ThreadContext *tc, bool aarch64,
374                           std::vector<uint64_t> &argv)
375{
376    return retOK((char)std::cin.get());
377}
378
379ArmSemihosting::RetErrno
380ArmSemihosting::callIsError(ThreadContext *tc, bool aarch64,
381                            std::vector<uint64_t> &argv)
382{
383    // Sign extend from a 32 bit integer in aarch32 since the argument
384    // reader zero extends to a uint64_t.
385    const int64_t status = (int64_t)(aarch64 ? argv[1] :sext<32>(argv[1]));
386    // Assume there was an error if the status value is negative.
387    return retOK(status < 0 ? 1 : 0);
388}
389
390ArmSemihosting::RetErrno
391ArmSemihosting::callIsTTY(ThreadContext *tc, bool aarch64,
392                          std::vector<uint64_t> &argv)
393{
394    if (argv[1] > files.size() || !files[argv[1]])
395        return retError(EBADF);
396
397    int64_t ret = files[argv[1]]->isTTY();
398    if (ret < 0) {
399        return retError(-ret);
400    } else {
401        return retOK(ret ? 1 : 0);
402    }
403}
404
405ArmSemihosting::RetErrno
406ArmSemihosting::callSeek(ThreadContext *tc, bool aarch64,
407                          std::vector<uint64_t> &argv)
408{
409    if (argv[1] > files.size() || !files[argv[1]])
410        return retError(EBADF);
411
412    int64_t ret = files[argv[1]]->seek(argv[2]);
413    if (ret < 0) {
414        return retError(-ret);
415    } else {
416        return retOK(0);
417    }
418}
419
420ArmSemihosting::RetErrno
421ArmSemihosting::callFLen(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(0);
432    }
433}
434
435ArmSemihosting::RetErrno
436ArmSemihosting::callTmpNam(ThreadContext *tc, bool aarch64,
437                           std::vector<uint64_t> &argv)
438{
439    const Addr guest_buf = argv[1];
440    //const uint64_t id = argv[2];
441    const uint64_t max_len = argv[3];
442
443    std::vector<char> buf(L_tmpnam);
444    char *path = tmpnam(buf.data());
445    if (!path)
446        return retError(EINVAL);
447
448    const size_t path_len = strlen(path);
449    if (path_len >= max_len)
450        return retError(ENOSPC);
451
452    tc->getPhysProxy().writeBlob(
453        guest_buf, (const uint8_t *)path, path_len + 1);
454    return retOK(0);
455}
456
457ArmSemihosting::RetErrno
458ArmSemihosting::callRemove(ThreadContext *tc, bool aarch64,
459                           std::vector<uint64_t> &argv)
460{
461    std::string fname = readString(tc, argv[1], argv[2]);
462
463    if (remove(fname.c_str()) != 0) {
464        return retError(errno);
465    } else {
466        return retOK(0);
467    }
468}
469
470ArmSemihosting::RetErrno
471ArmSemihosting::callRename(ThreadContext *tc, bool aarch64,
472                           std::vector<uint64_t> &argv)
473{
474    std::string from = readString(tc, argv[1], argv[2]);
475    std::string to = readString(tc, argv[3], argv[4]);
476
477    if (rename(from.c_str(), to.c_str()) != 0) {
478        return retError(errno);
479    } else {
480        return retOK(0);
481    }
482}
483
484ArmSemihosting::RetErrno
485ArmSemihosting::callClock(ThreadContext *tc, bool aarch64,
486                          std::vector<uint64_t> &argv)
487{
488    return retOK(curTick() / (SimClock::Int::s / 100));
489}
490
491ArmSemihosting::RetErrno
492ArmSemihosting::callTime(ThreadContext *tc, bool aarch64,
493                         std::vector<uint64_t> &argv)
494{
495    return retOK(timeBase + round(curTick() / SimClock::Float::s));
496}
497
498ArmSemihosting::RetErrno
499ArmSemihosting::callSystem(ThreadContext *tc, bool aarch64,
500                         std::vector<uint64_t> &argv)
501{
502    const std::string cmd = readString(tc, argv[1], argv[2]);
503    warn("Semihosting: SYS_SYSTEM not implemented. Guest tried to run: %s\n",
504         cmd);
505    return retError(EINVAL);
506
507}
508
509ArmSemihosting::RetErrno
510ArmSemihosting::callErrno(ThreadContext *tc, bool aarch64,
511                          std::vector<uint64_t> &argv)
512{
513    // Preserve errno by returning it in errno as well.
514    return RetErrno(semiErrno, semiErrno);
515}
516
517ArmSemihosting::RetErrno
518ArmSemihosting::callGetCmdLine(ThreadContext *tc, bool aarch64,
519                               std::vector<uint64_t> &argv)
520{
521    if (cmdLine.size() + 1 < argv[2]) {
522        PortProxy &proxy = tc->getPhysProxy();
523        ByteOrder endian = ArmISA::byteOrder(tc);
524        proxy.writeBlob(
525            (Addr)argv[1],
526            (const uint8_t *)cmdLine.c_str(), cmdLine.size() + 1);
527
528        if (aarch64)
529            proxy.writeHtoG<uint64_t>(argv[0] + 1 * 8, cmdLine.size(), endian);
530        else
531            proxy.writeHtoG<uint32_t>(argv[0] + 1 * 4, cmdLine.size(), endian);
532        return retOK(0);
533    } else {
534        return retError(0);
535    }
536}
537
538ArmSemihosting::RetErrno
539ArmSemihosting::callHeapInfo(ThreadContext *tc, bool aarch64,
540                             std::vector<uint64_t> &argv)
541{
542    const PhysicalMemory &phys = tc->getSystemPtr()->getPhysMem();
543    const AddrRangeList memories = phys.getConfAddrRanges();
544    fatal_if(memories.size() < 1, "No memories reported from System");
545    warn_if(memories.size() > 1, "Multiple physical memory ranges available. "
546            "Using first range heap/stack.");
547    const AddrRange memory = *memories.begin();
548    const Addr mem_start = memory.start() + memReserve;
549    Addr mem_end = memory.end();
550
551    // Make sure that 32-bit guests can access their memory.
552    if (!aarch64) {
553        const Addr phys_max = (1ULL << 32) - 1;
554        panic_if(mem_start > phys_max,
555                 "Physical memory out of range for a 32-bit guest.");
556        if (mem_end > phys_max) {
557            warn("Some physical memory out of range for a 32-bit guest.");
558            mem_end = phys_max;
559        }
560    }
561
562    fatal_if(mem_start + stackSize >= mem_end,
563             "Physical memory too small to fit desired stack and a heap.");
564
565    const Addr heap_base = mem_start;
566    const Addr heap_limit = mem_end - stackSize + 1;
567    const Addr stack_base = (mem_end + 1) & ~0x7ULL; // 8 byte stack alignment
568    const Addr stack_limit = heap_limit;
569
570
571    inform("Reporting heap/stack info to guest:\n"
572           "\tHeap base: 0x%x\n"
573           "\tHeap limit: 0x%x\n"
574           "\tStack base: 0x%x\n"
575           "\tStack limit: 0x%x\n",
576           heap_base, heap_limit, stack_base, stack_limit);
577
578    Addr base = argv[1];
579    PortProxy &proxy = tc->getPhysProxy();
580    ByteOrder endian = ArmISA::byteOrder(tc);
581    if (aarch64) {
582        proxy.writeHtoG<uint64_t>(base + 0 * 8, heap_base, endian);
583        proxy.writeHtoG<uint64_t>(base + 1 * 8, heap_limit, endian);
584        proxy.writeHtoG<uint64_t>(base + 2 * 8, stack_base, endian);
585        proxy.writeHtoG<uint64_t>(base + 3 * 8, stack_limit, endian);
586    } else {
587        proxy.writeHtoG<uint32_t>(base + 0 * 4, heap_base, endian);
588        proxy.writeHtoG<uint32_t>(base + 1 * 4, heap_limit, endian);
589        proxy.writeHtoG<uint32_t>(base + 2 * 4, stack_base, endian);
590        proxy.writeHtoG<uint32_t>(base + 3 * 4, stack_limit, endian);
591    }
592
593    return retOK(0);
594}
595
596ArmSemihosting::RetErrno
597ArmSemihosting::callExit(ThreadContext *tc, bool aarch64,
598                         std::vector<uint64_t> &argv)
599{
600    if (aarch64) {
601        semiExit(argv[1], argv[2]);
602    } else {
603        semiExit(argv[0], 0);
604    }
605
606    return retOK(0);
607}
608
609ArmSemihosting::RetErrno
610ArmSemihosting::callExitExtended(ThreadContext *tc, bool aarch64,
611                                 std::vector<uint64_t> &argv)
612{
613    semiExit(argv[1], argv[2]);
614
615    return retOK(0);
616}
617
618void
619ArmSemihosting::semiExit(uint64_t code, uint64_t subcode)
620{
621    auto it = exitCodes.find(code);
622    if (it != exitCodes.end()) {
623        exitSimLoop(it->second, subcode);
624    } else {
625        exitSimLoop(csprintf("semi:0x%x", code), subcode);
626    }
627}
628
629
630ArmSemihosting::RetErrno
631ArmSemihosting::callElapsed(ThreadContext *tc, bool aarch64,
632                            std::vector<uint64_t> &argv)
633{
634    PortProxy &proxy = tc->getPhysProxy();
635    ByteOrder endian = ArmISA::byteOrder(tc);
636    const uint64_t tick = semiTick(curTick());
637
638    if (aarch64) {
639        proxy.writeHtoG<uint64_t>(argv[0], tick, endian);
640    } else {
641        proxy.writeHtoG<uint32_t>(argv[0] + 0 * 4, tick, endian);
642        proxy.writeHtoG<uint32_t>(argv[0] + 1 * 4, tick >> 32, endian);
643    }
644
645    return retOK(0);
646}
647
648
649ArmSemihosting::RetErrno
650ArmSemihosting::callTickFreq(ThreadContext *tc, bool aarch64,
651                             std::vector<uint64_t> &argv)
652{
653    return retOK(semiTick(SimClock::Frequency));
654}
655
656const ArmSemihosting::SemiCall *
657ArmSemihosting::getCall(uint32_t op, bool aarch64)
658{
659    auto it = calls.find(op);
660    if (it == calls.end())
661        return nullptr;
662    else {
663        return &it->second;
664    }
665}
666
667std::unique_ptr<ArmSemihosting::FileBase>
668ArmSemihosting::FileBase::create(
669    ArmSemihosting &parent, const std::string &fname, const char *mode)
670{
671    std::unique_ptr<FileBase> file;
672    if (fname == ":semihosting-features") {
673        file.reset(new FileFeatures(parent, fname.c_str(), mode));
674    } else {
675        file.reset(new File(parent, fname.c_str(), mode));
676    }
677
678    return file;
679}
680
681std::unique_ptr<ArmSemihosting::FileBase>
682ArmSemihosting::FileBase::create(ArmSemihosting &parent,
683                                 CheckpointIn &cp, const std::string &sec)
684{
685    std::unique_ptr<FileBase> file;
686    ScopedCheckpointSection _sec(cp, sec);
687
688    // Was the file open when the checkpoint was created?
689    if (!cp.sectionExists(Serializable::currentSection()))
690        return file;
691
692    std::string fname, mode;
693    paramIn(cp, "name", fname);
694    paramIn(cp, "mode", mode);
695    file = create(parent, fname, mode.c_str());
696    assert(file);
697    file->unserialize(cp);
698
699    return file;
700}
701
702void
703ArmSemihosting::FileBase::serialize(CheckpointOut &cp) const
704{
705    paramOut(cp, "name", _name);
706    SERIALIZE_SCALAR(mode);
707}
708
709void
710ArmSemihosting::FileBase::unserialize(CheckpointIn &cp)
711{
712    /* Unserialization of name and mode happens in
713     * ArmSemihosting::FileBase::create() */
714}
715
716int64_t
717ArmSemihosting::FileBase::read(uint8_t *buffer, uint64_t size)
718{
719    return -EINVAL;
720}
721
722int64_t
723ArmSemihosting::FileBase::write(const uint8_t *buffer, uint64_t size)
724{
725    return -EINVAL;
726}
727
728int64_t
729ArmSemihosting::FileBase::seek(uint64_t pos)
730{
731    return -EINVAL;
732}
733
734int64_t
735ArmSemihosting::FileBase::flen()
736{
737    return -EINVAL;
738}
739
740
741ArmSemihosting::FileFeatures::FileFeatures(
742    ArmSemihosting &_parent, const char *_name, const char *_mode)
743    : FileBase(_parent, _name, _mode)
744{
745}
746
747int64_t
748ArmSemihosting::FileFeatures::read(uint8_t *buffer, uint64_t size)
749{
750    int64_t len = 0;
751
752    for (; pos < size && pos < ArmSemihosting::features.size(); pos++)
753        buffer[len++] = ArmSemihosting::features[pos];
754
755    return len;
756}
757
758int64_t
759ArmSemihosting::FileFeatures::seek(uint64_t _pos)
760{
761    if (_pos < ArmSemihosting::features.size()) {
762        pos = _pos;
763        return 0;
764    } else {
765        return -ENXIO;
766    }
767}
768
769void
770ArmSemihosting::FileFeatures::serialize(CheckpointOut &cp) const
771{
772    FileBase::serialize(cp);
773    SERIALIZE_SCALAR(pos);
774}
775
776void
777ArmSemihosting::FileFeatures::unserialize(CheckpointIn &cp)
778{
779    FileBase::unserialize(cp);
780    UNSERIALIZE_SCALAR(pos);
781}
782
783
784
785ArmSemihosting::File::File(ArmSemihosting &_parent,
786                           const char *_name, const char *_perms)
787    : FileBase(_parent, _name, _perms),
788      file(nullptr)
789{
790}
791
792ArmSemihosting::File::~File()
793{
794    if (file)
795        close();
796}
797
798int64_t
799ArmSemihosting::File::openImpl(bool in_cpt)
800{
801    panic_if(file, "Trying to open an already open file.\n");
802
803    if (_name == ":tt") {
804        if (mode[0] == 'r') {
805            file = stdin;
806        } else if (mode[0] == 'w') {
807            file = stdout;
808        } else if (mode[0] == 'a') {
809            file = stderr;
810        } else {
811            warn("Unknown file mode for the ':tt' special file");
812            return -EINVAL;
813        }
814    } else {
815        std::string real_mode(this->mode);
816        // Avoid truncating the file if we are restoring from a
817        // checkpoint.
818        if (in_cpt && real_mode[0] == 'w')
819            real_mode[0] = 'a';
820
821        file = fopen(_name.c_str(), real_mode.c_str());
822    }
823
824    return file ? 0 : -errno;
825}
826
827int64_t
828ArmSemihosting::File::close()
829{
830    panic_if(!file, "Trying to close an already closed file.\n");
831
832    if (needClose()) {
833        fclose(file);
834    }
835    file = nullptr;
836
837    return 0;
838}
839
840bool
841ArmSemihosting::File::isTTY() const
842{
843    return file == stdout || file == stderr || file == stdin;
844}
845
846int64_t
847ArmSemihosting::File::read(uint8_t *buffer, uint64_t size)
848{
849    panic_if(!file, "Trying to read from a closed file");
850
851    size_t ret = fread(buffer, 1, size, file);
852    if (ret == 0) {
853        // Error or EOF. Assume errors are due to invalid file
854        // operations (e.g., reading a write-only stream).
855        return ferror(file) ? -EINVAL : 0;
856    } else {
857        return ret;
858    }
859}
860
861int64_t
862ArmSemihosting::File::write(const uint8_t *buffer, uint64_t size)
863{
864    panic_if(!file, "Trying to write to a closed file");
865
866
867    size_t ret = fwrite(buffer, 1, size, file);
868    if (ret == 0) {
869        // Assume errors are due to invalid file operations (e.g.,
870        // writing a read-only stream).
871        return -EINVAL;
872    } else {
873        return ret;
874    }
875}
876
877int64_t
878ArmSemihosting::File::seek(uint64_t _pos)
879{
880    panic_if(!file, "Trying to seek in a closed file");
881
882    errno = 0;
883    if (fseek(file, _pos, SEEK_SET) == 0)
884        return 0;
885    else
886        return -errno;
887}
888
889int64_t
890ArmSemihosting::File::flen()
891{
892    errno = 0;
893    long pos = ftell(file);
894    if (pos < 0)
895        return -errno;
896
897    if (fseek(file, 0, SEEK_END) != 0)
898        return -errno;
899
900    long len = ftell(file);
901    if (len < 0)
902        return -errno;
903
904    if (fseek(file, pos, SEEK_SET) != 0)
905        return -errno;
906
907    return len;
908}
909
910
911void
912ArmSemihosting::File::serialize(CheckpointOut &cp) const
913{
914    FileBase::serialize(cp);
915
916    if (!isTTY()) {
917        long pos = file ? ftell(file) : 0;
918        panic_if(pos < 0, "Failed to get file position.");
919        SERIALIZE_SCALAR(pos);
920    }
921}
922
923void
924ArmSemihosting::File::unserialize(CheckpointIn &cp)
925{
926    FileBase::unserialize(cp);
927
928    if (openImpl(true) < 0) {
929        fatal("Failed to open file: %s", _name);
930    }
931
932    if (!isTTY()) {
933        long pos = 0;
934        UNSERIALIZE_SCALAR(pos);
935        if (fseek(file, pos, SEEK_SET) != 0) {
936            fatal("Failed seek to current position (%i) in '%s'", pos, _name);
937        }
938    }
939}
940
941
942ArmSemihosting *
943ArmSemihostingParams::create()
944{
945    return new ArmSemihosting(this);
946}
947