forked from chipsalliance/VeeR-ISS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
whisper.cpp
1869 lines (1608 loc) · 53.7 KB
/
whisper.cpp
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
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 Western Digital Corporation or its affiliates.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <iostream>
#include <fstream>
#include <sstream>
#include <thread>
#include <atomic>
#if defined(__cpp_lib_filesystem)
#include <filesystem>
namespace FileSystem = std::filesystem;
#else
#include <experimental/filesystem>
namespace FileSystem = std::experimental::filesystem;
#endif
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#ifdef __MINGW64__
#include <winsock2.h>
typedef int socklen_t;
#define close(s) closesocket((s))
#define setlinebuf(f) setvbuf((f),NULL,_IOLBF,0)
#define strerror_r(a,b,c) strerror((a))
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#endif
#include <csignal>
#include "HartConfig.hpp"
#include "WhisperMessage.h"
#include "Hart.hpp"
#include "Core.hpp"
#include "System.hpp"
#include "Server.hpp"
#include "Interactive.hpp"
using namespace WdRiscv;
/// Return format string suitable for printing an integer of type URV
/// in hexadecimal form.
template <typename URV>
static
const char*
getHexForm()
{
if (sizeof(URV) == 4)
return "0x%08x";
if (sizeof(URV) == 8)
return "0x%016x";
if (sizeof(URV) == 16)
return "0x%032x";
return "0x%x";
}
/// Convert the command line string numberStr to a number using
/// strotull and a base of zero (prefixes 0 and 0x are
/// honored). Return true on success and false on failure (string does
/// not represent a number). TYPE is an integer type (e.g
/// uint32_t). Option is the command line option associated with the
/// string and is used for diagnostic messages.
template <typename TYPE>
static
bool
parseCmdLineNumber(const std::string& option,
const std::string& numberStr,
TYPE& number)
{
std::string str = numberStr;
bool good = not str.empty();
uint64_t scale = 1;
if (good)
{
char suffix = str.back();
if (suffix == 'k')
scale = 1024;
else if (suffix == 'm')
scale = 1024*1024;
else if (suffix == 'g')
scale = 1024*1024*1024;
if (scale != 1)
{
str = str.substr(0, str.length() - 1);
if (str.empty())
good = false;
}
}
if (good)
{
typedef typename std::make_signed_t<TYPE> STYPE;
char* end = nullptr;
bool bad = false;
if (std::is_same<TYPE, STYPE>::value)
{
int64_t val = strtoll(str.c_str(), &end, 0) * scale;
number = static_cast<TYPE>(val);
bad = val != number;
}
else
{
uint64_t val = strtoull(str.c_str(), &end, 0) * scale;
number = static_cast<TYPE>(val);
bad = val != number;
}
if (bad)
{
std::cerr << "parseCmdLineNumber: Number too large: " << numberStr
<< '\n';
return false;
}
if (end and *end)
good = false; // Part of the string are non parseable.
}
if (not good)
std::cerr << "Invalid command line " << option << " value: " << numberStr
<< '\n';
return good;
}
/// Aapter for the parseCmdLineNumber for optionals.
template <typename TYPE>
static
bool
parseCmdLineNumber(const std::string& option,
const std::string& numberStr,
std::optional<TYPE>& number)
{
TYPE n;
if (not parseCmdLineNumber(option, numberStr, n))
return false;
number = n;
return true;
}
typedef std::vector<std::string> StringVec;
/// Hold values provided on the command line.
struct Args
{
StringVec hexFiles; // Hex files to be loaded into simulator memory.
std::string traceFile; // Log of state change after each instruction.
std::string commandLogFile; // Log of interactive or socket commands.
std::string consoleOutFile; // Console io output file.
std::string serverFile; // File in which to write server host and port.
std::string instFreqFile; // Instruction frequency file.
std::string configFile; // Configuration (JSON) file.
std::string isa;
std::string snapshotDir = "snapshot"; // Dir prefix for saving snapshots
std::string loadFrom; // Directory for loading a snapshot
std::string stdoutFile; // Redirect target program stdout to this.
std::string stderrFile; // Redirect target program stderr to this.
StringVec zisa;
StringVec regInits; // Initial values of regs
StringVec targets; // Target (ELF file) programs and associated
// program options to be loaded into simulator
// memory. Each target plus args is one string.
std::string targetSep = " "; // Target program argument separator.
std::optional<std::string> toHostSym;
std::optional<std::string> consoleIoSym;
// Ith item is a vector of strings representing ith target and its args.
std::vector<StringVec> expandedTargets;
std::optional<uint64_t> startPc;
std::optional<uint64_t> endPc;
std::optional<uint64_t> toHost;
std::optional<uint64_t> consoleIo;
std::optional<uint64_t> instCountLim;
std::optional<uint64_t> memorySize;
std::optional<uint64_t> snapshotPeriod;
std::optional<uint64_t> alarmInterval;
std::optional<uint64_t> swInterrupt; // Sotware interrupt mem mapped address
std::optional<uint64_t> clint; // Clint mem mapped address
std::optional<uint64_t> syscallSlam;
unsigned regWidth = 32;
unsigned harts = 1;
unsigned cores = 1;
unsigned pageSize = 4*1024;
bool help = false;
bool hasRegWidth = false;
bool hasHarts = false;
bool hasCores = false;
bool trace = false;
bool interactive = false;
bool verbose = false;
bool version = false;
bool traceLdSt = false; // Trace ld/st data address if true.
bool triggers = false; // Enable debug triggers when true.
bool counters = false; // Enable performance counters when true.
bool gdb = false; // Enable gdb mode when true.
std::vector<unsigned> gdbTcpPort; // Enable gdb mode over TCP when port is positive.
bool abiNames = false; // Use ABI register names in inst disassembly.
bool newlib = false; // True if target program linked with newlib.
bool linux = false; // True if target program linked with Linux C-lib.
bool raw = false; // True if bare-metal program (no linux no newlib).
bool elfisa = false; // Use ELF file RISCV architecture tags to set MISA if true.
bool fastExt = false; // True if fast external interrupt dispatch enabled.
bool unmappedElfOk = false;
bool iccmRw = false;
bool quitOnAnyHart = false; // True if run quits when any hart finishes.
bool noConInput = false; // If true console io address is not used for input (ld).
// Expand each target program string into program name and args.
void expandTargets();
};
void
Args::expandTargets()
{
this->expandedTargets.clear();
for (const auto& target : this->targets)
{
StringVec tokens;
boost::split(tokens, target, boost::is_any_of(this->targetSep),
boost::token_compress_on);
this->expandedTargets.push_back(tokens);
}
}
static
void
printVersion()
{
unsigned version = 1;
unsigned subversion = 687;
std::cout << "Version " << version << "." << subversion << " compiled on "
<< __DATE__ << " at " << __TIME__ << '\n';
}
static
bool
collectCommandLineValues(const boost::program_options::variables_map& varMap,
Args& args)
{
bool ok = true;
if (varMap.count("startpc"))
{
auto numStr = varMap["startpc"].as<std::string>();
if (not parseCmdLineNumber("startpc", numStr, args.startPc))
ok = false;
}
if (varMap.count("endpc"))
{
auto numStr = varMap["endpc"].as<std::string>();
if (not parseCmdLineNumber("endpc", numStr, args.endPc))
ok = false;
}
if (varMap.count("tohost"))
{
auto numStr = varMap["tohost"].as<std::string>();
if (not parseCmdLineNumber("tohost", numStr, args.toHost))
ok = false;
}
if (varMap.count("consoleio"))
{
auto numStr = varMap["consoleio"].as<std::string>();
if (not parseCmdLineNumber("consoleio", numStr, args.consoleIo))
ok = false;
}
if (varMap.count("maxinst"))
{
auto numStr = varMap["maxinst"].as<std::string>();
if (not parseCmdLineNumber("maxinst", numStr, args.instCountLim))
ok = false;
}
if (varMap.count("memorysize"))
{
auto numStr = varMap["memorysize"].as<std::string>();
if (not parseCmdLineNumber("memorysize", numStr, args.memorySize))
ok = false;
}
if (varMap.count("snapshotperiod"))
{
auto numStr = varMap["snapshotperiod"].as<std::string>();
if (not parseCmdLineNumber("snapshotperiod", numStr, args.snapshotPeriod))
ok = false;
else if (*args.snapshotPeriod == 0)
std::cerr << "Warning: Zero snapshot period ignored.\n";
}
if (varMap.count("tohostsym"))
args.toHostSym = varMap["tohostsym"].as<std::string>();
if (varMap.count("consoleiosym"))
args.consoleIoSym = varMap["consoleiosym"].as<std::string>();
if (varMap.count("xlen"))
args.hasRegWidth = true;
if (varMap.count("cores"))
args.hasCores = true;
if (varMap.count("harts"))
args.hasHarts = true;
if (varMap.count("alarm"))
{
auto numStr = varMap["alarm"].as<std::string>();
if (not parseCmdLineNumber("alarm", numStr, args.alarmInterval))
ok = false;
else if (*args.alarmInterval == 0)
std::cerr << "Warning: Zero alarm period ignored.\n";
}
if (varMap.count("clint"))
{
auto numStr = varMap["clint"].as<std::string>();
if (not parseCmdLineNumber("clint", numStr, args.clint))
ok = false;
else if ((*args.clint & 7) != 0)
{
std::cerr << "Error: clint address must be a multiple of 8\n";
ok = false;
}
}
if (varMap.count("softinterrupt"))
{
auto numStr = varMap["softinterrupt"].as<std::string>();
if (not parseCmdLineNumber("softinterrupt", numStr, args.swInterrupt))
ok = false;
else if ((*args.swInterrupt & 3) != 0)
{
std::cerr << "Error: softinterrupt address must be a multiple of 4\n";
ok = false;
}
}
if (varMap.count("syscallslam"))
{
auto numStr = varMap["syscallslam"].as<std::string>();
if (not parseCmdLineNumber("syscallslam", numStr, args.syscallSlam))
ok = false;
}
if (args.interactive)
args.trace = true; // Enable instruction tracing in interactive mode.
return ok;
}
/// Parse command line arguments. Place option values in args.
/// Return true on success and false on failure. Exists program
/// if --help is used.
static
bool
parseCmdLineArgs(int argc, char* argv[], Args& args)
{
try
{
// Define command line options.
namespace po = boost::program_options;
po::options_description desc("options");
desc.add_options()
("help,h", po::bool_switch(&args.help),
"Produce this message.")
("log,l", po::bool_switch(&args.trace),
"Enable tracing to standard output of executed instructions.")
("isa", po::value(&args.isa),
"Specify instruction set extensions to enable. Supported extensions "
"are a, c, d, f, i, m, s and u. Default is imc.")
("zisa", po::value(&args.zisa)->multitoken(),
"Specify instruction set z-extension to enable. Only z-extensions "
"currently supported are zbb and zbs (Exammple --zisa zbb)")
("xlen", po::value(&args.regWidth),
"Specify register width (32 or 64), defaults to 32")
("harts", po::value(&args.harts),
"Specify number of hardware threads per core (default=1).")
("cores", po::value(&args.cores),
"Specify number of core per system (default=1).")
("pagesize", po::value(&args.pageSize),
"Specify memory page size.")
("target,t", po::value(&args.targets)->multitoken(),
"Target program (ELF file) to load into simulator memory. In "
"newlib/Linux emulation mode, program options may follow program name.")
("targetsep", po::value(&args.targetSep),
"Target program argument separator.")
("hex,x", po::value(&args.hexFiles)->multitoken(),
"HEX file to load into simulator memory.")
("logfile,f", po::value(&args.traceFile),
"Enable tracing to given file of executed instructions.")
("consoleoutfile", po::value(&args.consoleOutFile),
"Redirect console output to given file.")
("commandlog", po::value(&args.commandLogFile),
"Enable logging of interactive/socket commands to the given file.")
("server", po::value(&args.serverFile),
"Interactive server mode. Put server hostname and port in file.")
("startpc,s", po::value<std::string>(),
"Set program entry point. If not specified, use entry point of the "
"most recently loaded ELF file.")
("endpc,e", po::value<std::string>(),
"Set stop program counter. Simulator will stop once instruction at "
"the stop program counter is executed.")
("tohost", po::value<std::string>(),
"Memory address to which a write stops simulator.")
("tohostsym", po::value<std::string>(),
"ELF symbol to use for setting tohost from ELF file (in the case "
"where tohost is not specified on the command line). Default: "
"\"tohost\".")
("consoleio", po::value<std::string>(),
"Memory address corresponding to console io. Reading/writing "
"(lw/lh/lb sw/sh/sb) from given address reads/writes a byte from the "
"console.")
("consoleiosym", po::value<std::string>(),
"ELF symbol to use as console-io address (in the case where "
"consoleio is not specified on the command line). Deafult: "
"\"__whisper_console_io\".")
("maxinst,m", po::value<std::string>(),
"Limit executed instruction count to arg.")
("memorysize", po::value<std::string>(),
"Memory size (must be a multiple of 4096).")
("interactive,i", po::bool_switch(&args.interactive),
"Enable interactive mode.")
("traceload", po::bool_switch(&args.traceLdSt),
"Enable tracing of load/store instruction data address.")
("triggers", po::bool_switch(&args.triggers),
"Enable debug triggers (triggers are on in interactive and server modes)")
("counters", po::bool_switch(&args.counters),
"Enable performance counters")
("gdb", po::bool_switch(&args.gdb),
"Run in gdb mode enabling remote debugging from gdb (this requires gdb version"
"8.2 or higher).")
("gdb-tcp-port", po::value(&args.gdbTcpPort)->multitoken(),
"TCP port number for gdb; If port num is negative,"
" gdb will work with stdio (default -1).")
("profileinst", po::value(&args.instFreqFile),
"Report instruction frequency to file.")
("setreg", po::value(&args.regInits)->multitoken(),
"Initialize registers. Apply to all harts unless specific prefix "
"present (hart is 1 in 1:x3=0xabc). Example: --setreg x1=4 x2=0xff "
"1:x3=0xabc")
("configfile", po::value(&args.configFile),
"Configuration file (JSON file defining system features).")
("snapshotdir", po::value(&args.snapshotDir),
"Directory prefix for saving snapshots.")
("snapshotperiod", po::value<std::string>(),
"Snapshot period: Save snapshot using snapshotdir every so many instructions.")
("loadfrom", po::value(&args.loadFrom),
"Snapshot directory from which to restore a previously saved (snapshot) state.")
("stdout", po::value(&args.stdoutFile),
"Redirect standard output of newlib/Linux target program to this.")
("stderr", po::value(&args.stderrFile),
"Redirect standard error of newlib/Linux target program to this.")
("abinames", po::bool_switch(&args.abiNames),
"Use ABI register names (e.g. sp instead of x2) in instruction disassembly.")
("newlib", po::bool_switch(&args.newlib),
"Emulate (some) newlib system calls. Done automatically if newlib "
"symbols are detected in the target ELF file.")
("linux", po::bool_switch(&args.linux),
"Emulate (some) Linux system calls. Done automatically if Linux "
"symbols are detected in the target ELF file.")
("raw", po::bool_switch(&args.raw),
"Bare metal mode: Disble emulation of Linux/newlib system call emulation "
"even if Linux/newlib symbols detected in the target ELF file.")
("elfisa", po::bool_switch(&args.elfisa),
"Confiure reset value of MISA according to the RISCV architecture tag(s) "
"encoded into the laoded ELF file(s) if any.")
("fastext", po::bool_switch(&args.fastExt),
"Enable fast external interrupt dispatch.")
("unmappedelfok", po::bool_switch(&args.unmappedElfOk),
"Do not flag as error ELF file sections targeting unmapped "
" memory.")
("alarm", po::value<std::string>(),
"External interrupt period in micro-seconds: Convert arg to an "
"instruction count, n, assuming a 1ghz clock, and force an external "
" interrupt every n instructions. No-op if arg is zero.")
("softinterrupt", po::value<std::string>(),
"Address of memory mapped word(s) controlling software interrupts. In "
"an n-hart system, words at addresses a, a+4, ... a+(n-1)*4 "
"are associated with the n harts (\"a\" being the address "
"specified by this option and must be a multiple of "
"4). Writing 0/1 to one of these addresses (using sw) "
"clear/sets the software interrupt bit in the the MIP (machine "
"interrupt pending) CSR of the corresponding hart. If a "
"software interrupt is taken, it is up to interrupt handler to "
"write zero to the same location to clear the corresponding "
"bit in MIP. Writing values besides 0/1 will not affect the "
"MIP bit and neither will writing using sb/sh/sd or writing to "
"non-multiple-of-4 addresses.")
("clint", po::value<std::string>(),
"Define address, a, of memory mapped area for clint (core local "
"interruptor). In an n-hart system, words at addresses a, a+4, ... "
"a+(n-1)*4, are associated with the n harts. Store a 0/1 to one of "
"these locations clears/sets the software interrupt bit in the MIP CSR "
"of the corresponding hart. Similary, addresses b, b+8, ... b+(n-1)*8, "
"where b is a+0x4000, are associated with the n harts. Writing to one "
"of these double words sets the timer-limit of the corresponding hart. "
"A timer interrupt in such a hart becomes pending when the timer value "
"equals or exceeds the timer limit.")
("syscallslam", po::value<std::string>(),
"Define address, a, of a non-cached memory area in which the "
"memory changes of an emulated system call will be slammed. This "
"is used in server mode to relay the effects of a system call "
"to the RTL simulator. The memory area at location a will be filled "
"with a sequence of pairs of double words designating addresses and "
"corresponding values. A zero/zero pair will indicate the end of "
"sequence.")
("iccmrw", po::bool_switch(&args.iccmRw),
"Temporary switch to make ICCM region available to ld/st isntructions.")
("quitany", po::bool_switch(&args.quitOnAnyHart),
"Terminate multi-threaded run when any hart finishes (default is to wait "
"for all harts.)")
("noconinput", po::bool_switch(&args.noConInput),
"Do not use console IO address for input. Loads from the cosole io address "
"simply return last value stored there.")
("verbose,v", po::bool_switch(&args.verbose),
"Be verbose.")
("version", po::bool_switch(&args.version),
"Print version.");
// Define positional options.
po::positional_options_description pdesc;
pdesc.add("target", -1);
// Parse command line options.
po::variables_map varMap;
po::command_line_parser parser(argc, argv);
auto parsed = parser.options(desc).positional(pdesc).run();
po::store(parsed, varMap);
po::notify(varMap);
// auto unparsed = po::collect_unrecognized(parsed.options, po::include_positional);
if (args.version)
printVersion();
if (args.help)
{
std::cout <<
"Simulate a RISCV system running the program specified by the given ELF\n"
"and/or HEX file. With --newlib/--linux, the ELF file is a newlib/linux linked\n"
"program and may be followed by corresponding command line arguments.\n"
"All numeric arguments are interpreted as hexadecimal numbers when prefixed"
" with 0x."
"Examples:\n"
" whisper --target prog --log\n"
" whisper --target prog --setreg sp=0xffffff00\n"
" whisper --newlib --log --target \"prog -x -y\"\n"
" whisper --linux --log --targetsep ':' --target \"prog:-x:-y\"\n\n";
std::cout << desc;
return true;
}
if (not collectCommandLineValues(varMap, args))
return false;
}
catch (std::exception& exp)
{
std::cerr << "Failed to parse command line args: " << exp.what() << '\n';
return false;
}
return true;
}
/// Apply register initializations specified on the command line.
template<typename URV>
static
bool
applyCmdLineRegInit(const Args& args, Hart<URV>& hart)
{
bool ok = true;
URV hartId = hart.sysHartIndex();
for (const auto& regInit : args.regInits)
{
// Each register initialization is a string of the form reg=val
// or hart:reg=val
std::vector<std::string> tokens;
boost::split(tokens, regInit, boost::is_any_of("="),
boost::token_compress_on);
if (tokens.size() != 2)
{
std::cerr << "Invalid command line register initialization: "
<< regInit << '\n';
ok = false;
continue;
}
std::string regName = tokens.at(0);
const std::string& regVal = tokens.at(1);
bool specificHart = false;
unsigned id = 0;
size_t colonIx = regName.find(':');
if (colonIx != std::string::npos)
{
std::string hartStr = regName.substr(0, colonIx);
regName = regName.substr(colonIx + 1);
if (not parseCmdLineNumber("hart", hartStr, id))
{
std::cerr << "Invalid command line register initialization: "
<< regInit << '\n';
ok = false;
continue;
}
specificHart = true;
}
URV val = 0;
if (not parseCmdLineNumber("register", regVal, val))
{
ok = false;
continue;
}
if (specificHart and id != hartId)
continue;
if (unsigned reg = 0; hart.findIntReg(regName, reg))
{
if (args.verbose)
std::cerr << "Setting register " << regName << " to command line "
<< "value 0x" << std::hex << val << std::dec << '\n';
hart.pokeIntReg(reg, val);
continue;
}
if (unsigned reg = 0; hart.findFpReg(regName, reg))
{
if (args.verbose)
std::cerr << "Setting register " << regName << " to command line "
<< "value 0x" << std::hex << val << std::dec << '\n';
hart.pokeFpReg(reg, val);
continue;
}
auto csr = hart.findCsr(regName);
if (csr)
{
if (args.verbose)
std::cerr << "Setting register " << regName << " to command line "
<< "value 0x" << std::hex << val << std::dec << '\n';
hart.pokeCsr(csr->getNumber(), val);
continue;
}
std::cerr << "No such RISCV register: " << regName << '\n';
ok = false;
}
return ok;
}
template<typename URV>
static
bool
applyZisaStrings(const std::vector<std::string>& zisa, Hart<URV>& hart)
{
unsigned errors = 0;
for (const auto& ext : zisa)
{
if (ext == "zba" or ext == "ba")
hart.enableRvzba(true);
else if (ext == "zbb" or ext == "bb")
hart.enableRvzbb(true);
else if (ext == "zbc" or ext == "bc")
hart.enableRvzbc(true);
else if (ext == "zbe" or ext == "be")
hart.enableRvzbe(true);
else if (ext == "zbf" or ext == "bf")
hart.enableRvzbf(true);
else if (ext == "zbm" or ext == "bm")
hart.enableRvzbm(true);
else if (ext == "zbp" or ext == "bp")
hart.enableRvzbp(true);
else if (ext == "zbr" or ext == "br")
hart.enableRvzbr(true);
else if (ext == "zbs" or ext == "bs")
hart.enableRvzbs(true);
else if (ext == "zbt" or ext == "bt")
hart.enableRvzbt(true);
else if (ext == "zbmini" or ext == "bmini")
{
hart.enableRvzbb(true);
hart.enableRvzbs(true);
std::cerr << "ISA option zbmini is deprecated. Using zbb and zbs.\n";
}
else
{
std::cerr << "No such Z extension: " << ext << '\n';
errors++;
}
}
return errors == 0;
}
template<typename URV>
static
bool
applyIsaString(const std::string& isaStr, Hart<URV>& hart)
{
URV isa = 0;
unsigned errors = 0;
for (auto c : isaStr)
{
switch(c)
{
case 'a':
case 'c':
case 'd':
case 'e':
case 'f':
case 'i':
case 'm':
case 's':
case 'u':
case 'v':
isa |= URV(1) << (c - 'a');
break;
case 'g': // Enable a, d, f, and m
isa |= 0x1 | 0x8 | 0x20 | 0x1000;
break;
default:
std::cerr << "Extension \"" << c << "\" is not supported.\n";
errors++;
break;
}
}
if (not (isa & (URV(1) << ('i' - 'a'))))
{
std::cerr << "Extension \"i\" implicitly enabled\n";
isa |= URV(1) << ('i' - 'a');
}
if (isa & (URV(1) << ('d' - 'a')))
if (not (isa & (URV(1) << ('f' - 'a'))))
{
std::cerr << "Extension \"d\" requires \"f\" -- Enabling \"f\"\n";
isa |= URV(1) << ('f' - 'a');
}
// Set the xlen bits: 1 for 32-bits and 2 for 64.
URV xlen = sizeof(URV) == 4? 1 : 2;
isa |= xlen << (8*sizeof(URV) - 2);
bool resetMemoryMappedRegs = false;
URV mask = 0, pokeMask = 0;
bool implemented = true, isDebug = false, shared = true;
if (not hart.configCsr("misa", implemented, isa, mask, pokeMask, isDebug,
shared))
{
std::cerr << "Failed to configure MISA CSR\n";
errors++;
}
else
hart.reset(resetMemoryMappedRegs); // Apply effects of new misa value.
return errors == 0;
}
/// Enable linux or newlib based on the symbols in the ELF files.
/// Return true if either is enabled.
template<typename URV>
static
bool
enableNewlibOrLinuxFromElf(const Args& args, Hart<URV>& hart)
{
bool newlib = args.newlib, linux = args.linux;
if (args.raw)
{
if (newlib or linux)
std::cerr << "Raw mode not comptible with newlib/linux. Sticking"
<< " with raw mode.\n";
return false;
}
if (linux or newlib)
; // Emulation preference already set by user.
else
{
// At this point ELF files have not been loaded: Cannot use
// hart.findElfSymbol.
for (auto target : args.expandedTargets)
{
auto elfPath = target.at(0);
if (not linux)
linux = Memory::isSymbolInElfFile(elfPath, "__libc_csu_init");
if (not newlib)
newlib = Memory::isSymbolInElfFile(elfPath, "__call_exitprocs");
}
if (args.verbose and linux)
std::cerr << "Deteced linux symbol in ELF\n";
if (args.verbose and newlib)
std::cerr << "Deteced newlib symbol in ELF\n";
if (newlib and linux)
{
std::cerr << "Fishy: Both newlib and linux symbols present in "
<< "ELF file(s). Doing linux emulation.\n";
newlib = false;
}
}
hart.enableNewlib(newlib);
hart.enableLinux(linux);
return newlib or linux;
}
/// Set stack pointer to a reasonable value for linux/newlib.
template<typename URV>
static
void
sanitizeStackPointer(Hart<URV>& hart, bool verbose)
{
// Set stack pointer to the 128 bytes below end of memory.
size_t memSize = hart.getMemorySize();
if (memSize > 128)
{
size_t spValue = memSize - 128;
if (verbose)
std::cerr << "Setting stack pointer to 0x" << std::hex << spValue
<< std::dec << " for newlib/linux\n";
hart.pokeIntReg(IntRegNumber::RegSp, spValue);
}
}
/// Load register and memory state from snapshot previously saved
/// in the given directory. Return true on success and false on
/// failure.
template <typename URV>
static
bool
loadSnapshot(Hart<URV>& hart, const std::string& snapDir)
{
using std::cerr;
if (not FileSystem::is_directory(snapDir))
{
cerr << "Error: Path is not a snapshot directory: " << snapDir << '\n';
return false;
}
FileSystem::path path(snapDir);
FileSystem::path regPath = path / "registers";
if (not FileSystem::is_regular_file(regPath))
{
cerr << "Error: Snapshot file does not exists: " << regPath << '\n';
return false;
}
FileSystem::path memPath = path / "memory";
if (not FileSystem::is_regular_file(regPath))
{
cerr << "Error: Snapshot file does not exists: " << memPath << '\n';
return false;
}
if (not hart.loadSnapshot(path))
{
cerr << "Error: Failed to load sanpshot from dir " << snapDir << '\n';
return false;
}
return true;
}
template<typename URV>
static
void
configureClint(Hart<URV>& hart, System<URV>& system, uint64_t clintStart,
uint64_t clintLimit, uint64_t timerAddr)
{
// Define callback to associate a memory mapped software interrupt
// location to its corresponding hart so that when such a location
// is written the software interrupt bit is set/cleared in the MIP
// register of that hart.
uint64_t swAddr = clintStart;
auto swAddrToHart = [swAddr, &system](URV addr) -> Hart<URV>* {
uint64_t addr2 = swAddr + system.hartCount()*4; // 1 word per hart
if (addr >= swAddr and addr < addr2)
{
size_t ix = (addr - swAddr) / 4;
return system.ithHart(ix).get();
}
return nullptr;
};
// Same for timer limit addresses.
auto timerAddrToHart = [timerAddr, &system](URV addr) -> Hart<URV>* {
uint64_t addr2 = timerAddr + system.hartCount()*8; // 1 double word per hart
if (addr >= timerAddr and addr < addr2)
{
size_t ix = (addr - timerAddr) / 8;
return system.ithHart(ix).get();
}
return nullptr;
};
hart.configClint(clintStart, clintLimit, swAddrToHart, timerAddrToHart);
}
static
bool
getElfFilesIsaString(const Args& args, std::string& isaString)
{
std::vector<std::string> archTags;
unsigned errors = 0;
for (const auto& target : args.expandedTargets)
{
const auto& elfFile = target.front();
if (not Memory::collectElfRiscvTags(elfFile, archTags))
errors++;
}
std::unordered_set<char> isaChars;
for (const auto& tag : archTags)
{
if (args.verbose)
std::cerr << "Collecting ISA string from ELF file tag: " << tag << '\n';
// Example tag: rv32i2p0_m2p0_a2p0_f2p0_d2p0_c2p0
std::vector<std::string> extensions;
boost::split(extensions, tag, boost::is_any_of("_"));
for (size_t i = 1; i < extensions.size(); ++i)
{
const auto& ext = extensions.at(i);
if (not ext.empty())
{
char cc = ext.front();
isaChars.insert(cc);
}
}
}
for (auto cc : isaChars)
isaString.push_back(cc);
if (args.verbose)
std::cerr << "ISA string from ELF file(s): " << isaString << '\n';
return errors == 0;
}