-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathdebugger.cpp
More file actions
1710 lines (1584 loc) Β· 62.7 KB
/
debugger.cpp
File metadata and controls
1710 lines (1584 loc) Β· 62.7 KB
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
#include "debugger.h"
#include <algorithm>
#include <cinttypes>
#include <cstring>
#include <optional>
#ifndef ARDUINO
#include <nlohmann/json.hpp>
#else
#include "../../lib/json/single_include/nlohmann/json.hpp"
#endif
#include "../Memory/mem.h"
#include "../Utils//util.h"
#include "../Utils/macros.h"
#include "../WARDuino/CallbackHandler.h"
// Debugger
Debugger::Debugger(Channel *duplex) {
this->channel = duplex;
this->supervisor_mutex = new warduino::mutex();
this->supervisor_mutex->lock();
this->snapshotPolicy = SnapshotPolicy::none;
this->checkpointInterval = 10;
this->instructions_executed = 0;
this->fidx_called = {};
this->min_return_values = 10;
this->checkpoint_state = nullptr;
this->checkpoint_state_size = 0;
this->remaining_instructions = -1;
}
// Public methods
void Debugger::setChannel(Channel *duplex) {
delete this->channel;
this->channel = duplex;
}
void Debugger::addDebugMessage(size_t len, const uint8_t *buff) {
this->parseDebugBuffer(len, buff);
uint8_t *data{};
while (!this->parsedInterrupts.empty()) {
data = this->parsedInterrupts.front();
this->parsedInterrupts.pop();
if (*data == interruptRecvCallbackmapping) {
size_t startIdx = 0;
while (buff[startIdx] != '7' || buff[startIdx + 1] != '5' ||
buff[startIdx + 2] != '{') {
startIdx++;
}
size_t endIdx = startIdx;
while (buff[endIdx] != '\n') {
endIdx++;
}
auto *msg = static_cast<uint8_t *>(acalloc(
sizeof(uint8_t), (endIdx - startIdx), "interrupt buffer"));
memcpy(msg, buff + startIdx, (endIdx - startIdx) * sizeof(uint8_t));
*msg = *data;
free(data);
this->pushMessage(msg);
} else {
this->pushMessage(data);
}
}
}
void Debugger::pushMessage(uint8_t *msg) {
warduino::lock_guard const lg(messageQueueMutex);
this->debugMessages.push_back(msg);
this->freshMessages = !this->debugMessages.empty();
this->messageQueueConditionVariable.notify_one();
}
void Debugger::parseDebugBuffer(size_t len, const uint8_t *buff) {
for (size_t i = 0; i < len; i++) {
bool success = true;
int r = 0;
// TODO replace by real binary
switch (buff[i]) {
case '0' ... '9':
r = buff[i] - '0';
break;
case 'A' ... 'F':
r = buff[i] - 'A' + 10;
break;
case 'a' ... 'f':
r = buff[i] - 'a' + 10;
break;
default:
success = false;
}
if (!success) {
if (this->interruptEven) {
if (!this->interruptBuffer.empty()) {
// done, send to process
// TODO: pointer gets leaked!
auto data = static_cast<uint8_t *>(
acalloc(sizeof(uint8_t), this->interruptBuffer.size(),
"interrupt buffer"));
memcpy(data, this->interruptBuffer.data(),
this->interruptBuffer.size() * sizeof(uint8_t));
this->parsedInterrupts.push(data);
this->interruptBuffer.clear();
}
} else {
this->interruptBuffer.clear();
this->interruptEven = true;
dbg_warn("Dropped interrupt: could not process");
}
} else { // good parse
if (!this->interruptEven) {
this->interruptLastChar =
(this->interruptLastChar << 4u) + static_cast<uint8_t>(r);
this->interruptBuffer.push_back(this->interruptLastChar);
} else {
this->interruptLastChar = static_cast<uint8_t>(r);
}
this->interruptEven = !this->interruptEven;
}
}
}
uint8_t *Debugger::getDebugMessage() {
warduino::lock_guard const lg(messageQueueMutex);
uint8_t *ret = nullptr;
if (!this->debugMessages.empty()) {
ret = this->debugMessages.front();
this->debugMessages.pop_front();
}
this->freshMessages = !this->debugMessages.empty();
return ret;
}
void Debugger::addBreakpoint(uint8_t *loc) { this->breakpoints.insert(loc); }
void Debugger::deleteBreakpoint(uint8_t *loc) { this->breakpoints.erase(loc); }
// ReSharper disable once CppParameterMayBeConstPtrOrRef // incorrect warning
bool Debugger::isBreakpoint(uint8_t *loc) {
return this->breakpoints.find(loc) != this->breakpoints.end() ||
this->mark == loc;
}
void Debugger::notifyBreakpoint(Module *m, uint8_t *pc_ptr) {
if (snapshotPolicy == SnapshotPolicy::checkpointing) {
checkpoint(m);
}
this->mark = nullptr;
const uint32_t bp = toVirtualAddress(pc_ptr, m);
this->channel->write("AT %" PRIu32 "!\n", bp);
}
/**
* Validate if there are interrupts and execute them
*
* The various kinds of interrupts are preceded by an identifier:
*
* - `0x01` : Continue running
* - `0x02` : Halt the execution
* - `0x03` : Pause execution
* - `0x04` : Execute one operation and then pause
* - `0x06` : Add a breakpoint, the address is specified as a pointer.
* The pointer should be specified as: 06[length][pointer]
* eg: 060655a5994fa3d6 (note the lack of spaces between the
* arguments, the 'length' is halve the size of the address string)
* - `0x07` : Remove the breakpoint at the address specified as a pointer if it
* exists (see `0x06`)
* - `0x10` : Dump information about the program
* - `0x11` : show locals
* - `0x12` : Dump full information
* - `0x20` : Replace the content body of a function by a new function given
* as payload (immediately following `0x10`), see #readChange
*/
bool Debugger::checkDebugMessages(Module *m, RunningState *program_state) {
uint8_t *interruptData = this->getDebugMessage();
if (interruptData == nullptr) {
fflush(stdout);
return false;
}
debug("received interrupt %x\n", *interruptData);
fflush(stdout);
this->channel->write("Interrupt: %x\n", *interruptData);
long start = 0, size = 0;
switch (*interruptData) {
case interruptRUN:
this->handleInterruptRUN(m, program_state);
free(interruptData);
break;
case interruptHALT:
this->channel->write("STOP!\n");
this->channel->close();
free(interruptData);
exit(0);
case interruptPAUSE:
this->pauseRuntime(m);
// Make a checkpoint so the debugger knows the current state and
// knows how many instructions were executed since the last
// checkpoint.
if (snapshotPolicy == SnapshotPolicy::checkpointing) {
checkpoint(m, true);
}
this->channel->write("PAUSE!\n");
free(interruptData);
break;
case interruptSTEP:
this->handleSTEP(m, program_state);
free(interruptData);
break;
case interruptSTEPOver:
this->handleSTEPOver(m, program_state);
free(interruptData);
break;
case interruptBPAdd: // Breakpoint
case interruptBPRem: // Breakpoint remove
this->handleInterruptBP(m, interruptData);
free(interruptData);
break;
case interruptContinueFor: {
uint8_t *data = interruptData + 1;
uint32_t amount = read_B32(&data);
debug("Continue for %" PRIu32 " instruction(s)\n", amount);
remaining_instructions = (int32_t)amount;
*program_state = WARDUINOrun;
free(interruptData);
break;
}
case interruptDUMP:
this->pauseRuntime(m);
this->dump(m);
free(interruptData);
break;
case interruptDUMPLocals:
this->pauseRuntime(m);
this->dumpLocals(m);
this->channel->write("\n");
free(interruptData);
break;
case interruptDUMPFull:
this->pauseRuntime(m);
this->dump(m, true);
free(interruptData);
break;
case interruptReset:
this->reset(m);
free(interruptData);
break;
case interruptUPDATEFun:
this->channel->write("CHANGE function!\n");
Debugger::handleChangedFunction(m, interruptData);
// do not free(interruptData);
// we need it to run that code
// TODO: free double replacements
break;
case interruptUPDATELocal:
this->channel->write("CHANGE local!\n");
this->handleChangedLocal(m, interruptData);
free(interruptData);
break;
case interruptUPDATEModule:
handleUpdateModule(m, interruptData);
this->channel->write("CHANGE Module!\n");
free(interruptData);
break;
case interruptUPDATEGlobal:
this->handleUpdateGlobalValue(m, interruptData + 1);
free(interruptData);
break;
case interruptUPDATEStackValue:
this->handleUpdateStackValue(m, interruptData + 1);
free(interruptData);
break;
case interruptINVOKE:
this->handleInvoke(m, interruptData + 1);
free(interruptData);
break;
case interruptSnapshot:
this->pauseRuntime(m);
free(interruptData);
snapshot(m);
this->channel->write("\n");
break;
case interruptSetSnapshotPolicy:
setSnapshotPolicy(m, interruptData + 1);
free(interruptData);
break;
case interruptInspect: {
uint8_t *data = interruptData + 1;
uint16_t numberBytes = read_B16(&data);
uint8_t *state = interruptData + 3;
inspect(m, numberBytes, state);
this->channel->write("\n");
free(interruptData);
break;
}
case interruptLoadSnapshot:
if (!this->receivingData) {
this->pauseRuntime(m);
debug("paused program execution\n");
CallbackHandler::manual_event_resolution = true;
dbg_info("Manual event resolution is on.");
this->receivingData = true;
this->freeState(m, interruptData);
free(interruptData);
this->channel->write("ack!\n");
} else {
debug("receiving state\n");
receivingData = !this->saveState(m, interruptData);
free(interruptData);
debug("sending %s!\n", receivingData ? "ack" : "done");
this->channel->write("%s!\n", receivingData ? "ack" : "done");
}
break;
case interruptProxyCall: {
this->handleProxyCall(m, program_state, interruptData + 1);
free(interruptData);
} break;
case interruptMonitorProxies: {
debug("receiving functions list to proxy\n");
this->handleMonitorProxies(m, interruptData + 1);
free(interruptData);
} break;
case interruptProxify: {
dbg_info("Converting to proxy settings.\n");
this->proxify();
free(interruptData);
break;
}
case interruptDUMPAllEvents:
debug("InterruptDUMPEvents\n");
size = static_cast<long>(CallbackHandler::event_count());
[[fallthrough]];
case interruptDUMPEvents:
// TODO get start and size from message
this->channel->write("{");
this->dumpEvents(start, size);
this->channel->write("}\n");
free(interruptData);
break;
case interruptPOPEvent:
CallbackHandler::resolve_event(true);
free(interruptData);
break;
case interruptPUSHEvent:
this->handlePushedEvent(reinterpret_cast<char *>(interruptData));
free(interruptData);
break;
case interruptRecvCallbackmapping:
Debugger::updateCallbackmapping(
m, reinterpret_cast<const char *>(interruptData + 2));
free(interruptData);
break;
case interruptDUMPCallbackmapping:
this->dumpCallbackmapping();
free(interruptData);
break;
case interruptSetOverridePinValue:
this->addOverride(m, interruptData + 1);
free(interruptData);
break;
case interruptUnsetOverridePinValue:
this->removeOverride(m, interruptData + 1);
free(interruptData);
break;
default:
// handle later
this->channel->write("COULD not parse interrupt data!\n");
free(interruptData);
break;
}
fflush(stdout);
return true;
}
// Private methods
void Debugger::printValue(const StackValue *v, const uint32_t idx,
const bool end = false) const {
char buff[256];
#define FMT(fmt0) "%" fmt0
switch (v->value_type) {
case I32:
snprintf(buff, 255, R"("type":"i32","value":)" FMT(PRIi32),
v->value.uint32);
break;
case I64:
snprintf(buff, 255, R"("type":"i64","value":)" FMT(PRIi64),
v->value.uint64);
break;
case F32:
snprintf(buff, 255, R"("type":"F32","value":")" FMT(PRIx32) "\"",
v->value.uint32);
break;
case F64:
snprintf(buff, 255, R"("type":"F64","value":")" FMT(PRIx64) "\"",
v->value.uint64);
break;
default:
snprintf(buff, 255, R"("type":"%02x","value":")" FMT(PRIx64) "\"",
v->value_type, v->value.uint64);
}
this->channel->write(R"({"idx":%d,%s}%s)", idx, buff, end ? "" : ",");
}
uint8_t *Debugger::findOpcode(Module *m, const Block *block) {
const auto find =
std::find_if(std::begin(m->block_lookup), std::end(m->block_lookup),
[&](const std::pair<uint8_t *, Block *> &pair) {
return pair.second == block;
});
uint8_t *opcode = nullptr;
if (find != std::end(m->block_lookup)) {
opcode = find->first;
} else {
// FIXME FATAL?
debug("find_opcode: not found\n");
exit(33);
}
return opcode;
}
void Debugger::handleInvoke(Module *m, uint8_t *interruptData) const {
const uint32_t fidx = read_LEB_32(&interruptData);
if (fidx >= m->function_count) {
debug("no function available for fidx %" PRIi32 "\n", fidx);
return;
}
const Type func = *m->functions[fidx].type;
StackValue *args = readWasmArgs(func, interruptData);
WARDuino *instance = WARDuino::instance();
const RunningState current = instance->program_state;
instance->program_state = WARDUINOrun;
WARDuino::instance()->invoke(m, fidx, func.param_count, args);
instance->program_state = current;
this->dumpStack(m);
}
void Debugger::handleInterruptRUN(const Module *m,
RunningState *program_state) {
this->channel->write("GO!\n");
if (*program_state == WARDUINOpause && this->isBreakpoint(m->pc_ptr)) {
this->skipBreakpoint = m->pc_ptr;
}
*program_state = WARDUINOrun;
}
void Debugger::handleSTEP(const Module *m, RunningState *program_state) {
*program_state = WARDUINOstep;
this->skipBreakpoint = m->pc_ptr;
}
void Debugger::handleSTEPOver(const Module *m, RunningState *program_state) {
this->skipBreakpoint = m->pc_ptr;
uint8_t const opcode = *m->pc_ptr;
if (opcode == 0x10) { // step over direct call
uint8_t *ptr_cpy = m->pc_ptr + 1;
read_LEB_32(&ptr_cpy);
this->mark = m->pc_ptr + (ptr_cpy - m->pc_ptr);
*program_state = WARDUINOrun;
// warning: ack will be BP hit
} else if (opcode == 0x11) { // step over indirect call
uint8_t *ptr_cpy = m->pc_ptr + 1;
read_LEB_32(&ptr_cpy);
read_LEB_32(&ptr_cpy);
this->mark = m->pc_ptr + (ptr_cpy - m->pc_ptr);
*program_state = WARDUINOrun;
} else {
// normal step
this->handleSTEP(m, program_state);
}
}
void Debugger::handleInterruptBP(Module *m, uint8_t *interruptData) {
uint8_t *bpData = interruptData + 1;
uint32_t virtualAddress = read_B32(&bpData);
if (isToPhysicalAddrPossible(virtualAddress, m)) {
uint8_t *bpt = toPhysicalAddress(virtualAddress, m);
if (*interruptData == 0x06) {
this->addBreakpoint(bpt);
} else {
this->deleteBreakpoint(bpt);
}
}
this->channel->write("BP %" PRIu32 "!\n", virtualAddress);
}
void Debugger::dump(Module *m, bool full) const {
auto toVA = [m](uint8_t *addr) { return toVirtualAddress(addr, m); };
this->channel->write("{");
// current PC
this->channel->write("\"pc\":%" PRIu32 ",", toVA(m->pc_ptr));
this->dumpBreakpoints(m);
this->dumpFunctions(m);
this->dumpCallstack(m);
if (full) {
this->channel->write(R"(, "locals": )");
this->dumpLocals(m);
this->channel->write(", ");
this->dumpEvents(0, static_cast<long>(CallbackHandler::event_count()));
}
this->channel->write("}\n\n");
// fflush(stdout);
}
void Debugger::dumpStack(const Module *m) const {
this->channel->write("{\"stack\": [");
int32_t i = m->sp;
while (0 <= i) {
this->printValue(&m->stack[i], i, i < 1);
i--;
}
this->channel->write("]}\n\n");
}
void Debugger::dumpBreakpoints(Module *m) const {
this->channel->write("\"breakpoints\":[");
{
size_t i = 0;
for (auto bp : this->breakpoints) {
this->channel->write("%" PRIu32 "%s", toVirtualAddress(bp, m),
(++i < this->breakpoints.size()) ? "," : "");
}
}
this->channel->write("],");
}
void Debugger::dumpFunctions(Module *m) const {
this->channel->write("\"functions\":[");
for (size_t i = m->import_count; i < m->function_count; i++) {
this->channel->write(R"({"fidx":"0x%x",)", m->functions[i].fidx);
this->channel->write("\"from\":%" PRIu32 ",\"to\":%" PRIu32 "}%s",
toVirtualAddress(m->functions[i].start_ptr, m),
toVirtualAddress(m->functions[i].end_ptr, m),
(i < m->function_count - 1) ? "," : "],");
}
}
/*
* {"type":%u,"fidx":"0x%x","sp":%d,"fp":%d,"ra":"%p"}%s
*/
void Debugger::dumpCallstack(Module *m) const {
auto toVA = [m](uint8_t *addr) { return toVirtualAddress(addr, m); };
this->channel->write("\"callstack\":[");
for (int i = 0; i <= m->csp; i++) {
const Frame *f = &m->callstack[i];
int callsite_retaddr = -1;
int retaddr = -1;
// first frame has no retrun address
if (f->ra_ptr != nullptr) {
uint8_t *callsite = nullptr;
callsite = f->ra_ptr - 2; // callsite of function (if type 0)
callsite_retaddr = static_cast<int>(toVA(callsite));
retaddr = static_cast<int>(toVA(f->ra_ptr));
}
this->channel->write(R"({"type":%u,"fidx":"0x%x","sp":%d,"fp":%d,)",
f->block->block_type, f->block->fidx, f->sp,
f->fp);
this->channel->write("\"start\":%" PRIu32
",\"ra\":%d,\"callsite\":%d}%s",
toVA(f->block->start_ptr), retaddr,
callsite_retaddr, (i < m->csp) ? "," : "]");
}
}
void Debugger::dumpLocals(const Module *m) const {
// fflush(stdout);
int firstFunFramePtr = m->csp;
while (m->callstack[firstFunFramePtr].block->block_type != 0) {
firstFunFramePtr--;
if (firstFunFramePtr < 0) {
FATAL("Not in a function!");
}
}
Frame *f = &m->callstack[firstFunFramePtr];
this->channel->write(R"({"count":%u,"locals":[)", f->block->local_count);
// fflush(stdout); // FIXME: this is needed for ESP to properly print
for (uint32_t i = 0; i < f->block->local_count; i++) {
char _value_str[256];
auto v = &m->stack[m->fp + i];
switch (v->value_type) {
case I32:
snprintf(_value_str, 255,
R"("type":"i32","value":)" FMT(PRIi32),
v->value.uint32);
break;
case I64:
snprintf(_value_str, 255,
R"("type":"i64","value":)" FMT(PRIi64),
v->value.uint64);
break;
case F32:
snprintf(_value_str, 255, R"("type":"F32","value":%.7f)",
v->value.f32);
break;
case F64:
snprintf(_value_str, 255, R"("type":"F64","value":%.7f)",
v->value.f64);
break;
default:
snprintf(_value_str, 255,
R"("type":"%02x","value":")" FMT(PRIx64) "\"",
v->value_type, v->value.uint64);
}
this->channel->write("{%s, \"index\":%u}%s", _value_str,
i + f->block->type->param_count,
(i + 1 < f->block->local_count) ? "," : "");
}
this->channel->write("]}");
// fflush(stdout);
#undef FMT
}
void Debugger::dumpEvents(long start, long size) const {
bool previous = CallbackHandler::resolving_event;
CallbackHandler::resolving_event = true;
if (size > EVENTS_SIZE) {
size = EVENTS_SIZE;
}
this->channel->write(R"("events": [)");
long index = start, end = start + size;
std::for_each(CallbackHandler::event_begin() + start,
CallbackHandler::event_begin() + end,
[this, &index, &end](const Event &e) {
this->channel->write(
R"({"topic": "%s", "payload": "%s"})",
e.topic.c_str(), e.payload.c_str());
if (++index < end) {
this->channel->write(", ");
}
});
this->channel->write("]");
CallbackHandler::resolving_event = previous;
}
void Debugger::dumpCallbackmapping() const {
this->channel->write("%s\n", CallbackHandler::dump_callbacks().c_str());
}
/**
* Read the change in bytes array.
*
* The array should be of the form
* [0x10, index, ... new function body 0x0b]
* Where index is the index without imports
*/
bool Debugger::handleChangedFunction(const Module *m, uint8_t *bytes) {
// Check if this was a change request
if (*bytes != interruptUPDATEFun) return false;
// SKIP the first byte (0x10), type of change
uint8_t *pos = bytes + 1;
uint32_t b = read_LEB_32(&pos); // read id
Block *function = &m->functions[m->import_count + b];
const uint32_t body_size = read_LEB_32(&pos);
uint8_t *payload_start = pos;
const uint32_t local_count = read_LEB_32(&pos);
uint8_t *save_pos = pos;
uint32_t tidx, lidx, lecount;
// Local variable handling
// Get number of locals for alloc
function->local_count = 0;
for (uint32_t l = 0; l < local_count; l++) {
lecount = read_LEB_32(&pos);
function->local_count += lecount;
tidx = read_LEB(&pos, 7);
(void)tidx; // TODO: use tidx?
}
if (function->local_count > 0) {
function->local_value_type = static_cast<uint8_t *>(
acalloc(function->local_count, sizeof(uint8_t),
"function->local_value_type"));
}
// Restore position and read the locals
pos = save_pos;
lidx = 0;
for (uint32_t l = 0; l < local_count; l++) {
lecount = read_LEB_32(&pos);
uint8_t vt = read_LEB(&pos, 7);
for (uint32_t i = 0; i < lecount; i++) {
function->local_value_type[lidx++] = vt;
}
}
function->start_ptr = pos;
function->end_ptr = payload_start + body_size - 1;
function->br_ptr = function->end_ptr;
ASSERT(*function->end_ptr == 0x0b, "Code section did not end with 0x0b\n");
pos = function->end_ptr + 1;
return true;
}
/**
* Read change to local
* @param m
* @param bytes
* @return
*/
bool Debugger::handleChangedLocal(const Module *m, uint8_t *bytes) const {
if (*bytes != interruptUPDATELocal) return false;
uint8_t *pos = bytes + 1;
this->channel->write("Local updates: %x\n", *pos);
uint32_t localId = read_LEB_32(&pos);
this->channel->write("Local %u being changed\n", localId);
auto v = &m->stack[m->fp + localId];
switch (v->value_type) {
case I32:
v->value.uint32 = read_LEB_signed(&pos, 32);
break;
case I64:
v->value.int64 = static_cast<int64_t>(read_LEB_signed(&pos, 64));
break;
case F32:
memcpy(&v->value.uint32, pos, 4);
break;
case F64:
memcpy(&v->value.uint64, pos, 8);
break;
default: // nothing to do :(
break;
}
this->channel->write("Local %u changed to %u\n", localId, v->value.uint32);
return true;
}
void Debugger::notifyPushedEvent() const {
this->channel->write("new pushed event\n");
}
bool Debugger::handlePushedEvent(char *bytes) const {
if (*bytes != interruptPUSHEvent) return false;
auto parsed = nlohmann::json::parse(bytes + 1);
debug("handle pushed event: %s\n", bytes + 1);
auto *event = new Event(*parsed.find("topic"), *parsed.find("payload"));
CallbackHandler::push_event(event);
this->notifyPushedEvent();
return true;
}
void Debugger::snapshot(Module *m) const {
uint16_t numberBytes = 12;
uint8_t state[] = {pcState,
breakpointsState,
callstackState,
globalsState,
tableState,
memoryState,
branchingTableState,
stackState,
callbacksState,
eventsState,
ioState,
overridesState};
inspect(m, numberBytes, state);
}
void Debugger::inspect(Module *m, const uint16_t sizeStateArray,
const uint8_t *state) const {
debug("asked for inspect\n");
uint16_t idx = 0;
auto toVA = [m](uint8_t *addr) { return toVirtualAddress(addr, m); };
bool addComma = false;
this->channel->write("{");
while (idx < sizeStateArray) {
switch (state[idx++]) {
case pcState: { // PC
this->channel->write("\"pc\":%" PRIu32 "", toVA(m->pc_ptr));
addComma = true;
break;
}
case breakpointsState: {
this->channel->write("%s\"breakpoints\":[",
addComma ? "," : "");
addComma = true;
size_t i = 0;
for (auto bp : this->breakpoints) {
this->channel->write(
"%" PRIu32 "%s", toVA(bp),
(++i < this->breakpoints.size()) ? "," : "");
}
this->channel->write("]");
break;
}
case callstackState: {
this->channel->write("%s\"callstack\":[", addComma ? "," : "");
addComma = true;
for (int j = 0; j <= m->csp; j++) {
const Frame *f = &m->callstack[j];
const uint8_t bt = f->block->block_type;
const uint32_t block_key =
(bt == 0 || bt == 0xff || bt == 0xfe)
? 0
: toVA(findOpcode(m, f->block));
const uint32_t fidx = bt == 0 ? f->block->fidx : 0;
const auto ra = f->ra_ptr == nullptr ? -1 : toVA(f->ra_ptr);
this->channel->write(
R"({"type":%u,"fidx":"0x%x","sp":%d,"fp":%d,"idx":%d,)",
bt, fidx, f->sp, f->fp, j);
this->channel->write(
"\"block_key\":%" PRIu32 ",\"ra\":%d}%s", block_key, ra,
(j < m->csp) ? "," : "");
}
this->channel->write("]");
break;
}
case stackState: {
this->channel->write("%s\"stack\":[", addComma ? "," : "");
addComma = true;
for (int j = 0; j <= m->sp; j++) {
auto v = &m->stack[j];
printValue(v, j, j == m->sp);
}
this->channel->write("]");
break;
}
case globalsState: {
this->channel->write("%s\"globals\":[", addComma ? "," : "");
addComma = true;
for (uint32_t j = 0; j < m->global_count; j++) {
auto v = (*(m->globals + j))->value;
printValue(v, j, j == (m->global_count - 1));
}
this->channel->write("]"); // closing globals
break;
}
case tableState: {
this->channel->write(
R"(%s"table":{"max":%d, "init":%d, "elements":[)",
addComma ? "," : "", m->table.maximum, m->table.initial);
addComma = true;
for (uint32_t j = 0; j < m->table.size; j++) {
this->channel->write("%" PRIu32 "%s", m->table.entries[j],
(j + 1) == m->table.size ? "" : ",");
}
this->channel->write("]}"); // closing table
break;
}
case branchingTableState: {
this->channel->write(
R"(%s"br_table":{"size":"0x%x","labels":[)",
addComma ? "," : "", BR_TABLE_SIZE);
for (uint32_t j = 0; j < BR_TABLE_SIZE; j++) {
this->channel->write("%" PRIu32 "%s", m->br_table[j],
(j + 1) == BR_TABLE_SIZE ? "" : ",");
}
this->channel->write("]}");
break;
}
case memoryState: {
uint32_t total_elems =
m->memory.pages * static_cast<uint32_t>(PAGE_SIZE);
this->channel->write(
R"(%s"memory":{"pages":%d,"max":%d,"init":%d,"bytes":[)",
addComma ? "," : "", m->memory.pages, m->memory.maximum,
m->memory.initial);
addComma = true;
if (total_elems != 0) {
uint8_t data = m->memory.bytes[0];
uint32_t count = 1;
bool arrayComma = false;
for (uint32_t j = 1; j < total_elems; j++) {
if (m->memory.bytes[j] == data) {
count++;
} else {
this->channel->write("%s%" PRIu8 ",%d",
arrayComma ? "," : "", data,
count);
arrayComma = true;
data = m->memory.bytes[j];
count = 1;
}
}
this->channel->write("%s%" PRIu8 ",%d",
arrayComma ? "," : "", data, count);
}
this->channel->write("]}"); // closing memory
break;
}
case callbacksState: {
bool noOuterBraces = false;
this->channel->write(
"%s%s", addComma ? "," : "",
CallbackHandler::dump_callbacksV2(noOuterBraces).c_str());
addComma = true;
break;
}
case eventsState: {
this->channel->write("%s", addComma ? "," : "");
this->dumpEvents(
0, static_cast<long>(CallbackHandler::event_count()));
addComma = true;
break;
}
case ioState: {
this->channel->write("%s", addComma ? "," : "");
this->channel->write("\"io\": [");
bool comma = false;
std::vector<IOStateElement *> external_state =
m->warduino->interpreter->get_io_state(m);
for (auto state_elem : external_state) {
this->channel->write("%s{", comma ? ", " : "");
this->channel->write(
R"("key": "%s", "output": %s, "value": %d)",
state_elem->key.c_str(),
state_elem->output ? "true" : "false",
state_elem->value);
this->channel->write("}");
comma = true;
delete state_elem;
}
this->channel->write("]");
addComma = true;
break;
}
case overridesState: {
this->channel->write("%s", addComma ? "," : "");
this->channel->write(R"("overrides": [)");
bool comma = false;
for (auto key : overrides) {
for (auto argResult : key.second) {
this->channel->write("%s", comma ? ", " : "");
this->channel->write(
R"({"fidx": %d, "arg": %d, "return_value": %d})",
key.first, argResult.first, argResult.second);
comma = true;
}
}
this->channel->write("]");
addComma = true;
break;
}
default: {
debug("dumpExecutionState: Received unknown state request\n");
break;
}
}
}
this->channel->write("}");
}
void Debugger::setSnapshotPolicy(Module *m, uint8_t *interruptData) {
uint8_t **data_ptr = &interruptData;
if (*interruptData <= 2) {
snapshotPolicy = SnapshotPolicy{*interruptData};
min_return_values = 0;
if (checkpoint_state) {
free(checkpoint_state);
}
checkpoint_state = nullptr;
checkpoint_state_size = 0;
} else {
snapshotPolicy = SnapshotPolicy::checkpointing;
*data_ptr += 1;
min_return_values = read_LEB_32(data_ptr);
if (checkpoint_state) {
free(checkpoint_state);
}
checkpoint_state_size = read_LEB_32(data_ptr);
checkpoint_state = new uint8_t[checkpoint_state_size];
for (int i = 0; i < checkpoint_state_size; i++) {
checkpoint_state[i] = **data_ptr;
*data_ptr += 1;
}
}
// Make a checkpoint when you first enable checkpointing
if (snapshotPolicy == SnapshotPolicy::checkpointing) {
uint8_t *ptr = *data_ptr + 1;
checkpointInterval = read_B32(&ptr);
checkpoint(m, true);
}