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, 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(guest_buf, path, path_len + 1);
483    return retOK(0);
484}
485
486ArmSemihosting::RetErrno
487ArmSemihosting::callRemove(ThreadContext *tc, bool aarch64,
488                           std::vector<uint64_t> &argv)
489{
490    std::string fname = readString(tc, argv[1], argv[2]);
491
492    if (remove(fname.c_str()) != 0) {
493        return retError(errno);
494    } else {
495        return retOK(0);
496    }
497}
498
499ArmSemihosting::RetErrno
500ArmSemihosting::callRename(ThreadContext *tc, bool aarch64,
501                           std::vector<uint64_t> &argv)
502{
503    std::string from = readString(tc, argv[1], argv[2]);
504    std::string to = readString(tc, argv[3], argv[4]);
505
506    if (rename(from.c_str(), to.c_str()) != 0) {
507        return retError(errno);
508    } else {
509        return retOK(0);
510    }
511}
512
513ArmSemihosting::RetErrno
514ArmSemihosting::callClock(ThreadContext *tc, bool aarch64,
515                          std::vector<uint64_t> &argv)
516{
517    return retOK(curTick() / (SimClock::Int::s / 100));
518}
519
520ArmSemihosting::RetErrno
521ArmSemihosting::callTime(ThreadContext *tc, bool aarch64,
522                         std::vector<uint64_t> &argv)
523{
524    return retOK(timeBase + round(curTick() / SimClock::Float::s));
525}
526
527ArmSemihosting::RetErrno
528ArmSemihosting::callSystem(ThreadContext *tc, bool aarch64,
529                         std::vector<uint64_t> &argv)
530{
531    const std::string cmd = readString(tc, argv[1], argv[2]);
532    warn("Semihosting: SYS_SYSTEM not implemented. Guest tried to run: %s\n",
533         cmd);
534    return retError(EINVAL);
535
536}
537
538ArmSemihosting::RetErrno
539ArmSemihosting::callErrno(ThreadContext *tc, bool aarch64,
540                          std::vector<uint64_t> &argv)
541{
542    // Preserve errno by returning it in errno as well.
543    return RetErrno(semiErrno, semiErrno);
544}
545
546ArmSemihosting::RetErrno
547ArmSemihosting::callGetCmdLine(ThreadContext *tc, bool aarch64,
548                               std::vector<uint64_t> &argv)
549{
550    if (cmdLine.size() + 1 < argv[2]) {
551        PortProxy &proxy = physProxy(tc);
552        ByteOrder endian = ArmISA::byteOrder(tc);
553        proxy.writeBlob((Addr)argv[1], cmdLine.c_str(), cmdLine.size() + 1);
554
555        if (aarch64)
556            proxy.write<uint64_t>(argv[0] + 1 * 8, cmdLine.size(), endian);
557        else
558            proxy.write<uint32_t>(argv[0] + 1 * 4, cmdLine.size(), endian);
559        return retOK(0);
560    } else {
561        return retError(0);
562    }
563}
564
565ArmSemihosting::RetErrno
566ArmSemihosting::callHeapInfo(ThreadContext *tc, bool aarch64,
567                             std::vector<uint64_t> &argv)
568{
569    const PhysicalMemory &phys = tc->getSystemPtr()->getPhysMem();
570    const AddrRangeList memories = phys.getConfAddrRanges();
571    fatal_if(memories.size() < 1, "No memories reported from System");
572    warn_if(memories.size() > 1, "Multiple physical memory ranges available. "
573            "Using first range heap/stack.");
574    const AddrRange memory = *memories.begin();
575    const Addr mem_start = memory.start() + memReserve;
576    Addr mem_end = memory.end();
577
578    // Make sure that 32-bit guests can access their memory.
579    if (!aarch64) {
580        const Addr phys_max = (1ULL << 32) - 1;
581        panic_if(mem_start > phys_max,
582                 "Physical memory out of range for a 32-bit guest.");
583        if (mem_end > phys_max) {
584            warn("Some physical memory out of range for a 32-bit guest.");
585            mem_end = phys_max;
586        }
587    }
588
589    fatal_if(mem_start + stackSize >= mem_end,
590             "Physical memory too small to fit desired stack and a heap.");
591
592    const Addr heap_base = mem_start;
593    const Addr heap_limit = mem_end - stackSize + 1;
594    const Addr stack_base = (mem_end + 1) & ~0x7ULL; // 8 byte stack alignment
595    const Addr stack_limit = heap_limit;
596
597
598    inform("Reporting heap/stack info to guest:\n"
599           "\tHeap base: 0x%x\n"
600           "\tHeap limit: 0x%x\n"
601           "\tStack base: 0x%x\n"
602           "\tStack limit: 0x%x\n",
603           heap_base, heap_limit, stack_base, stack_limit);
604
605    Addr base = argv[1];
606    PortProxy &proxy = physProxy(tc);
607    ByteOrder endian = ArmISA::byteOrder(tc);
608    if (aarch64) {
609        proxy.write<uint64_t>(base + 0 * 8, heap_base, endian);
610        proxy.write<uint64_t>(base + 1 * 8, heap_limit, endian);
611        proxy.write<uint64_t>(base + 2 * 8, stack_base, endian);
612        proxy.write<uint64_t>(base + 3 * 8, stack_limit, endian);
613    } else {
614        proxy.write<uint32_t>(base + 0 * 4, heap_base, endian);
615        proxy.write<uint32_t>(base + 1 * 4, heap_limit, endian);
616        proxy.write<uint32_t>(base + 2 * 4, stack_base, endian);
617        proxy.write<uint32_t>(base + 3 * 4, stack_limit, endian);
618    }
619
620    return retOK(0);
621}
622
623ArmSemihosting::RetErrno
624ArmSemihosting::callExit(ThreadContext *tc, bool aarch64,
625                         std::vector<uint64_t> &argv)
626{
627    if (aarch64) {
628        semiExit(argv[1], argv[2]);
629    } else {
630        semiExit(argv[0], 0);
631    }
632
633    return retOK(0);
634}
635
636ArmSemihosting::RetErrno
637ArmSemihosting::callExitExtended(ThreadContext *tc, bool aarch64,
638                                 std::vector<uint64_t> &argv)
639{
640    semiExit(argv[1], argv[2]);
641
642    return retOK(0);
643}
644
645void
646ArmSemihosting::semiExit(uint64_t code, uint64_t subcode)
647{
648    auto it = exitCodes.find(code);
649    if (it != exitCodes.end()) {
650        exitSimLoop(it->second, subcode);
651    } else {
652        exitSimLoop(csprintf("semi:0x%x", code), subcode);
653    }
654}
655
656
657ArmSemihosting::RetErrno
658ArmSemihosting::callElapsed(ThreadContext *tc, bool aarch64,
659                            std::vector<uint64_t> &argv)
660{
661    PortProxy &proxy = physProxy(tc);
662    ByteOrder endian = ArmISA::byteOrder(tc);
663    const uint64_t tick = semiTick(curTick());
664
665    if (aarch64) {
666        proxy.write<uint64_t>(argv[0], tick, endian);
667    } else {
668        proxy.write<uint32_t>(argv[0] + 0 * 4, tick, endian);
669        proxy.write<uint32_t>(argv[0] + 1 * 4, tick >> 32, endian);
670    }
671
672    return retOK(0);
673}
674
675
676ArmSemihosting::RetErrno
677ArmSemihosting::callTickFreq(ThreadContext *tc, bool aarch64,
678                             std::vector<uint64_t> &argv)
679{
680    return retOK(semiTick(SimClock::Frequency));
681}
682
683const ArmSemihosting::SemiCall *
684ArmSemihosting::getCall(uint32_t op, bool aarch64)
685{
686    auto it = calls.find(op);
687    if (it == calls.end())
688        return nullptr;
689    else {
690        return &it->second;
691    }
692}
693
694FILE *
695ArmSemihosting::getSTDIO(const char *stream_name,
696                         const std::string &name, const char *mode)
697{
698    auto it = stdioMap.find(name);
699    if (it == stdioMap.end()) {
700        FILE *f = fopen(name.c_str(), mode);
701        if (!f) {
702            fatal("Failed to open %s (%s): %s\n",
703                  stream_name, name, strerror(errno));
704        }
705        return f;
706    } else {
707        return it->second;
708    }
709}
710
711std::unique_ptr<ArmSemihosting::FileBase>
712ArmSemihosting::FileBase::create(
713    ArmSemihosting &parent, const std::string &fname, const char *mode)
714{
715    std::unique_ptr<FileBase> file;
716    if (fname == ":semihosting-features") {
717        file.reset(new FileFeatures(parent, fname.c_str(), mode));
718    } else {
719        file.reset(new File(parent, fname.c_str(), mode));
720    }
721
722    return file;
723}
724
725std::unique_ptr<ArmSemihosting::FileBase>
726ArmSemihosting::FileBase::create(ArmSemihosting &parent,
727                                 CheckpointIn &cp, const std::string &sec)
728{
729    std::unique_ptr<FileBase> file;
730    ScopedCheckpointSection _sec(cp, sec);
731
732    // Was the file open when the checkpoint was created?
733    if (!cp.sectionExists(Serializable::currentSection()))
734        return file;
735
736    std::string fname, mode;
737    paramIn(cp, "name", fname);
738    paramIn(cp, "mode", mode);
739    file = create(parent, fname, mode.c_str());
740    assert(file);
741    file->unserialize(cp);
742
743    return file;
744}
745
746void
747ArmSemihosting::FileBase::serialize(CheckpointOut &cp) const
748{
749    paramOut(cp, "name", _name);
750    SERIALIZE_SCALAR(mode);
751}
752
753void
754ArmSemihosting::FileBase::unserialize(CheckpointIn &cp)
755{
756    /* Unserialization of name and mode happens in
757     * ArmSemihosting::FileBase::create() */
758}
759
760int64_t
761ArmSemihosting::FileBase::read(uint8_t *buffer, uint64_t size)
762{
763    return -EINVAL;
764}
765
766int64_t
767ArmSemihosting::FileBase::write(const uint8_t *buffer, uint64_t size)
768{
769    return -EINVAL;
770}
771
772int64_t
773ArmSemihosting::FileBase::seek(uint64_t pos)
774{
775    return -EINVAL;
776}
777
778int64_t
779ArmSemihosting::FileBase::flen()
780{
781    return -EINVAL;
782}
783
784
785ArmSemihosting::FileFeatures::FileFeatures(
786    ArmSemihosting &_parent, const char *_name, const char *_mode)
787    : FileBase(_parent, _name, _mode)
788{
789}
790
791int64_t
792ArmSemihosting::FileFeatures::read(uint8_t *buffer, uint64_t size)
793{
794    int64_t len = 0;
795
796    for (; pos < size && pos < ArmSemihosting::features.size(); pos++)
797        buffer[len++] = ArmSemihosting::features[pos];
798
799    return len;
800}
801
802int64_t
803ArmSemihosting::FileFeatures::seek(uint64_t _pos)
804{
805    if (_pos < ArmSemihosting::features.size()) {
806        pos = _pos;
807        return 0;
808    } else {
809        return -ENXIO;
810    }
811}
812
813void
814ArmSemihosting::FileFeatures::serialize(CheckpointOut &cp) const
815{
816    FileBase::serialize(cp);
817    SERIALIZE_SCALAR(pos);
818}
819
820void
821ArmSemihosting::FileFeatures::unserialize(CheckpointIn &cp)
822{
823    FileBase::unserialize(cp);
824    UNSERIALIZE_SCALAR(pos);
825}
826
827
828
829ArmSemihosting::File::File(ArmSemihosting &_parent,
830                           const char *_name, const char *_perms)
831    : FileBase(_parent, _name, _perms),
832      file(nullptr)
833{
834}
835
836ArmSemihosting::File::~File()
837{
838    if (file)
839        close();
840}
841
842int64_t
843ArmSemihosting::File::openImpl(bool in_cpt)
844{
845    panic_if(file, "Trying to open an already open file.\n");
846
847    if (_name == ":tt") {
848        if (mode[0] == 'r') {
849            file = parent.stdin;
850        } else if (mode[0] == 'w') {
851            file = parent.stdout;
852        } else if (mode[0] == 'a') {
853            file = parent.stderr;
854        } else {
855            warn("Unknown file mode for the ':tt' special file");
856            return -EINVAL;
857        }
858    } else {
859        std::string real_mode(this->mode);
860        // Avoid truncating the file if we are restoring from a
861        // checkpoint.
862        if (in_cpt && real_mode[0] == 'w')
863            real_mode[0] = 'a';
864
865        file = fopen(_name.c_str(), real_mode.c_str());
866    }
867
868    return file ? 0 : -errno;
869}
870
871int64_t
872ArmSemihosting::File::close()
873{
874    panic_if(!file, "Trying to close an already closed file.\n");
875
876    if (needClose()) {
877        fclose(file);
878    }
879    file = nullptr;
880
881    return 0;
882}
883
884bool
885ArmSemihosting::File::isTTY() const
886{
887    return file == parent.stdout ||
888        file == parent.stderr ||
889        file == parent.stdin;
890}
891
892int64_t
893ArmSemihosting::File::read(uint8_t *buffer, uint64_t size)
894{
895    panic_if(!file, "Trying to read from a closed file");
896
897    size_t ret = fread(buffer, 1, size, file);
898    if (ret == 0) {
899        // Error or EOF. Assume errors are due to invalid file
900        // operations (e.g., reading a write-only stream).
901        return ferror(file) ? -EINVAL : 0;
902    } else {
903        return ret;
904    }
905}
906
907int64_t
908ArmSemihosting::File::write(const uint8_t *buffer, uint64_t size)
909{
910    panic_if(!file, "Trying to write to a closed file");
911
912
913    size_t ret = fwrite(buffer, 1, size, file);
914    if (ret == 0) {
915        // Assume errors are due to invalid file operations (e.g.,
916        // writing a read-only stream).
917        return -EINVAL;
918    } else {
919        return ret;
920    }
921}
922
923int64_t
924ArmSemihosting::File::seek(uint64_t _pos)
925{
926    panic_if(!file, "Trying to seek in a closed file");
927
928    errno = 0;
929    if (fseek(file, _pos, SEEK_SET) == 0)
930        return 0;
931    else
932        return -errno;
933}
934
935int64_t
936ArmSemihosting::File::flen()
937{
938    errno = 0;
939    long pos = ftell(file);
940    if (pos < 0)
941        return -errno;
942
943    if (fseek(file, 0, SEEK_END) != 0)
944        return -errno;
945
946    long len = ftell(file);
947    if (len < 0)
948        return -errno;
949
950    if (fseek(file, pos, SEEK_SET) != 0)
951        return -errno;
952
953    return len;
954}
955
956
957void
958ArmSemihosting::File::serialize(CheckpointOut &cp) const
959{
960    FileBase::serialize(cp);
961
962    if (!isTTY()) {
963        long pos = file ? ftell(file) : 0;
964        panic_if(pos < 0, "Failed to get file position.");
965        SERIALIZE_SCALAR(pos);
966    }
967}
968
969void
970ArmSemihosting::File::unserialize(CheckpointIn &cp)
971{
972    FileBase::unserialize(cp);
973
974    if (openImpl(true) < 0) {
975        fatal("Failed to open file: %s", _name);
976    }
977
978    if (!isTTY()) {
979        long pos = 0;
980        UNSERIALIZE_SCALAR(pos);
981        if (fseek(file, pos, SEEK_SET) != 0) {
982            fatal("Failed seek to current position (%i) in '%s'", pos, _name);
983        }
984    }
985}
986
987
988ArmSemihosting *
989ArmSemihostingParams::create()
990{
991    return new ArmSemihosting(this);
992}
993