forked from tenstorrent/whisper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Session.cpp
1345 lines (1110 loc) · 33.6 KB
/
Session.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.
// Copyright 2024 Tenstorrent 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 <fstream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <sys/mman.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <unistd.h>
#include <dlfcn.h>
#include <csignal>
#include "Session.hpp"
#include "HartConfig.hpp"
#include "Hart.hpp"
#include "Server.hpp"
#include "Interactive.hpp"
#if !defined(SOL_TCP) && defined(IPPROTO_TCP)
#define SOL_TCP IPPROTO_TCP
#endif
using namespace WdRiscv;
using StringVec = std::vector<std::string>;
template <typename URV>
Session<URV>::Session()
{
}
template <typename URV>
std::shared_ptr<System<URV>>
Session<URV>::defineSystem(const Args& args, const HartConfig& config)
{
// Collect primary configuration parameters.
unsigned hartsPerCore = 1;
unsigned coreCount = 1;
size_t pageSize = UINT64_C(4)*1024;
size_t memorySize = size_t(1) << 32; // 4 gigs
if (not getPrimaryConfigParameters(args, config, hartsPerCore, coreCount,
pageSize, memorySize))
return nullptr;
checkAndRepairMemoryParams(memorySize, pageSize);
if (args.hexFiles.empty() and args.expandedTargets.empty()
and args.binaryFiles.empty() and args.kernelFile.empty()
#ifdef LZ4_COMPRESS
and args.lz4Files.empty()
#endif
and not args.interactive)
{
std::cerr << "No program file specified.\n";
return nullptr;
}
// Create cores & harts.
unsigned hartIdOffset = hartsPerCore;
config.getHartIdOffset(hartIdOffset);
if (hartIdOffset < hartsPerCore)
{
std::cerr << "Invalid core_hart_id_offset: " << hartIdOffset
<< ", must be greater than harts_per_core: " << hartsPerCore << '\n';
return nullptr;
}
system_ = std::make_shared<System<URV>> (coreCount, hartsPerCore, hartIdOffset,
memorySize, pageSize);
assert(system_ -> hartCount() == coreCount*hartsPerCore);
assert(system_ -> hartCount() > 0);
return system_;
}
template <typename URV>
bool
Session<URV>::configureSystem(const Args& args, const HartConfig& config)
{
if (not system_)
return false;
auto& system = *system_;
// Configure harts. Define callbacks for non-standard CSRs.
bool userMode = args.isa.find_first_of("uU") != std::string::npos;
if (not config.configHarts(system, userMode, args.verbose))
if (not args.interactive)
return false;
// Configure memory.
if (not config.configMemory(system, args.unmappedElfOk))
return false;
if (not args.pciDevs.empty())
if (not system.addPciDevices(args.pciDevs))
return false;
if (not args.dataLines.empty())
system.enableDataLineTrace(args.dataLines);
if (not args.instrLines.empty())
system.enableInstructionLineTrace(args.instrLines);
bool newlib = false, linux = false;
checkForNewlibOrLinux(args, newlib, linux);
bool clib = newlib or linux;
bool updateMisa = clib and not config.hasCsrConfig("misa");
std::string isa;
if (not determineIsa(config, args, clib, isa))
return false;
if (not openUserFiles(args))
return false;
for (unsigned i = 0; i < system.hartCount(); ++i)
{
auto& hart = *(system_ -> ithHart(i));
hart.setConsoleOutput(consoleOut_);
hart.enableBasicBlocks(bblockFile_, args.bblockInsts);
hart.enableNewlib(newlib);
hart.enableLinux(linux);
if (not isa.empty())
if (not hart.configIsa(isa, updateMisa))
return false;
hart.reset();
}
// This needs Smaia extension to be enabled.
if (not config.applyImsicConfig(system))
return false;
for (unsigned i = 0; i < system.hartCount(); ++i)
if (not applyCmdLineArgs(args, *system.ithHart(i), config, clib))
if (not args.interactive)
return false;
if (not args.loadFrom.empty())
if (not system.loadSnapshot(args.loadFrom))
return false;
if (linux and checkForOpenMp(args))
{
if (args.verbose)
std::cerr << "Found OpenMP in executable. To emulate clone, we suspend "
"all harts other than hart 0.\n";
for (unsigned i = 1; i < system.hartCount(); ++i)
{
auto& hart = *system.ithHart(i);
hart.setSuspendState(true);
}
}
// Set instruction count limit.
if (args.instCountLim)
for (unsigned i = 0; i < system.hartCount(); ++i)
{
auto& hart = *system.ithHart(i);
uint64_t count = args.relativeInstCount? hart.getInstructionCount() : 0;
count += *args.instCountLim;
hart.setInstructionCountLimit(count);
}
if (not args.initStateFile.empty())
{
if (system.hartCount() > 1)
{
std::cerr << "Initial line-state report (--initstate) valid only when hart count is 1\n";
return false;
}
auto& hart0 = *system.ithHart(0);
hart0.setInitialStateFile(initStateFile_);
}
return true;
}
template <typename URV>
bool
Session<URV>::getPrimaryConfigParameters(const Args& args, const HartConfig& config,
unsigned& hartsPerCore, unsigned& coreCount,
size_t& pageSize, size_t& memorySize)
{
config.getHartsPerCore(hartsPerCore);
if (args.hasHarts)
hartsPerCore = args.harts;
if (hartsPerCore == 0 or hartsPerCore > 32)
{
std::cerr << "Unsupported hart count: " << hartsPerCore;
std::cerr << " (1 to 32 currently supported)\n";
return false;
}
config.getCoreCount(coreCount);
if (args.hasCores)
coreCount = args.cores;
if (coreCount == 0 or coreCount > 32)
{
std::cerr << "Unsupported core count: " << coreCount;
std::cerr << " (1 to 32 currently supported)\n";
return false;
}
// Determine simulated memory size. Default to 4 gigs.
// If running a 32-bit machine (pointer size = 32 bits), try 2 gigs.
if (memorySize == 0)
memorySize = size_t(1) << 31; // 2 gigs
config.getMemorySize(memorySize);
if (args.memorySize)
memorySize = *args.memorySize;
if (not config.getPageSize(pageSize))
pageSize = args.pageSize;
return true;
}
template <typename URV>
bool
Session<URV>::checkAndRepairMemoryParams(size_t& memSize, size_t& pageSize)
{
bool ok = true;
unsigned logPageSize = static_cast<unsigned>(std::log2(pageSize));
size_t p2PageSize = size_t(1) << logPageSize;
if (p2PageSize != pageSize)
{
std::cerr << "Memory page size (0x" << std::hex << pageSize << ") "
<< "is not a power of 2 -- using 0x" << p2PageSize << '\n'
<< std::dec;
pageSize = p2PageSize;
ok = false;
}
if (pageSize < 64)
{
std::cerr << "Page size (" << pageSize << ") is less than 64. Using 64.\n";
pageSize = 64;
ok = false;
}
if (memSize < pageSize)
{
std::cerr << "Memory size (0x" << std::hex << memSize << ") "
<< "smaller than page size (0x" << pageSize << ") -- "
<< "using 0x" << pageSize << " as memory size\n" << std::dec;
memSize = pageSize;
ok = false;
}
size_t pageCount = memSize / pageSize;
if (pageCount * pageSize != memSize)
{
size_t newSize = (pageCount + 1) * pageSize;
if (newSize == 0)
newSize = (pageCount - 1) * pageSize; // Avoid overflow
std::cerr << "Memory size (0x" << std::hex << memSize << ") is not a "
<< "multiple of page size (0x" << pageSize << ") -- "
<< "using 0x" << newSize << '\n' << std::dec;
memSize = newSize;
ok = false;
}
return ok;
}
template<typename URV>
bool
Session<URV>::openUserFiles(const Args& args)
{
traceFiles_.resize(system_ -> hartCount());
unsigned ix = 0;
for (auto& traceFile : traceFiles_)
{
size_t len = args.traceFile.size();
doGzip_ = len > 3 and args.traceFile.substr(len-3) == ".gz";
if (not args.traceFile.empty())
{
std::string name = args.traceFile;
if (args.logPerHart)
{
if (not doGzip_)
name.append(std::to_string(ix));
else
name.insert(len - 3, std::to_string(ix));
}
if ((ix == 0) || args.logPerHart)
{
if (doGzip_)
{
std::string cmd = "/usr/bin/gzip -c > ";
cmd += name;
traceFile = popen(cmd.c_str(), "w");
}
else
traceFile = fopen(name.c_str(), "w");
}
else
traceFile = traceFiles_.at(0); // point the same File pointer to each hart
if (not traceFile)
{
std::cerr << "Failed to open trace file '" << name
<< "' for output\n";
return false;
}
}
if (args.trace and traceFile == nullptr)
traceFile = stdout;
++ix;
}
if (not args.commandLogFile.empty())
{
commandLog_ = fopen(args.commandLogFile.c_str(), "w");
if (not commandLog_)
{
std::cerr << "Failed to open command log file '"
<< args.commandLogFile << "' for output\n";
return false;
}
setlinebuf(commandLog_); // Make line-buffered.
}
if (not args.consoleOutFile.empty())
{
consoleOut_ = fopen(args.consoleOutFile.c_str(), "w");
if (not consoleOut_)
{
std::cerr << "Failed to open console output file '"
<< args.consoleOutFile << "' for output\n";
return false;
}
}
if (not args.bblockFile.empty())
{
bblockFile_ = fopen(args.bblockFile.c_str(), "w");
if (not bblockFile_)
{
std::cerr << "Failed to open basic block file '"
<< args.bblockFile << "' for output\n";
return false;
}
}
if (not args.initStateFile.empty())
{
initStateFile_ = fopen(args.initStateFile.c_str(), "w");
if (not initStateFile_)
{
std::cerr << "Failed to open init state file '"
<< args.initStateFile << "' for output\n";
return false;
}
}
return true;
}
template<typename URV>
void
Session<URV>::closeUserFiles()
{
if (consoleOut_ and consoleOut_ != stdout)
fclose(consoleOut_);
consoleOut_ = nullptr;
FILE* prev = nullptr;
for (auto& traceFile : traceFiles_)
{
if (traceFile and traceFile != stdout and traceFile != prev)
{
if (doGzip_)
pclose(traceFile);
else
fclose(traceFile);
}
prev = traceFile;
traceFile = nullptr;
}
if (commandLog_ and commandLog_ != stdout)
fclose(commandLog_);
commandLog_ = nullptr;
if (bblockFile_ and bblockFile_ != stdout)
fclose(bblockFile_);
bblockFile_ = nullptr;
if (initStateFile_ and initStateFile_ != stdout)
fclose(initStateFile_);
initStateFile_ = nullptr;
}
template<typename URV>
void
Session<URV>::checkForNewlibOrLinux(const Args& args, bool& newlib, bool& linux)
{
if (args.raw)
{
if (args.newlib or args.linux)
std::cerr << "Raw mode not compatible with newlib/linux. Sticking"
<< " with raw mode.\n";
return;
}
newlib = args.newlib;
linux = args.linux;
if (linux or newlib)
return; // Emulation preference already set by user.
for (auto target : args.expandedTargets)
{
auto elfPath = target.at(0);
if (not linux)
linux = (Memory::isSymbolInElfFile(elfPath, "__libc_early_init") or
Memory::isSymbolInElfFile(elfPath, "__dladdr"));
if (not newlib)
newlib = Memory::isSymbolInElfFile(elfPath, "__call_exitprocs");
if (linux and newlib)
break;
}
if (linux and args.verbose)
std::cerr << "Detected Linux symbol in ELF\n";
if (newlib and args. verbose)
std::cerr << "Detected 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;
}
}
template<typename URV>
bool
Session<URV>::checkForOpenMp(const Args& args)
{
bool foundOpenMp = false;
for (auto target : args.expandedTargets)
{
auto elfPath = target.at(0);
foundOpenMp = Memory::isSymbolInElfFile(elfPath, "gomp_init_num_threads");
if (foundOpenMp)
break;
}
return foundOpenMp;
}
template<typename URV>
bool
Session<URV>::determineIsa(const HartConfig& config, const Args& args, bool clib,
std::string& isa)
{
isa.clear();
if (not args.isa.empty() and args.elfisa)
std::cerr << "Warning: Both --isa and --elfisa present: Using --isa\n";
isa = args.isa;
if (isa.empty() and args.elfisa)
if (not getElfFilesIsaString(args, isa))
return false;
if (isa.empty())
{
// No command line ISA. Use config file.
config.getIsa(isa);
}
if (isa.empty() and clib)
{
if (args.verbose)
std::cerr << "No ISA specified, using i/m/a/c/f/d/v extensions for newlib/linux\n";
isa = "imcafdv";
}
if (isa.empty() and not args.raw)
{
if (args.verbose)
std::cerr << "No ISA specified: Defaulting to imac\n";
isa = "imacfd";
}
return true;
}
template<typename URV>
bool
Session<URV>::getElfFilesIsaString(const Args& args, std::string& isaString)
{
StringVec archTags;
unsigned errors = 0;
for (const auto& target : args.expandedTargets)
{
const auto& elfFile = target.front();
if (not Memory::collectElfRiscvTags(elfFile, archTags))
errors++;
}
if (archTags.empty())
return errors == 0;
const std::string& ref = archTags.front();
for (const auto& tag : archTags)
if (tag != ref)
std::cerr << "Warning different ELF files have different ISA strings: "
<< tag << " and " << ref << '\n';
isaString = ref;
if (args.verbose)
std::cerr << "ISA string from ELF file(s): " << isaString << '\n';
return errors == 0;
}
/// 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);
}
}
/// Apply register initialization specified on the command line.
template<typename URV>
static
bool
applyCmdLineRegInit(const Args& args, Hart<URV>& hart)
{
bool ok = true;
URV hartIx = 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 ix = 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 Args::parseCmdLineNumber("hart", hartStr, ix))
{
std::cerr << "Invalid command line register initialization: " << regInit << '\n';
ok = false;
continue;
}
specificHart = true;
}
URV val = 0;
if (not Args::parseCmdLineNumber("register", regVal, val))
{
ok = false;
continue;
}
if (specificHart and ix != hartIx)
continue;
unsigned reg = 0;
Csr<URV>* csr = nullptr;
if (hart.findIntReg(regName, reg))
hart.pokeIntReg(reg, val);
else if (hart.findFpReg(regName, reg))
hart.pokeFpReg(reg, val);
else if ((csr = hart.findCsr(regName)) != nullptr)
hart.pokeCsr(csr->getNumber(), val);
else
{
std::cerr << "Invalid --setreg register: " << regName << '\n';
ok = false;
continue;
}
if (args.verbose)
std::cerr << "Setting register " << regName << " to command line "
<< "value 0x" << std::hex << val << std::dec << '\n';
}
return ok;
}
template<typename URV>
bool
Session<URV>::applyCmdLineArgs(const Args& args, Hart<URV>& hart,
const HartConfig& config, bool clib)
{
unsigned errors = 0;
auto& system = *system_;
if (clib) // Linux or Newlib enabled.
sanitizeStackPointer(hart, args.verbose);
if (args.toHostSym)
system.setTohostSymbol(*args.toHostSym);
if (args.consoleIoSym)
system.setConsoleIoSymbol(*args.consoleIoSym);
// Load ELF/HEX/binary files. Entry point of first ELF file sets the start PC unless in
// raw mode.
if (hart.sysHartIndex() == 0)
{
StringVec paths;
for (const auto& target : args.expandedTargets)
paths.push_back(target.at(0));
if (not system.loadElfFiles(paths, args.raw, args.verbose))
errors++;
if (not system.loadHexFiles(args.hexFiles, args.verbose))
errors++;
uint64_t offset = 0;
if (not system.loadBinaryFiles(args.binaryFiles, offset, args.verbose))
errors++;
#ifdef LZ4_COMPRESS
if (not system.loadLz4Files(args.lz4Files, offset, args.verbose))
errors++;
#endif
if (not args.kernelFile.empty())
{
// Default kernel file offset. FIX: make a parameter.
StringVec files{args.kernelFile};
offset = hart.isRv64() ? 0x80200000 : 0x80400000;
if (not system.loadBinaryFiles(files, offset, args.verbose))
errors++;
}
}
if (not args.instFreqFile.empty())
hart.enableInstructionFrequency(true);
if (args.clint)
{
uint64_t swAddr = *args.clint, size = 0xc000;
config.configAclint(system, hart, swAddr, size, swAddr, 0 /* swOffset */, true /* hasMswi */,
0x4000 /* timerOffset */, 0xbff8 /* timeOffset */, true /* hasMtimer */);
}
uint64_t window = 1000000;
if (args.branchWindow)
window = *args.branchWindow;
if (not args.branchTraceFile.empty())
hart.traceBranches(args.branchTraceFile, window);
if (args.logStart)
hart.setLogStart(*args.logStart);
if (args.logPerHart or (system.hartCount() == 1))
hart.setOwnTrace(args.logPerHart or (system.hartCount() == 1));
if (not args.loadFrom.empty())
{
if (not args.stdoutFile.empty() or not args.stderrFile.empty() or
not args.stdinFile.empty())
std::cerr << "Info: Options --stdin/--stdout/--stderr are ignored with --loadfrom\n";
}
else
{
if (not args.stdoutFile.empty())
if (not hart.redirectOutputDescriptor(STDOUT_FILENO, args.stdoutFile))
errors++;
if (not args.stderrFile.empty())
if (not hart.redirectOutputDescriptor(STDERR_FILENO, args.stderrFile))
errors++;
if (not args.stdinFile.empty())
if (not hart.redirectInputDescriptor(STDIN_FILENO, args.stdinFile))
errors++;
}
if (args.instCounter)
hart.setInstructionCount(*args.instCounter);
// Command line to-host overrides that of ELF and config file.
if (args.toHost)
hart.setToHostAddress(*args.toHost);
if (args.fromHost)
hart.setFromHostAddress(*args.fromHost, true);
// We turn off fromhost when interactive mode is used.
if (args.interactive)
hart.setFromHostAddress(0, false);
// Command-line entry point overrides that of ELF.
if (args.startPc)
{
hart.defineResetPc(*args.startPc);
hart.pokePc(URV(*args.startPc));
}
// Command-line exit point overrides that of ELF.
if (args.endPc)
hart.setStopAddress(URV(*args.endPc));
// Command-line console io address overrides config file.
if (args.consoleIo)
hart.setConsoleIo(URV(*args.consoleIo));
hart.enableConsoleInput(! args.noConInput);
if (args.interruptor)
{
uint64_t addr = *args.interruptor;
config.configInterruptor(system, hart, addr);
}
if (args.syscallSlam)
hart.defineSyscallSlam(*args.syscallSlam);
if (args.tracePtw)
hart.tracePtw(true);
// Setup periodic external interrupts.
if (args.alarmInterval)
{
// Convert from micro-seconds to processor ticks. Assume a 1
// ghz-processor.
uint64_t ticks = (*args.alarmInterval)*1000;
hart.setupPeriodicTimerInterrupts(ticks);
}
if (args.triggers)
hart.enableTriggers(args.triggers);
hart.enableGdb(args.gdb);
if (args.gdbTcpPort.size()>hart.sysHartIndex())
hart.setGdbTcpPort(args.gdbTcpPort[hart.sysHartIndex()]);
if (args.counters)
hart.enablePerformanceCounters(args.counters);
if (args.abiNames)
hart.enableAbiNames(args.abiNames);
// Apply register initialization.
if (not applyCmdLineRegInit(args, hart))
errors++;
// Setup target program arguments.
if (not args.expandedTargets.empty())
{
if (clib)
{
if (args.loadFrom.empty())
if (not hart.setTargetProgramArgs(args.expandedTargets.front(), args.envVars))
{
size_t memSize = hart.memorySize();
size_t suggestedStack = memSize - 4;
std::cerr << "Failed to setup target program arguments -- stack "
<< "is not writable\n"
<< "Try using --setreg sp=<val> to set the stack pointer "
<< "to a\nwritable region of memory (e.g. --setreg "
<< "sp=0x" << std::hex << suggestedStack << '\n'
<< std::dec;
errors++;
}
}
else if (args.expandedTargets.front().size() > 1 or not args.envVars.empty())
{
std::cerr << "Warning: Target program options or env vars present which requires\n"
<< " the use of --newlib/--linux. Options ignored.\n";
}
}
if (args.csv)
hart.enableCsvLog(args.csv);
if (args.logStart)
hart.setLogStart(*args.logStart);
if (args.mcm)
{
unsigned mcmLineSize = 64;
config.getMcmLineSize(mcmLineSize);
if (args.mcmls)
mcmLineSize = *args.mcmls;
bool checkAll = false;
config.getMcmCheckAll(checkAll);
if (args.mcmca)
checkAll = true;
if (not system.enableMcm(mcmLineSize, checkAll, not args.noPpo))
errors++;
}
if (args.steesr.size() == 2)
{
uint64_t low = args.steesr.at(0), high = args.steesr.at(1);
if ((low % hart.pageSize()) != 0 or (high % hart.pageSize()) != 0)
{
std::cerr << "Warning: STEE secure region bounds are not page aligned\n";
low -= low % hart.pageSize();
high -= high % hart.pageSize();
std::cerr << "Warning: STEE secure region bounds changed to: [0x" << std::hex
<< low << ", " << high << "]\n" << std::dec;
}
hart.configSteeSecureRegion(args.steesr.at(0), args.steesr.at(1));
}
if (args.perfApi)
{
if (not system.enablePerfApi(traceFiles_))
errors++;
if (not args.interactive and commandLog_)
system.perfApiCommandLog(commandLog_);
}
if (not args.snapshotPeriods.empty())
{
auto periods = args.snapshotPeriods;
std::sort(periods.begin(), periods.end());
if (std::find(periods.begin(), periods.end(), 0)
!= periods.end())
{
std::cerr << "Snapshot periods of 0 are ignored\n";
periods.erase(std::remove(periods.begin(), periods.end(), 0), periods.end());
}
auto it = std::unique(periods.begin(), periods.end());
if (it != periods.end())
{
periods.erase(it, periods.end());
std::cerr << "Duplicate snapshot periods not supported, removed duplicates\n";
}
}
if (not args.snapshotDir.empty())
system.setSnapshotDir(args.snapshotDir);
if (args.tlbSize)
{
size_t size = *args.tlbSize;
if ((size & (size-1)) != 0)
{
std::cerr << "TLB size must be a power of 2\n";
errors++;
}
else
hart.setTlbSize(size);
}
return errors == 0;
}
template<typename URV>
bool
Session<URV>::runServer(const std::string& serverFile)
{
auto& system = *system_;
auto traceFile = traceFiles_.at(0);
auto commandLog = commandLog_;
std::array<char, 1024> hostName = {};
if (gethostname(hostName.data(), hostName.size()) != 0)
{
std::cerr << "Failed to obtain name of this computer\n";
return false;
}
int soc = socket(AF_INET, SOCK_STREAM, 0);
if (soc < 0)
{
std::array<char, 512> buffer;
char* p = buffer.data();
#ifdef __APPLE__
strerror_r(errno, buffer.data(), buffer.size());
#else
p = strerror_r(errno, buffer.data(), buffer.size());
#endif
std::cerr << "Failed to create socket: " << p << '\n';
return -1;
}
int one = 1;
setsockopt(soc, SOL_TCP, TCP_NODELAY, &one, sizeof(one));
sockaddr_in serverAddr;
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(0);
if (bind(soc, (sockaddr*) &serverAddr, sizeof(serverAddr)) < 0)
{
perror("Socket bind failed");
return false;
}
if (listen(soc, 1) < 0)
{
perror("Socket listen failed");
return false;
}
sockaddr_in socAddr;
socklen_t socAddrSize = sizeof(socAddr);
socAddr.sin_family = AF_INET;
socAddr.sin_port = 0;
if (getsockname(soc, (sockaddr*) &socAddr, &socAddrSize) == -1)
{
perror("Failed to obtain socket information");
return false;
}