Repository navigation
Expand file tree
/
Copy pathudbg.c
More file actions
1978 lines (1624 loc) · 57.3 KB
/
Copy pathudbg.c
File metadata and controls
1978 lines (1624 loc) · 57.3 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
/*
* udbg - ucode debugger client
*
* Copyright (C) 2026 Jo-Philipp Wich <jo@mein.io>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ANY IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* ---
*
* Interactive client for ucode's line-based debug protocol (one uppercase
* VERB, optionally followed by a space and a JSON object, per '\n'-terminated
* line - see lib/debug_proto.h). This client owns all user-facing rendering:
* the server-side debug core never emits ANSI or formatted columns, only
* structured data (plus, where a rendering-rich port needed more than the
* original data model had - e.g. DISASSEMBLE's raw instruction bytes - a
* small additive extension of that same structured data, never markup).
*
* Three ways to obtain a connection:
* udbg <pid> - SIGUSR1-attach to a running `-X` process (gdb -p style)
* udbg <path> - connect to an explicit debug.listen(path) socket
* udbg --fd N - use an already-connected, inherited fd N (used
* internally by the local `-x` CLI, which forks this
* binary with one end of a socketpair on fd 3)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <ctype.h>
#include <inttypes.h>
#include <stdbool.h>
#include <json-c/json.h>
#include "debug_highlight.h"
#include "debug_lineedit.h"
/* -- ANSI colors ----------------------------------------------------------- */
#define C_RESET "\033[0m"
#define C_DIM "\033[2m"
#define C_BOLD "\033[1m"
#define C_RED "\033[31m"
#define C_GREEN "\033[32m"
#define C_YELLOW "\033[33m"
#define C_BLUE "\033[34m"
#define C_MAGENTA "\033[35m"
#define C_CYAN "\033[36m"
#define C_EVENT "\033[2;3m" /* faint + italic, for async server events */
#define MAX_LINE 65536
#define DEFAULT_SOCKET_DIR "/tmp"
#define MAX_WAIT_TIME 30
/* -- wire framing ----------------------------------------------------------
*
* Mirrors lib/debug_proto.c's framing without depending on it: this client
* has no ucode VM of its own to hand `ucv_*` helpers, so it talks the wire
* format directly in terms of json-c objects instead. */
static void
proto_write(int fd, const char *verb, struct json_object *payload)
{
const char *json;
char *line;
size_t len;
ssize_t n;
const char *p;
if (payload) {
json = json_object_to_json_string_ext(payload, JSON_C_TO_STRING_PLAIN);
len = strlen(verb) + 1 + strlen(json) + 1;
line = malloc(len + 1);
snprintf(line, len + 1, "%s %s\n", verb, json);
}
else {
len = strlen(verb) + 1;
line = malloc(len + 1);
snprintf(line, len + 1, "%s\n", verb);
}
p = line;
while (len > 0) {
n = write(fd, p, len);
if (n < 0) {
if (errno == EINTR)
continue;
break;
}
p += n;
len -= (size_t)n;
}
free(line);
}
/* Growable line-buffered reader, one instance per connection. */
typedef struct {
char *data;
size_t len, cap;
} linebuf_t;
static bool
linebuf_append(linebuf_t *lb, const char *data, size_t n)
{
if (lb->len + n > lb->cap) {
size_t newcap = lb->cap ? lb->cap : 4096;
while (newcap < lb->len + n)
newcap *= 2;
char *p = realloc(lb->data, newcap);
if (!p)
return false;
lb->data = p;
lb->cap = newcap;
}
memcpy(lb->data + lb->len, data, n);
lb->len += n;
return true;
}
/* Extract one already-buffered "VERB [json]" line, if any, without touching
* the fd. Returns false if no full line is buffered yet. */
static bool
linebuf_pop(linebuf_t *lb, char **verb_out, struct json_object **payload_out)
{
char *nl = memchr(lb->data, '\n', lb->len);
size_t linelen, verblen;
char *line, *sp;
if (!nl)
return false;
linelen = (size_t)(nl - lb->data);
line = malloc(linelen + 1);
memcpy(line, lb->data, linelen);
line[linelen] = '\0';
memmove(lb->data, lb->data + linelen + 1, lb->len - linelen - 1);
lb->len -= linelen + 1;
if (linelen > 0 && line[linelen - 1] == '\r')
line[--linelen] = '\0';
sp = memchr(line, ' ', linelen);
verblen = sp ? (size_t)(sp - line) : linelen;
*verb_out = malloc(verblen + 1);
memcpy(*verb_out, line, verblen);
(*verb_out)[verblen] = '\0';
*payload_out = NULL;
if (sp && *(sp + 1))
*payload_out = json_tokener_parse(sp + 1);
free(line);
return true;
}
/* Block until a full message is available on `fd`/`lb` and pop it - used for
* the synchronous SOURCE request/response round-trip triggered from within
* rendering. Only safe to call while the session is paused and no other
* request is outstanding (true for every call site below): the server only
* ever answers strictly in request order while paused, so the first message
* to arrive is the one we asked for, barring the rare case of an async
* EVENT interleaving, which is not handled specially here. */
static const char *
jstr(struct json_object *obj, const char *key, const char *dflt)
{
struct json_object *v;
if (obj && json_object_object_get_ex(obj, key, &v) && json_object_is_type(v, json_type_string))
return json_object_get_string(v);
return dflt;
}
static int64_t
jint(struct json_object *obj, const char *key, int64_t dflt)
{
struct json_object *v;
if (obj && json_object_object_get_ex(obj, key, &v))
return json_object_get_int64(v);
return dflt;
}
/* Every "col"/"from_col"/"to_col" field the protocol sends is 1-based (see
* uc_source_get_line() in source.c), meant for human-readable "line:col"
* display - debug_highlight's span/ip columns are 0-based byte indices
* into the line string, so any such field needs this before being used as
* one. */
static size_t
col0(int64_t col)
{
return (col > 0) ? (size_t)(col - 1) : 0;
}
/* -- source cache & syntax highlighting ----------------------------------- */
typedef struct source_cache_entry {
char *file;
char **lines;
size_t nlines;
struct source_cache_entry *next;
} source_cache_entry_t;
static source_cache_entry_t *source_cache = NULL;
static char **
split_lines(const char *text, size_t *nlines_out)
{
size_t count = 1, i;
char **lines;
const char *p, *start;
for (p = text; *p; p++)
if (*p == '\n')
count++;
lines = calloc(count, sizeof(char *));
i = 0;
start = text;
for (p = text; ; p++) {
if (*p == '\n' || *p == '\0') {
size_t len = (size_t)(p - start);
if (len > 0 && start[len - 1] == '\r')
len--;
lines[i] = malloc(len + 1);
memcpy(lines[i], start, len);
lines[i][len] = '\0';
i++;
if (*p == '\0')
break;
start = p + 1;
}
}
*nlines_out = i;
return lines;
}
static char **
find_cached_source(const char *file, size_t *nlines_out)
{
source_cache_entry_t *e;
for (e = source_cache; e; e = e->next) {
if (!strcmp(e->file, file)) {
*nlines_out = e->nlines;
return e->lines;
}
}
return NULL;
}
/* Split and cache already-known source `text` for `file` (e.g. from a
* SOURCE response the caller already has in hand), so a later
* render_source_lines() call for the same file doesn't re-request it. */
static char **
cache_source_text(const char *file, const char *text, size_t *nlines_out)
{
source_cache_entry_t *e;
char **cached = find_cached_source(file, nlines_out);
if (cached)
return cached;
e = malloc(sizeof(source_cache_entry_t));
e->file = strdup(file);
e->lines = split_lines(text, &e->nlines);
e->next = source_cache;
source_cache = e;
*nlines_out = e->nlines;
return e->lines;
}
/* Local source root override (-s/--srcdir), used when the path the server
* reports doesn't exist as-is on this machine - see try_load_local_file(). */
static const char *opt_srcdir = NULL;
static char *
read_whole_file(FILE *fp)
{
char buf[65536];
size_t n, cap = 0, len = 0;
char *text = NULL;
while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
if (len + n + 1 > cap) {
cap = cap ? cap * 2 : 65536;
while (cap < len + n + 1)
cap *= 2;
text = realloc(text, cap);
}
memcpy(text + len, buf, n);
len += n;
}
if (!text)
text = malloc(1);
text[len] = '\0';
return text;
}
/* Debugging usually either runs fully locally (the client and the debugged
* script share the same filesystem - the common `-x`/`udbg <pid>`-on-the-
* same-box case) or from a development checkout against a remote target
* (the *client* has the better/only real source access, not the server) -
* in both cases, the client reading the file itself is at least as likely
* to succeed as asking the server for it, and doesn't need a round trip.
* Only once this fails do callers fall back to requesting SOURCE from the
* server (e.g. the target is a remote embedded device with no shared
* filesystem, or running precompiled bytecode with only embedded source).
*
* Tries the path exactly as the server reported it first (already correct
* for the local case, and for absolute paths that happen to also exist on
* this machine), then, if `-s/--srcdir DIR` was given, DIR joined with
* just the reported path's basename - a simple heuristic for "the server's
* path is from a different checkout/build root than this one". */
static char **
try_load_local_file(const char *file, size_t *nlines_out)
{
FILE *fp = fopen(file, "rb");
char *joined = NULL;
if (!fp && opt_srcdir) {
const char *base = strrchr(file, '/');
base = base ? base + 1 : file;
joined = malloc(strlen(opt_srcdir) + 1 + strlen(base) + 1);
sprintf(joined, "%s/%s", opt_srcdir, base);
fp = fopen(joined, "rb");
}
free(joined);
if (!fp)
return NULL;
{
char *text = read_whole_file(fp);
char **lines = cache_source_text(file, text, nlines_out);
fclose(fp);
free(text);
return lines;
}
}
/* Rendering a source range/context needs the actual text, which only ever
* arrives asynchronously as a SOURCE response processed by the normal main
* loop - never via a nested blocking round-trip from inside another
* response's rendering, which would re-enter the single shared connection
* state from two places at once. So when the file isn't cached yet, a
* render call fires off a SOURCE request and remembers what it wanted to
* show as `pending_source`; the main loop's SOURCE handler finishes the
* render once the response actually arrives. */
typedef struct {
bool active;
char *file;
int64_t from, to;
debug_highlight_span_t hl;
bool have_hl;
size_t left_pad;
} pending_source_t;
static pending_source_t pending_source = { 0 };
static void
request_source(int fd, const char *file, int64_t from, int64_t to,
const debug_highlight_span_t *hl, size_t left_pad)
{
struct json_object *payload;
/* A fetch for this exact file is already in flight (e.g. the initial
* PAUSED's own auto-context request hasn't resolved yet when a
* "lines" response also wants it) - don't send a second SOURCE
* request that would only overwrite this same pending_source's
* tracking with no way to reconcile the two, just adopt whichever
* range was asked for most recently and let the one response in
* flight satisfy it. */
if (pending_source.active && !strcmp(pending_source.file, file)) {
pending_source.from = from;
pending_source.to = to;
pending_source.have_hl = (hl != NULL);
pending_source.left_pad = left_pad;
if (hl)
pending_source.hl = *hl;
return;
}
payload = json_object_new_object();
json_object_object_add(payload, "file", json_object_new_string(file));
proto_write(fd, "SOURCE", payload);
json_object_put(payload);
free(pending_source.file);
pending_source.active = true;
pending_source.file = strdup(file);
pending_source.from = from;
pending_source.to = to;
pending_source.have_hl = (hl != NULL);
pending_source.left_pad = left_pad;
if (hl)
pending_source.hl = *hl;
}
/* Current terminal width, for the same wrap/pad behavior
* debug_highlight_print_source()'s ported original had via term_width().
* Falls back to 80 columns when stdout isn't a tty (e.g. piped output). */
static size_t
term_columns(void)
{
struct winsize w;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0 && w.ws_col > 0)
return w.ws_col;
return 80;
}
/* Print source lines [from, to] (1-based, inclusive) from `file`, shading
* the `hl` statement span if given. If the text isn't cached yet,
* asynchronously requests it (see `pending_source` above) and returns
* without printing anything - the main loop's SOURCE response handler
* re-invokes this once the text has actually arrived. */
/* Mirrors format_context_statement()'s range-splitting for a statement/
* function too long to show in full: a window of context around `from`,
* a gap, and a window around the current instruction and/or `to` - using
* the same 2-line-before/2-line-after context radius render_paused()/
* render_backtrace_final() already use. Returns the number of ranges
* written to `ranges` (1 if the span is short enough to just show whole,
* up to 3 otherwise). Falls back to a single [from, to] range verbatim if
* there's no known "current line" to anchor the split around. */
static size_t
compute_context_ranges(int64_t from, int64_t to, const debug_highlight_span_t *hl,
debug_highlight_range_t ranges[3])
{
const int64_t ctx = 2;
int64_t ip;
debug_highlight_range_t r[3] = { { 0, 0 }, { 0, 0 }, { 0, 0 } };
size_t n = 0, i;
if (from < 1)
from = 1;
if (!hl || !hl->have_ip || to - from <= 4) {
ranges[0] = (debug_highlight_range_t){ (size_t)from, (size_t)to };
return 1;
}
ip = (int64_t)hl->ip_line;
if (ip < from)
ip = from;
if (ip > to)
ip = to;
if (ip - from <= (ctx + ctx + 2)) {
r[1].from = (size_t)from;
}
else {
r[0].from = (size_t)from;
r[0].to = (size_t)(from + ctx);
r[1].from = (size_t)(ip - ctx);
}
if (to - ip <= (ctx + ctx + 2)) {
r[1].to = (size_t)to;
}
else {
r[1].to = (size_t)(ip + ctx);
r[2].from = (size_t)(to - ctx);
r[2].to = (size_t)to;
}
for (i = 0; i < 3; i++)
if (r[i].from && r[i].to)
ranges[n++] = r[i];
return n;
}
static void
render_source_lines(int fd, const char *file, int64_t from, int64_t to,
const debug_highlight_span_t *hl, size_t left_pad)
{
size_t nlines;
char **lines = find_cached_source(file, &nlines);
if (!lines)
lines = try_load_local_file(file, &nlines);
if (!lines) {
request_source(fd, file, from, to, hl, left_pad);
return;
}
if (from < 1)
from = 1;
{
size_t columns = term_columns();
debug_highlight_range_t ranges[3];
size_t nranges;
columns = (columns > left_pad) ? columns - left_pad : 0;
nranges = compute_context_ranges(from, to, hl, ranges);
debug_highlight_print_source_ranges(stdout, lines, nlines,
nranges, ranges, hl, left_pad, columns);
}
}
/* -- response rendering ------------------------------------------------- */
/* Join a JSON array of strings with " \xc2\xbb " (U+00BB, " » "), matching
* format_context_breadcrumb()'s separator. Caller frees the result. */
static char *
join_breadcrumb(struct json_object *arr)
{
static const char sep[] = " \xc2\xbb "; /* U+00BB RIGHT-POINTING GUILLEMET */
size_t n = arr ? json_object_array_length(arr) : 0;
size_t len = 0, i;
char *out, *p;
if (n == 0)
return strdup("");
for (i = 0; i < n; i++)
len += strlen(json_object_get_string(json_object_array_get_idx(arr, i)));
len += (n - 1) * (sizeof(sep) - 1);
out = p = malloc(len + 1);
for (i = 0; i < n; i++) {
const char *s = json_object_get_string(json_object_array_get_idx(arr, i));
size_t l = strlen(s);
if (i > 0) {
memcpy(p, sep, sizeof(sep) - 1);
p += sizeof(sep) - 1;
}
memcpy(p, s, l);
p += l;
}
*p = '\0';
return out;
}
static void
render_paused(int fd, struct json_object *p)
{
int64_t line = jint(p, "line", 0);
const char *file = jstr(p, "file", NULL);
printf(C_BOLD "Paused" C_RESET " (%s) in " C_BOLD "%s()" C_RESET ", %s:%" PRId64 ":%" PRId64 "\n",
jstr(p, "reason", "?"),
jstr(p, "function", "?"),
file ? file : "?",
line,
jint(p, "col", 0));
if (json_object_object_get_ex(p, "breakpoint_id", NULL))
printf(" " C_GREEN "breakpoint #%" PRId64 C_RESET "\n", jint(p, "breakpoint_id", 0));
if (json_object_object_get_ex(p, "exception_message", NULL))
printf(" " C_RED "exception: %s" C_RESET "\n", jstr(p, "exception_message", ""));
if (file && line > 0) {
struct json_object *breadcrumb_arr = json_object_object_get(p, "breadcrumb");
char *breadcrumb = join_breadcrumb(breadcrumb_arr);
int64_t col = jint(p, "col", 0);
debug_highlight_span_t hl = {
.from_line = (size_t)line, .from_col = 0,
.to_line = (size_t)line, .to_col = SIZE_MAX,
.have_ip = true, .ip_line = (size_t)line, .ip_col = col0(col)
};
debug_highlight_print_header_bar(stdout, file, breadcrumb, 0, term_columns());
free(breadcrumb);
render_source_lines(fd, file, line - 2, line + 2, &hl, 0);
}
}
static void
render_breakpoints(struct json_object *p)
{
struct json_object *items = NULL;
size_t i, n;
json_object_object_get_ex(p, "items", &items);
n = items ? json_object_array_length(items) : 0;
if (n == 0) {
printf("No breakpoints set\n");
return;
}
for (i = 0; i < n; i++) {
struct json_object *it = json_object_array_get_idx(items, i);
struct json_object *idv = NULL;
if (json_object_object_get_ex(it, "id", &idv))
printf(C_BOLD "#%-4" PRId64 C_RESET " ", json_object_get_int64(idv));
else
printf(C_DIM "(%-4s)" C_RESET " ", jstr(it, "kind", "?"));
if (json_object_object_get_ex(it, "file", NULL))
printf("%s:%" PRId64 ":%" PRId64 " - %s\n",
jstr(it, "file", "?"), jint(it, "line", 0),
jint(it, "col", 0), jstr(it, "function", "?"));
else
printf("<next instruction>\n");
}
}
static void
render_variables_array(struct json_object *items, const char *indent)
{
size_t i, n = items ? json_object_array_length(items) : 0;
debug_variable_t *vars = calloc(n ? n : 1, sizeof(*vars));
for (i = 0; i < n; i++) {
struct json_object *it = json_object_array_get_idx(items, i);
struct json_object *shadowed_j = json_object_object_get(it, "shadowed");
vars[i].name = jstr(it, "name", "?");
vars[i].kind = jstr(it, "kind", "");
vars[i].value_repr = jstr(it, "value_repr", "");
vars[i].shadowed = shadowed_j && json_object_get_boolean(shadowed_j);
}
debug_highlight_print_variables(stdout, vars, n, indent, term_columns());
free(vars);
}
/* Async multi-file fetch for render_backtrace(): a backtrace can span
* several source files at once (unlike PAUSED/LINES, which only ever need
* one), so a single pending_source-style slot isn't enough - this instead
* queues every file the frames need that isn't cached yet, fetches them
* one at a time, and only actually prints once all of them have arrived. */
typedef struct {
bool active;
struct json_object *payload;
char **files;
size_t nfiles, next;
} pending_backtrace_t;
static pending_backtrace_t pending_backtrace = { 0 };
static void
request_backtrace_file(int fd, const char *file)
{
struct json_object *payload = json_object_new_object();
json_object_object_add(payload, "file", json_object_new_string(file));
proto_write(fd, "SOURCE", payload);
json_object_put(payload);
}
static void
render_backtrace_final(int fd, struct json_object *p)
{
struct json_object *frames = NULL;
size_t i, n;
json_object_object_get_ex(p, "frames", &frames);
n = frames ? json_object_array_length(frames) : 0;
for (i = 0; i < n; i++) {
struct json_object *fr = json_object_array_get_idx(frames, i);
struct json_object *vars = NULL;
const char *file = jstr(fr, "file", NULL);
int64_t line = jint(fr, "line", 0);
int64_t col = jint(fr, "col", 0);
bool native = !strcmp(jstr(fr, "kind", ""), "native");
char signature[256];
char prefix[16];
size_t prefix_len, columns = term_columns();
snprintf(signature, sizeof(signature), "%s()", jstr(fr, "function", "?"));
/* "#N " is printed right before the header bar, on the same line -
* left_pad itself would make the bar draw *another* copy of that
* indentation (it is meant for a bar that draws its own leading
* blanks, see render_paused() above for that usage), so instead
* just shrink the width budget by the prefix that already went
* out via printf() below, and leave left_pad at 0. Without this,
* the bar is sized for the full terminal width and the combined
* line overflows it by exactly the prefix's length. */
prefix_len = (size_t)snprintf(prefix, sizeof(prefix), "#%-2" PRId64 " ", jint(fr, "index", 0));
columns = (columns > prefix_len) ? columns - prefix_len : 0;
printf(C_BOLD "%s" C_RESET, prefix);
debug_highlight_print_header_bar(stdout,
native ? "C" : (file ? file : "?"), signature, 0, columns);
if (!native && file && line > 0) {
debug_highlight_span_t hl = {
.from_line = (size_t)line, .from_col = 0,
.to_line = (size_t)line, .to_col = SIZE_MAX,
.have_ip = true, .ip_line = (size_t)line, .ip_col = col0(col)
};
render_source_lines(fd, file, line - 2, line + 2, &hl, 2);
}
/* tail call optimization reuses this frame for the callee, so the
* intermediate frames of the tail calls are absent from the stack -
* show the gap (see uc_vm_frame_reinit() in vm.c). */
{
struct json_object *tco_j = json_object_object_get(fr, "tco");
if (tco_j && json_object_get_int64(tco_j) > 0)
printf(C_DIM " (%" PRId64 " tail call frames omitted)" C_RESET "\n",
json_object_get_int64(tco_j));
}
if (json_object_object_get_ex(fr, "variables", &vars))
render_variables_array(vars, " - ");
printf("\n");
}
}
static void
render_backtrace(int fd, struct json_object *p)
{
struct json_object *frames = NULL;
size_t i, n;
char **missing = NULL;
size_t n_missing = 0, cap = 0;
json_object_object_get_ex(p, "frames", &frames);
n = frames ? json_object_array_length(frames) : 0;
for (i = 0; i < n; i++) {
struct json_object *fr = json_object_array_get_idx(frames, i);
const char *file = jstr(fr, "file", NULL);
size_t dummy;
size_t j;
bool already = false;
if (!file || strcmp(jstr(fr, "kind", ""), "script"))
continue;
if (find_cached_source(file, &dummy))
continue;
if (try_load_local_file(file, &dummy))
continue;
for (j = 0; j < n_missing; j++)
if (!strcmp(missing[j], file))
already = true;
if (already)
continue;
if (n_missing >= cap) {
cap = cap ? cap * 2 : 4;
missing = realloc(missing, cap * sizeof(*missing));
}
missing[n_missing++] = strdup(file);
}
if (n_missing == 0) {
free(missing);
render_backtrace_final(fd, p);
return;
}
pending_backtrace.active = true;
pending_backtrace.payload = json_object_get(p);
pending_backtrace.files = missing;
pending_backtrace.nfiles = n_missing;
pending_backtrace.next = 0;
request_backtrace_file(fd, missing[0]);
}
static void
render_source_range(int fd, struct json_object *p)
{
const char *file = jstr(p, "file", NULL);
struct json_object *cursor = json_object_object_get(p, "cursor");
int64_t from = jint(p, "from", 0);
int64_t to = jint(p, "to", 0);
debug_highlight_span_t hl;
if (!file) {
printf("(no source range)\n");
return;
}
if (cursor) {
hl.from_line = (size_t)jint(cursor, "from_line", 0);
hl.from_col = col0(jint(cursor, "from_col", 0));
hl.to_line = (size_t)jint(cursor, "to_line", 0);
hl.to_col = col0(jint(cursor, "to_col", 0));
/* The protocol only gives us the statement's *span*, not the
* exact current instruction position within it (which can differ
* for multi-part expressions) - approximate with the span start,
* which is exact for the common case of a simple statement. */
hl.have_ip = true;
hl.ip_line = hl.from_line;
hl.ip_col = hl.from_col;
render_source_lines(fd, file, from, to, &hl, 0);
}
else {
render_source_lines(fd, file, from, to, NULL, 0);
}
}
/* Fill in the raw byte array fields of a debug_disasm_insn_t (or a
* capture/unpack sub-entry) from a JSON array of small integers. `dst` must
* already point at storage for at least `cap` bytes; only the first
* min(array length, cap) entries are filled. */
static void
jbytes(struct json_object *arr, unsigned char *dst, size_t cap)
{
size_t n = arr ? json_object_array_length(arr) : 0;
if (n > cap)
n = cap;
for (size_t i = 0; i < n; i++)
dst[i] = (unsigned char)json_object_get_int64(json_object_array_get_idx(arr, i));
}
static void
render_disassembly(struct json_object *p)
{
struct json_object *insns_j = NULL;
debug_disasm_insn_t *insns;
size_t n;
json_object_object_get_ex(p, "instructions", &insns_j);
n = insns_j ? json_object_array_length(insns_j) : 0;
insns = calloc(n, sizeof(*insns));
for (size_t i = 0; i < n; i++) {
struct json_object *ins = json_object_array_get_idx(insns_j, i);
struct json_object *bytes_j = json_object_object_get(ins, "bytes");
struct json_object *constant_j = NULL;
struct json_object *captures_j = json_object_object_get(ins, "captures");
struct json_object *unpacks_j = json_object_object_get(ins, "unpacks");
debug_disasm_insn_t *d = &insns[i];
size_t nbytes = bytes_j ? json_object_array_length(bytes_j) : 0;
unsigned char *bytes = malloc(nbytes ? nbytes : 1);
jbytes(bytes_j, bytes, nbytes);
d->offset = (size_t)jint(ins, "offset", 0);
d->mnemonic = jstr(ins, "mnemonic", "?");
d->format = (int)jint(ins, "format", 0);
d->bytes = bytes;
d->nbytes = nbytes;
d->operand = jint(ins, "operand", 0);
if (json_object_object_get_ex(ins, "constant", &constant_j)) {
d->have_constant = true;
d->constant_repr = json_object_to_json_string(constant_j);
d->constant_is_string = (json_object_get_type(constant_j) == json_type_string);
}
if (json_object_object_get_ex(ins, "variable_kind", NULL)) {
d->variable_kind = jstr(ins, "variable_kind", NULL);
d->variable_name = jstr(ins, "variable_name", NULL);
}
if (json_object_object_get_ex(ins, "closure_index", NULL)) {
d->have_closure = true;
d->closure_kind = jstr(ins, "closure_kind", "closure");
d->closure_index = (uint32_t)jint(ins, "closure_index", 0);
}
if (json_object_object_get_ex(ins, "call_nargs", NULL)) {
struct json_object *mcall_j = json_object_object_get(ins, "call_mcall");
struct json_object *tail_j = json_object_object_get(ins, "call_tail");
struct json_object *stdlib_j = json_object_object_get(ins, "stdlib_name");
d->have_call = true;
d->call_mcall = mcall_j && json_object_get_boolean(mcall_j);
d->call_nargs = (uint32_t)jint(ins, "call_nargs", 0);
d->call_tail = tail_j && json_object_get_boolean(tail_j);
if (stdlib_j && json_object_get_type(stdlib_j) == json_type_string)
d->stdlib_name = json_object_get_string(stdlib_j);
}
if (json_object_object_get_ex(ins, "return_tailcall", NULL))
d->return_tailcall = true;
d->ncaptures = captures_j ? json_object_array_length(captures_j) : 0;
d->captures = calloc(d->ncaptures ? d->ncaptures : 1, sizeof(*d->captures));
for (size_t j = 0; j < d->ncaptures; j++) {
struct json_object *cap = json_object_array_get_idx(captures_j, j);
d->captures[j].slot = jint(cap, "slot", 0);
d->captures[j].upval = !strcmp(jstr(cap, "kind", ""), "upval");
d->captures[j].name = jstr(cap, "name", "(unknown)");
jbytes(json_object_object_get(cap, "bytes"), d->captures[j].bytes, 4);
}
d->nunpacks = unpacks_j ? json_object_array_length(unpacks_j) : 0;
d->unpacks = calloc(d->nunpacks ? d->nunpacks : 1, sizeof(*d->unpacks));
for (size_t j = 0; j < d->nunpacks; j++) {
struct json_object *u = json_object_array_get_idx(unpacks_j, j);
d->unpacks[j].slot = (uint16_t)jint(u, "slot", 0);
jbytes(json_object_object_get(u, "bytes"), d->unpacks[j].bytes, 2);
}
}
debug_highlight_print_disassembly(stdout, jstr(p, "function", "?"), insns, n, term_columns());
for (size_t i = 0; i < n; i++) {
free((void *)insns[i].bytes);
free(insns[i].captures);
free(insns[i].unpacks);
}
free(insns);
}
/* Async server events (see EVENT in lib/debug_proto.h) can land at any
* time, unprompted by anything the user typed - set in a faint italic
* style to visually set them apart from direct command responses. */
static void
render_event(struct json_object *p)
{
const char *event = jstr(p, "event", "?");