summaryrefslogtreecommitdiff
path: root/src/arch/arm/semihosting.cc
blob: 98b50f46899b3ad6207d32b3662a47a98b714843 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
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);
}