Skip to main content
summaryrefslogtreecommitdiffstats
blob: c76fd7d87455a398792894e9d8133d2c4de0aef5 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
/*******************************************************************************
 * Copyright (c) 2007, 2012 Wind River Systems, Inc. and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 * The Eclipse Public License is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 * http://www.eclipse.org/org/documents/edl-v10.php.
 * You may elect to redistribute this code under either of these licenses.
 *
 * Contributors:
 *     Wind River Systems - initial API and implementation
 *******************************************************************************/

/*
 * This module forwards handling of process/thread OS contexts to remote peer.
 */

#include <tcf/config.h>

#if ENABLE_DebugContext && ENABLE_ContextProxy

#include <errno.h>
#include <stdio.h>
#include <assert.h>
#include <sys/stat.h>
#include <tcf/framework/context.h>
#include <tcf/framework/myalloc.h>
#include <tcf/framework/trace.h>
#include <tcf/framework/exceptions.h>
#include <tcf/framework/protocol.h>
#include <tcf/framework/json.h>
#include <tcf/framework/cache.h>
#include <tcf/services/pathmap.h>
#include <tcf/services/memorymap.h>
#include <tcf/services/stacktrace.h>
#include <tcf/services/context-proxy.h>

typedef struct ContextCache ContextCache;
typedef struct MemoryCache MemoryCache;
typedef struct StackFrameCache StackFrameCache;
typedef struct PeerCache PeerCache;
typedef struct RegisterProps RegisterProps;

#define CTX_ID_HASH_SIZE 101

struct ContextCache {
    char id[256];
    char parent_id[256];
    char process_id[256];
    char creator_id[256];
    char * file;
    Context * ctx;
    PeerCache * peer;
    LINK id_hash_link;

    /* Memory Map */
    MemoryMap mmap;
    AbstractCache mmap_cache;
    ErrorReport * mmap_error;
    ReplyHandlerInfo * pending_get_mmap;
    int mmap_is_valid;
    int has_mmap;

    /* Register definitions */
    AbstractCache regs_cache;
    ErrorReport * reg_error;
    unsigned reg_max;
    unsigned reg_size;
    RegisterProps * reg_props;
    RegisterDefinition * reg_defs;
    RegisterDefinition * pc_def;
    int pending_regs_cnt;

    /* Run Control Properties */
    int has_state;
    int is_container;
    int can_suspend;
    long can_resume;
    long can_count;
    int can_terminate;

    /* Run Control State */
    int pc_valid;
    uint64_t suspend_pc;
    char * suspend_reason;
    char * signal_name;
    char ** bp_ids;

    /* Memory */
    LINK mem_cache_list;

    /* Stack trace */
    LINK stk_cache_list;
};

struct RegisterProps {
    RegisterDefinition def;
    char * id;
};

struct MemoryCache {
    LINK link_ctx;
    ContextCache * ctx;
    AbstractCache cache;
    ErrorReport * error;
    ContextAddress addr;
    void * buf;
    size_t size;
    ReplyHandlerInfo * pending;
    int disposed;
};

struct StackFrameCache {
    LINK link_ctx;
    ContextCache * ctx;
    AbstractCache cache;
    ErrorReport * error;
    int frame;
    ContextAddress ip;
    ContextAddress rp;
    StackFrame info;
    RegisterData reg_data;
    RegisterDefinition ** reg_defs;
    unsigned reg_cnt;
    ReplyHandlerInfo * pending;
    int disposed;
};

struct PeerCache {
    LINK link_all;
    LINK context_id_hash[CTX_ID_HASH_SIZE];
    Channel * host;
    Channel * target;
    ForwardingInputStream bck_buf;
    ForwardingInputStream fwd_buf;
    InputStream * bck_inp;
    InputStream * fwd_inp;

    /* Initial Run Control context tree retrieval */
    int rc_done;
    int rc_pending_cnt;
    ErrorReport * rc_error;
    AbstractCache rc_cache;
};

#define peers2peer(A)    ((PeerCache *)((char *)(A) - offsetof(PeerCache, link_all)))
#define ctx2mem(A)       ((MemoryCache *)((char *)(A) - offsetof(MemoryCache, link_ctx)))
#define ctx2stk(A)       ((StackFrameCache *)((char *)(A) - offsetof(StackFrameCache, link_ctx)))
#define idhashl2ctx(A)   ((ContextCache *)((char *)(A) - offsetof(ContextCache, id_hash_link)))

static LINK peers = TCF_LIST_INIT(peers);

static MemoryRegion * mem_buf = NULL;
static unsigned mem_buf_max = 0;
static unsigned mem_buf_pos = 0;

static unsigned * ids_buf = NULL;
static unsigned ids_buf_max = 0;
static unsigned ids_buf_pos = 0;

static char * str_buf = NULL;
static unsigned str_buf_max = 0;
static unsigned str_buf_pos = 0;

static size_t context_extension_offset = 0;

#define EXT(ctx) ((ContextCache **)((char *)(ctx) + context_extension_offset))

static const char RUN_CONTROL[] = "RunControl";
static const char MEMORY_MAP[] = "MemoryMap";
static const char PATH_MAP[] = "PathMap";

static unsigned hash_ctx_id(const char * id) {
    int i;
    unsigned h = 0;
    for (i = 0; id[i]; i++) h += id[i];
    return h % CTX_ID_HASH_SIZE;
}

static ContextCache * find_context_cache(PeerCache * p, const char * id) {
    LINK * h = p->context_id_hash + hash_ctx_id(id);
    LINK * l = h->next;
    while (l != h) {
        ContextCache * c = idhashl2ctx(l);
        if (strcmp(c->id, id) == 0) return c;
        l = l->next;
    }
    return NULL;
}

static void set_context_links(ContextCache * c) {
    assert(c->peer->rc_done);
    if (c->parent_id[0]) {
        ContextCache * h = find_context_cache(c->peer, c->parent_id);
        if (h != NULL) {
            (c->ctx->parent = h->ctx)->ref_count++;
            list_add_last(&c->ctx->cldl, &h->ctx->children);
        }
        else {
            trace(LOG_ALWAYS, "Invalid parent ID: %s", c->parent_id);
        }
    }
    if (c->process_id[0]) {
        ContextCache * h = find_context_cache(c->peer, c->process_id);
        if (h != NULL) {
            c->ctx->mem = h->ctx;
        }
        else {
            trace(LOG_ALWAYS, "Invalid process ID: %s", c->process_id);
        }
    }
    if (c->creator_id[0]) {
        ContextCache * h = find_context_cache(c->peer, c->creator_id);
        if (h != NULL) {
            (c->ctx->creator = h->ctx)->ref_count++;
        }
        else {
            trace(LOG_ALWAYS, "Invalid creator ID: %s", c->creator_id);
        }
    }
}

static void add_context_cache(PeerCache * p, ContextCache * c) {
    LINK * h = p->context_id_hash + hash_ctx_id(c->id);
    c->peer = p;
    c->ctx = create_context(c->id);
    c->ctx->ref_count = 1;
    *EXT(c->ctx) = c;
    list_init(&c->mem_cache_list);
    list_init(&c->stk_cache_list);
    list_add_first(&c->id_hash_link, h);
    list_add_first(&c->ctx->ctxl, &context_root);
    if (p->rc_done) set_context_links(c);
    send_context_created_event(c->ctx);
}

static void free_memory_cache(MemoryCache * m) {
    list_remove(&m->link_ctx);
    m->disposed = 1;
    if (m->pending == NULL) {
        release_error_report(m->error);
        cache_dispose(&m->cache);
        loc_free(m->buf);
        loc_free(m);
    }
}

static void free_stack_frame_cache(StackFrameCache * s) {
    list_remove(&s->link_ctx);
    s->disposed = 1;
    if (s->pending == NULL) {
        release_error_report(s->error);
        cache_dispose(&s->cache);
        loc_free(s->reg_data.data);
        loc_free(s->reg_data.mask);
        loc_free(s->reg_defs);
        loc_free(s);
    }
}

static void free_context_cache(ContextCache * c) {
    assert(c->pending_get_mmap == NULL);
    assert(c->pending_regs_cnt == 0);
    cache_dispose(&c->mmap_cache);
    cache_dispose(&c->regs_cache);
    release_error_report(c->mmap_error);
    release_error_report(c->reg_error);
    loc_free(c->file);
    context_clear_memory_map(&c->mmap);
    loc_free(c->mmap.regions);
    loc_free(c->reg_defs);
    loc_free(c->signal_name);
    loc_free(c->bp_ids);
    if (c->reg_props != NULL) {
        unsigned i;
        for (i = 0; i < c->reg_max; i++) {
            loc_free(c->reg_props[i].id);
            loc_free(c->reg_props[i].def.role);
        }
        loc_free(c->reg_props);
    }
    assert(list_is_empty(&c->id_hash_link));
    if (!list_is_empty(&c->mem_cache_list)) {
        LINK * l = c->mem_cache_list.next;
        while (l != &c->mem_cache_list) {
            MemoryCache * m = ctx2mem(c->mem_cache_list.next);
            l = l->next;
            free_memory_cache(m);
        }
    }
    if (!list_is_empty(&c->stk_cache_list)) {
        LINK * l = c->stk_cache_list.next;
        while (l != &c->stk_cache_list) {
            StackFrameCache * s = ctx2stk(c->stk_cache_list.next);
            l = l->next;
            free_stack_frame_cache(s);
        }
    }
    loc_free(c);
}

static void on_context_suspended(ContextCache * c) {
    LINK * l;

    if (c->peer->rc_done) {
        LINK * x = context_root.next;
        while (x != &context_root) {
            Context * ctx = ctxl2ctxp(x);
            if (ctx->mem == c->ctx->mem) {
                ContextCache * p = *EXT(ctx);
                l = p->mem_cache_list.next;
                while (l != &p->mem_cache_list) {
                    MemoryCache * m = ctx2mem(p->mem_cache_list.next);
                    l = l->next;
                    if (!m->pending) free_memory_cache(m);
                }
            }
            x = x->next;
        }
    }

    l = c->stk_cache_list.next;
    while (l != &c->stk_cache_list) {
        StackFrameCache * f = ctx2stk(c->stk_cache_list.next);
        l = l->next;
        free_stack_frame_cache(f);
    }
}

static void read_run_control_context_property(InputStream * inp, const char * name, void * args) {
    ContextCache * ctx = (ContextCache *)args;
    if (strcmp(name, "ID") == 0) json_read_string(inp, ctx->id, sizeof(ctx->id));
    else if (strcmp(name, "ParentID") == 0) json_read_string(inp, ctx->parent_id, sizeof(ctx->parent_id));
    else if (strcmp(name, "ProcessID") == 0) json_read_string(inp, ctx->process_id, sizeof(ctx->process_id));
    else if (strcmp(name, "CreatorID") == 0) json_read_string(inp, ctx->creator_id, sizeof(ctx->creator_id));
    else if (strcmp(name, "File") == 0) ctx->file = json_read_alloc_string(inp);
    else if (strcmp(name, "HasState") == 0) ctx->has_state = json_read_boolean(inp);
    else if (strcmp(name, "IsContainer") == 0) ctx->is_container = json_read_boolean(inp);
    else if (strcmp(name, "CanSuspend") == 0) ctx->can_suspend = json_read_boolean(inp);
    else if (strcmp(name, "CanResume") == 0) ctx->can_resume = json_read_long(inp);
    else if (strcmp(name, "CanCount") == 0) ctx->can_count = json_read_long(inp);
    else if (strcmp(name, "CanTerminate") == 0) ctx->can_terminate = json_read_boolean(inp);
    else json_skip_object(inp);
}

static void read_context_suspended_data(InputStream * inp, const char * name, void * args) {
    ContextCache * ctx = (ContextCache *)args;
    if (strcmp(name, "Signal") == 0 && ctx->ctx != NULL) ctx->ctx->signal = json_read_long(inp);
    else if (strcmp(name, "SignalName") == 0) ctx->signal_name = json_read_alloc_string(inp);
    else if (strcmp(name, "BPs") == 0) ctx->bp_ids = json_read_alloc_string_array(inp, NULL);
    else json_skip_object(inp);
}

static void clear_context_suspended_data(ContextCache * ctx) {
    loc_free(ctx->suspend_reason);
    loc_free(ctx->signal_name);
    loc_free(ctx->bp_ids);
    if (ctx->ctx != NULL) ctx->ctx->signal = 0;
    ctx->pc_valid = 0;
    ctx->suspend_pc = 0;
    ctx->suspend_reason = NULL;
    ctx->signal_name = NULL;
    ctx->bp_ids = NULL;
}

static void crear_memory_map_data(ContextCache * ctx) {
    context_clear_memory_map(&ctx->mmap);
    release_error_report(ctx->mmap_error);
    ctx->mmap_is_valid = 0;
    ctx->mmap_error = NULL;
    if (ctx->has_mmap) {
        memory_map_event_mapping_changed(ctx->ctx);
        ctx->has_mmap = 0;
    }
}

static void read_context_added_item(InputStream * inp, void * args) {
    PeerCache * p = (PeerCache *)args;
    ContextCache * c = (ContextCache *)loc_alloc_zero(sizeof(ContextCache));

    json_read_struct(inp, read_run_control_context_property, c);

    if (find_context_cache(p, c->id) == NULL &&
        (c->parent_id[0] == 0 || find_context_cache(p, c->parent_id) != NULL)) {
        add_context_cache(p, c);
    }
    else {
        if (p->rc_done) trace(LOG_ALWAYS, "Invalid ID in 'context added' event: %s", c->id);
        free_context_cache(c);
    }
}

static void read_context_changed_item(InputStream * inp, void * args) {
    PeerCache * p = (PeerCache *)args;
    ContextCache * c = NULL;
    ContextCache buf;
    memset(&buf, 0, sizeof(buf));
    json_read_struct(inp, read_run_control_context_property, &buf);
    c = find_context_cache(p, buf.id);
    if (c != NULL) {
        strcpy(c->parent_id, buf.parent_id);
        c->has_state = buf.has_state;
        c->is_container = buf.is_container;
        c->can_suspend = buf.can_suspend;
        c->can_resume = buf.can_resume;
        c->can_count = buf.can_count;
        c->can_terminate = buf.can_terminate;
        send_context_changed_event(c->ctx);
    }
    else if (p->rc_done) {
        trace(LOG_ALWAYS, "Invalid ID in 'context changed' event: %s", buf.id);
    }
}

static void read_context_removed_item(InputStream * inp, void * args) {
    PeerCache * p = (PeerCache *)args;
    ContextCache * c = NULL;
    char id[256];
    json_read_string(inp, id, sizeof(id));
    c = find_context_cache(p, id);
    if (c != NULL) {
        assert(*EXT(c->ctx) == c);
        send_context_exited_event(c->ctx);
    }
    else if (p->rc_done) {
        trace(LOG_ALWAYS, "Invalid ID in 'context removed' event: %s", id);
    }
}

static void read_container_suspended_item(InputStream * inp, void * args) {
    PeerCache * p = (PeerCache *)args;
    ContextCache * c = NULL;
    char id[256];
    json_read_string(inp, id, sizeof(id));
    c = find_context_cache(p, id);
    if (c != NULL) {
        assert(*EXT(c->ctx) == c);
        if (!c->ctx->stopped) {
            c->ctx->stopped = 1;
            on_context_suspended(c);
            send_context_stopped_event(c->ctx);
        }
    }
    else if (p->rc_done) {
        trace(LOG_ALWAYS, "Invalid ID in 'container suspended' event: %s", id);
    }
}

static void read_container_resumed_item(InputStream * inp, void * args) {
    PeerCache * p = (PeerCache *)args;
    ContextCache * c = NULL;
    char id[256];
    json_read_string(inp, id, sizeof(id));
    c = find_context_cache(p, id);
    if (c != NULL) {
        assert(*EXT(c->ctx) == c);
        if (c->ctx->stopped) {
            c->ctx->stopped = 0;
            clear_context_suspended_data(c);
            send_context_started_event(c->ctx);
        }
    }
    else if (p->rc_done) {
        trace(LOG_ALWAYS, "Invalid ID in 'container resumed' event: %s", id);
    }
}

static void event_context_added(Channel * c, void * args) {
    PeerCache * p = (PeerCache *)args;
    write_stringz(&p->host->out, "E");
    write_stringz(&p->host->out, RUN_CONTROL);
    write_stringz(&p->host->out, "contextAdded");
    json_read_array(p->bck_inp, read_context_added_item, p);
    if (read_stream(p->bck_inp) != 0) exception(ERR_JSON_SYNTAX);
    if (read_stream(p->bck_inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);
}

static void event_context_changed(Channel * c, void * args) {
    PeerCache * p = (PeerCache *)args;
    write_stringz(&p->host->out, "E");
    write_stringz(&p->host->out, RUN_CONTROL);
    write_stringz(&p->host->out, "contextChanged");
    json_read_array(p->bck_inp, read_context_changed_item, p);
    if (read_stream(p->bck_inp) != 0) exception(ERR_JSON_SYNTAX);
    if (read_stream(p->bck_inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);
}

static void event_context_removed(Channel * c, void * args) {
    PeerCache * p = (PeerCache *)args;
    write_stringz(&p->host->out, "E");
    write_stringz(&p->host->out, RUN_CONTROL);
    write_stringz(&p->host->out, "contextRemoved");
    json_read_array(p->bck_inp, read_context_removed_item, p);
    if (read_stream(p->bck_inp) != 0) exception(ERR_JSON_SYNTAX);
    if (read_stream(p->bck_inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);
}

static void event_context_suspended(Channel * ch, void * args) {
    PeerCache * p = (PeerCache *)args;
    ContextCache buf;
    ContextCache * c = &buf;

    assert(p->target == ch);
    memset(&buf, 0, sizeof(buf));
    write_stringz(&p->host->out, "E");
    write_stringz(&p->host->out, RUN_CONTROL);
    write_stringz(&p->host->out, "contextSuspended");
    json_read_string(p->bck_inp, c->id, sizeof(c->id));
    if (read_stream(p->bck_inp) != 0) exception(ERR_JSON_SYNTAX);
    c = find_context_cache(p, c->id);
    if (c == NULL) c = &buf;
    else clear_context_suspended_data(c);
    c->suspend_pc = json_read_uint64(p->bck_inp);
    if (read_stream(p->bck_inp) != 0) exception(ERR_JSON_SYNTAX);
    c->suspend_reason = json_read_alloc_string(p->bck_inp);
    if (read_stream(p->bck_inp) != 0) exception(ERR_JSON_SYNTAX);
    json_read_struct(p->bck_inp, read_context_suspended_data, c);
    if (read_stream(p->bck_inp) != 0) exception(ERR_JSON_SYNTAX);
    if (read_stream(p->bck_inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);

    if (c != &buf) {
        assert(*EXT(c->ctx) == c);
        c->pc_valid = 1;
        if (!c->ctx->stopped) {
            c->ctx->stopped = 1;
            on_context_suspended(c);
            send_context_stopped_event(c->ctx);
        }
    }
    else {
        if (p->rc_done) trace(LOG_ALWAYS, "Invalid ID in 'context suspended' event: %s", c->id);
        clear_context_suspended_data(c);
    }
}

static void event_context_resumed(Channel * ch, void * args) {
    PeerCache * p = (PeerCache *)args;
    ContextCache * c = NULL;
    char id[256];

    assert(p->target == ch);
    write_stringz(&p->host->out, "E");
    write_stringz(&p->host->out, RUN_CONTROL);
    write_stringz(&p->host->out, "contextResumed");
    json_read_string(p->bck_inp, id, sizeof(id));
    if (read_stream(p->bck_inp) != 0) exception(ERR_JSON_SYNTAX);
    if (read_stream(p->bck_inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);

    c = find_context_cache(p, id);
    if (c != NULL) {
        assert(*EXT(c->ctx) == c);
        if (c->ctx->stopped) {
            c->ctx->stopped = 0;
            clear_context_suspended_data(c);
            send_context_started_event(c->ctx);
        }
    }
    else if (p->rc_done) {
        trace(LOG_ALWAYS, "Invalid ID in 'context resumed' event: %s", id);
    }
}

static void event_container_suspended(Channel * ch, void * args) {
    PeerCache * p = (PeerCache *)args;
    ContextCache buf;
    ContextCache * c = &buf;

    assert(p->target == ch);
    memset(&buf, 0, sizeof(buf));
    write_stringz(&p->host->out, "E");
    write_stringz(&p->host->out, RUN_CONTROL);
    write_stringz(&p->host->out, "containerSuspended");
    json_read_string(p->bck_inp, c->id, sizeof(c->id));
    if (read_stream(p->bck_inp) != 0) exception(ERR_JSON_SYNTAX);
    c = find_context_cache(p, c->id);
    if (c == NULL) c = &buf;
    else clear_context_suspended_data(c);
    c->suspend_pc = json_read_uint64(p->bck_inp);
    if (read_stream(p->bck_inp) != 0) exception(ERR_JSON_SYNTAX);
    c->suspend_reason = json_read_alloc_string(p->bck_inp);
    if (read_stream(p->bck_inp) != 0) exception(ERR_JSON_SYNTAX);
    json_read_struct(p->bck_inp, read_context_suspended_data, c);
    if (read_stream(p->bck_inp) != 0) exception(ERR_JSON_SYNTAX);
    if (c != &buf) {
        assert(*EXT(c->ctx) == c);
        c->pc_valid = 1;
        if (!c->ctx->stopped) {
            c->ctx->stopped = 1;
            on_context_suspended(c);
            send_context_stopped_event(c->ctx);
        }
    }
    else {
        if (p->rc_done) trace(LOG_ALWAYS, "Invalid ID in 'container suspended' event: %s", c->id);
        clear_context_suspended_data(c);
    }
    json_read_array(p->bck_inp, read_container_suspended_item, p);
    if (read_stream(p->bck_inp) != 0) exception(ERR_JSON_SYNTAX);
    if (read_stream(p->bck_inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);
}

static void event_container_resumed(Channel * c, void * args) {
    PeerCache * p = (PeerCache *)args;
    write_stringz(&p->host->out, "E");
    write_stringz(&p->host->out, RUN_CONTROL);
    write_stringz(&p->host->out, "containerResumed");
    json_read_array(p->bck_inp, read_container_resumed_item, p);
    if (read_stream(p->bck_inp) != 0) exception(ERR_JSON_SYNTAX);
    if (read_stream(p->bck_inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);
}

static void event_memory_map_changed(Channel * c, void * args) {
    char id[256];
    PeerCache * p = (PeerCache *)args;
    ContextCache * ctx = NULL;

    write_stringz(&p->host->out, "E");
    write_stringz(&p->host->out, MEMORY_MAP);
    write_stringz(&p->host->out, "changed");
    json_read_string(p->bck_inp, id, sizeof(id));
    if (read_stream(p->bck_inp) != 0) exception(ERR_JSON_SYNTAX);
    if (read_stream(p->bck_inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);

    ctx = find_context_cache(p, id);
    if (ctx != NULL) {
        assert(*EXT(ctx->ctx) == ctx);
        crear_memory_map_data(ctx);
    }
    else if (p->rc_done) {
        trace(LOG_ALWAYS, "Invalid ID in 'memory map changed' event: %s", id);
    }
}

static void command_path_map_set(char * token, Channel * c, void * args) {
    PeerCache * p = (PeerCache *)args;
    write_stringz(&p->target->out, "C");
    write_stream(&p->target->out, 'R');
    write_stringz(&p->target->out, token);
    write_stringz(&p->target->out, PATH_MAP);
    write_stringz(&p->target->out, "set");
    set_path_map(p->host, p->fwd_inp);
    if (read_stream(p->fwd_inp) != 0) exception(ERR_JSON_SYNTAX);
    if (read_stream(p->fwd_inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);
}

static void validate_peer_cache_children(Channel * c, void * args, int error);

void create_context_proxy(Channel * host, Channel * target, int forward_pm) {
    int i;
    LINK * l;
    PeerCache * p;
    for (l = peers.next; l != &peers; l = l->next) {
        p = peers2peer(l);
        if (p->target == target) return;
    }
    p = (PeerCache *)loc_alloc_zero(sizeof(PeerCache));
    p->host = host;
    p->target = target;
    p->bck_inp = create_forwarding_input_stream(&p->bck_buf, &target->inp, &host->out);
    p->fwd_inp = create_forwarding_input_stream(&p->fwd_buf, &host->inp, &target->out);
    for (i = 0; i < CTX_ID_HASH_SIZE; i++) list_init(p->context_id_hash + i);
    list_add_first(&p->link_all, &peers);
    channel_lock(host);
    channel_lock(target);
    add_event_handler2(target, RUN_CONTROL, "contextAdded", event_context_added, p);
    add_event_handler2(target, RUN_CONTROL, "contextChanged", event_context_changed, p);
    add_event_handler2(target, RUN_CONTROL, "contextRemoved", event_context_removed, p);
    add_event_handler2(target, RUN_CONTROL, "contextSuspended", event_context_suspended, p);
    add_event_handler2(target, RUN_CONTROL, "contextResumed", event_context_resumed, p);
    add_event_handler2(target, RUN_CONTROL, "containerSuspended", event_container_suspended, p);
    add_event_handler2(target, RUN_CONTROL, "containerResumed", event_container_resumed, p);
    add_event_handler2(target, MEMORY_MAP, "changed", event_memory_map_changed, p);
    if (forward_pm) add_command_handler2(host->protocol, PATH_MAP, "set", command_path_map_set, p);
    /* Retirve initial set of run control contexts */
    protocol_send_command(p->target, RUN_CONTROL, "getChildren", validate_peer_cache_children, p);
    write_stringz(&p->target->out, "null");
    write_stream(&p->target->out, MARKER_EOM);
    p->rc_pending_cnt++;
}

static void validate_peer_cache_context(Channel * c, void * args, int error);
static void validate_peer_cache_state(Channel * c, void * args, int error);

static void read_rc_children_item(InputStream * inp, void * args) {
    char id[256];
    PeerCache * p = (PeerCache *)args;

    json_read_string(inp, id, sizeof(id));

    if (find_context_cache(p, id) == NULL) {
        ContextCache * c = (ContextCache *)loc_alloc_zero(sizeof(ContextCache));
        strcpy(c->id, id);
        c->peer = p;
        protocol_send_command(p->target, RUN_CONTROL, "getContext", validate_peer_cache_context, c);
        json_write_string(&p->target->out, c->id);
        write_stream(&p->target->out, 0);
        write_stream(&p->target->out, MARKER_EOM);
        p->rc_pending_cnt++;
    }
}

static void set_rc_done(PeerCache * p) {
    if (p->rc_pending_cnt == 0) {
        int i;
        LINK * l;
        p->rc_done = 1;
        for (i = 0; i < CTX_ID_HASH_SIZE; i++) {
            LINK * h = p->context_id_hash + i;
            for (l = h->next; l != h; l = l->next) {
                set_context_links(idhashl2ctx(l));
            }
        }
        cache_notify(&p->rc_cache);
    }
}

static void set_rc_error(PeerCache * p, int error) {
    if (error == 0) return;
    if (get_error_code(error) == ERR_INV_CONTEXT) return;
    if (get_error_code(error) == ERR_ALREADY_EXITED) return;
    if (p->rc_error != NULL) return;
    p->rc_error = get_error_report(error);
}

static void validate_peer_cache_children(Channel * c, void * args, int error) {
    PeerCache * p = (PeerCache *)args;
    Trap trap;

    assert(p->target == c);
    assert(p->rc_pending_cnt > 0);
    if (set_trap(&trap)) {
        p->rc_pending_cnt--;
        if (!error) {
            error = read_errno(&c->inp);
            json_read_array(&c->inp, read_rc_children_item, p);
            if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX);
            if (read_stream(&c->inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);
        }
        clear_trap(&trap);
    }
    else {
        error = trap.error;
    }
    set_rc_error(p, error);
    set_rc_done(p);
}

static void validate_peer_cache_context(Channel * c, void * args, int error) {
    ContextCache * x = (ContextCache *)args;
    PeerCache * p = x->peer;
    Trap trap;

    assert(p->target == c);
    assert(p->rc_pending_cnt > 0);
    if (set_trap(&trap)) {
        p->rc_pending_cnt--;
        if (error) {
            set_rc_error(p, error);
            free_context_cache(x);
        }
        else {
            set_rc_error(p, error = read_errno(&c->inp));
            json_read_struct(&c->inp, read_run_control_context_property, x);
            if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX);
            if (read_stream(&c->inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);
            if (error || find_context_cache(p, x->id) != NULL) {
                free_context_cache(x);
            }
            else if (x->has_state) {
                protocol_send_command(p->target, RUN_CONTROL, "getState", validate_peer_cache_state, x);
                json_write_string(&p->target->out, x->id);
                write_stream(&p->target->out, 0);
                write_stream(&p->target->out, MARKER_EOM);
                p->rc_pending_cnt++;
            }
            else {
                add_context_cache(p, x);
                protocol_send_command(p->target, RUN_CONTROL, "getChildren", validate_peer_cache_children, p);
                json_write_string(&p->target->out, x->id);
                write_stream(&p->target->out, 0);
                write_stream(&p->target->out, MARKER_EOM);
                p->rc_pending_cnt++;
            }
        }
        clear_trap(&trap);
    }
    else {
        set_rc_error(p, trap.error);
        free_context_cache(x);
    }
    set_rc_done(p);
}

static void validate_peer_cache_state(Channel * c, void * args, int error) {
    ContextCache * x = (ContextCache *)args;
    PeerCache * p = x->peer;
    Trap trap;

    assert(p->target == c);
    assert(p->rc_pending_cnt > 0);
    if (set_trap(&trap)) {
        p->rc_pending_cnt--;
        if (error) {
            set_rc_error(p, error);
            free_context_cache(x);
        }
        else {
            set_rc_error(p, error = read_errno(&c->inp));
            clear_context_suspended_data(x);
            x->pc_valid = json_read_boolean(&c->inp);
            if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX);
            x->suspend_pc = json_read_uint64(&c->inp);
            if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX);
            x->suspend_reason = json_read_alloc_string(&c->inp);
            if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX);
            json_read_struct(&c->inp, read_context_suspended_data, x);
            if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX);
            if (read_stream(&c->inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);

            if (error || find_context_cache(p, x->id) != NULL) {
                free_context_cache(x);
            }
            else {
                add_context_cache(p, x);
                x->ctx->stopped = x->pc_valid;
                if (x->pc_valid) {
                    on_context_suspended(x);
                    send_context_stopped_event(x->ctx);
                }
                protocol_send_command(p->target, RUN_CONTROL, "getChildren", validate_peer_cache_children, p);
                json_write_string(&p->target->out, x->id);
                write_stream(&p->target->out, 0);
                write_stream(&p->target->out, MARKER_EOM);
                p->rc_pending_cnt++;
            }
        }
        clear_trap(&trap);
    }
    else {
        set_rc_error(p, trap.error);
        free_context_cache(x);
    }
    set_rc_done(p);
}

Context * id2ctx(const char * id) {
    LINK * l;
    Channel * c = cache_channel();
    assert(c != NULL);
    for (l = peers.next; l != &peers; l = l->next) {
        PeerCache * p = peers2peer(l);
        if (p->host == c || p->target == c) {
            if (p->rc_pending_cnt > 0) {
                cache_wait(&p->rc_cache);
            }
            else if (p->rc_error != NULL) {
                set_error_report_errno(p->rc_error);
            }
            else if (!p->rc_done) {
                cache_wait(&p->rc_cache);
            }
            else {
                ContextCache * h = find_context_cache(p, id);
                return h ? h->ctx : NULL;
            }
        }
    }
    return NULL;
}

int context_has_state(Context * ctx) {
    return (*EXT(ctx))->has_state;
}

Context * context_get_group(Context * ctx, int group) {
    switch (group) {
    case CONTEXT_GROUP_INTERCEPT:
        return ctx;
    }
    return ctx->mem;
}

static void validate_memory_cache(Channel * c, void * args, int error) {
    MemoryCache * m = (MemoryCache *)args;
    Context * ctx = m->ctx->ctx;
    Trap trap;

    assert(m->pending != NULL);
    assert(m->error == NULL);
    if (set_trap(&trap)) {
        m->pending = NULL;
        if (!error) {
            size_t pos = 0;
            JsonReadBinaryState state;
            json_read_binary_start(&state, &c->inp);
            for (;;) {
                int rd = json_read_binary_data(&state, (int8_t *)m->buf + pos, m->size - pos);
                if (rd == 0) break;
                pos += rd;
            }
            json_read_binary_end(&state);
            if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX);
            error = read_errno(&c->inp);
            while (read_stream(&c->inp) != 0) {}
            if (read_stream(&c->inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);
        }
        clear_trap(&trap);
    }
    else {
        error = trap.error;
    }
    m->error = get_error_report(error);
    cache_notify(&m->cache);
    if (m->disposed) free_memory_cache(m);
    context_unlock(ctx);
}

int context_write_mem(Context * ctx, ContextAddress address, void * buf, size_t size) {
    errno = EINVAL;
    return -1;
}

int context_read_mem(Context * ctx, ContextAddress address, void * buf, size_t size) {
    ContextCache * cache = *EXT(ctx);
    MemoryCache * m = NULL;
    Channel * c = NULL;
    LINK * l = NULL;
    Trap trap;

    if (!set_trap(&trap)) return -1;
    if (!cache->peer->rc_done) cache_wait(&cache->peer->rc_cache);

    for (l = cache->mem_cache_list.next; l != &cache->mem_cache_list; l = l->next) {
        m = ctx2mem(l);
        if (address >= m->addr && address + size <= m->addr + m->size) {
            if (m->pending != NULL) cache_wait(&m->cache);
            memcpy(buf, (int8_t *)m->buf + (address - m->addr), size);
            set_error_report_errno(m->error);
            clear_trap(&trap);
            return !errno ? 0 : -1;
        }
    }

    c = cache->peer->target;
    m = (MemoryCache *)loc_alloc_zero(sizeof(MemoryCache));
    list_add_first(&m->link_ctx, &cache->mem_cache_list);
    m->ctx = cache;
    m->addr = address;
    m->buf = loc_alloc(size);
    m->size = size;
    m->pending = protocol_send_command(c, "Memory", "get", validate_memory_cache, m);
    json_write_string(&c->out, cache->ctx->id);
    write_stream(&c->out, 0);
    json_write_int64(&c->out, m->addr);
    write_stream(&c->out, 0);
    json_write_long(&c->out, 1);
    write_stream(&c->out, 0);
    json_write_long(&c->out, m->size);
    write_stream(&c->out, 0);
    json_write_long(&c->out, 0);
    write_stream(&c->out, 0);
    write_stream(&c->out, MARKER_EOM);
    context_lock(ctx);
    cache_wait(&m->cache);
    return -1;
}

int context_write_reg(Context * ctx, RegisterDefinition * def, unsigned offs, unsigned size, void * buf) {
    errno = EINVAL;
    return -1;
}

int context_read_reg(Context * ctx, RegisterDefinition * def, unsigned offs, unsigned size, void * buf) {
    errno = EINVAL;
    return -1;
}

static void read_memory_region_property(InputStream * inp, const char * name, void * args) {
    MemoryRegion * m = (MemoryRegion *)args;
    if (strcmp(name, "Addr") == 0) m->addr = (ContextAddress)json_read_uint64(inp);
    else if (strcmp(name, "Size") == 0) m->size = json_read_ulong(inp);
    else if (strcmp(name, "Offs") == 0) m->file_offs = json_read_ulong(inp);
    else if (strcmp(name, "BSS") == 0) m->bss = json_read_boolean(inp);
    else if (strcmp(name, "Flags") == 0) m->flags = json_read_ulong(inp);
    else if (strcmp(name, "FileName") == 0) m->file_name = json_read_alloc_string(inp);
    else if (strcmp(name, "SectionName") == 0) m->sect_name = json_read_alloc_string(inp);
    else if (strcmp(name, "ContextQuery") == 0) m->query = json_read_alloc_string(inp);
    else if (strcmp(name, "ID") == 0) m->id = json_read_alloc_string(inp);
    else {
        MemoryRegionAttribute * x = (MemoryRegionAttribute *)loc_alloc(sizeof(MemoryRegionAttribute));
        x->name = loc_strdup(name);
        x->value = json_read_object(inp);
        x->next = m->attrs;
        m->attrs = x;
    }
}

static void read_memory_map_item(InputStream * inp, void * args) {
    ContextCache * cache = (ContextCache *)args;
    MemoryRegion * m;
    if (mem_buf_pos >= mem_buf_max) {
        mem_buf_max = mem_buf_max == 0 ? 16 : mem_buf_max * 2;
        mem_buf = (MemoryRegion *)loc_realloc(mem_buf, sizeof(MemoryRegion) * mem_buf_max);
    }
    m = mem_buf + mem_buf_pos;
    memset(m, 0, sizeof(MemoryRegion));
    if (json_read_struct(inp, read_memory_region_property, m) &&
            m->file_name != NULL && m->file_name[0] != 0) {
        struct stat buf;
        char * fnm = apply_path_map(cache->peer->host, cache->ctx, m->file_name, PATH_MAP_TO_LOCAL);
        if (fnm != m->file_name) {
            loc_free(m->file_name);
            m->file_name = loc_strdup(canonic_path_map_file_name(fnm));
        }
        if (m->file_name != NULL && stat(m->file_name, &buf) == 0) {
            m->dev = buf.st_dev;
            m->ino = buf.st_ino;
            mem_buf_pos++;
        }
        else if (m->file_name != NULL) {
            mem_buf_pos++;
        }
    }
}

static void validate_memory_map_cache(Channel * c, void * args, int error) {
    ContextCache * cache = (ContextCache *)args;
    Trap trap;

    assert(cache->mmap_is_valid == 0);
    assert(cache->pending_get_mmap != NULL);
    if (set_trap(&trap)) {
        cache->pending_get_mmap = NULL;
        if (!error) {
            error = read_errno(&c->inp);
            mem_buf_pos = 0;
            json_read_array(&c->inp, read_memory_map_item, cache);
            cache->mmap.region_cnt = mem_buf_pos;
            cache->mmap.region_max = mem_buf_pos;
            cache->mmap.regions = (MemoryRegion *)loc_alloc(sizeof(MemoryRegion) * mem_buf_pos);
            memcpy(cache->mmap.regions, mem_buf, sizeof(MemoryRegion) * mem_buf_pos);

            if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX);
            if (read_stream(&c->inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);
        }
        clear_trap(&trap);
    }
    else {
        error = trap.error;
    }
    cache->mmap_is_valid = 1;
    cache->mmap_error = get_error_report(error);
    cache_notify(&cache->mmap_cache);
    context_unlock(cache->ctx);
}

int context_get_memory_map(Context * ctx, MemoryMap * map) {
    ContextCache * cache = *EXT(ctx);
    Trap trap;

    if (!set_trap(&trap)) return -1;
    if (cache->peer != NULL && !cache->peer->rc_done) cache_wait(&cache->peer->rc_cache);

    cache = *EXT(ctx);
    assert(cache->ctx == ctx);
    if (cache->pending_get_mmap != NULL) cache_wait(&cache->mmap_cache);
    if (cache->mmap_is_valid == 0 && cache->peer != NULL) {
        Channel * c = cache->peer->target;
        cache->pending_get_mmap = protocol_send_command(c, MEMORY_MAP, "get", validate_memory_map_cache, cache);
        json_write_string(&c->out, cache->id);
        write_stream(&c->out, 0);
        write_stream(&c->out, MARKER_EOM);
        context_lock(ctx);
        cache_wait(&cache->mmap_cache);
    }
    if (map->region_max < cache->mmap.region_cnt) {
        map->region_max = cache->mmap.region_cnt;
        map->regions = (MemoryRegion *)loc_realloc(map->regions, sizeof(MemoryRegion) * map->region_max);
    }
    map->region_cnt = cache->mmap.region_cnt;
    if (map->region_cnt > 0) {
        memcpy(map->regions, cache->mmap.regions, sizeof(MemoryRegion) * map->region_cnt);
        memset(cache->mmap.regions, 0, sizeof(MemoryRegion) * map->region_cnt);
        cache->mmap.region_cnt = 0;
        cache->mmap_is_valid = 0;
    }
    clear_trap(&trap);
    if (cache->mmap_error != NULL) {
        set_error_report_errno(cache->mmap_error);
        return -1;
    }
    cache->has_mmap = 1;
    return 0;
}

static void read_ids_item(InputStream * inp, void * args) {
    int n;
    char id[256];
    if (ids_buf_pos >= ids_buf_max) {
        ids_buf_max = ids_buf_max == 0 ? 16 : ids_buf_max * 2;
        ids_buf = (unsigned *)loc_realloc(ids_buf, sizeof(unsigned) * ids_buf_max);
    }
    n = json_read_string(inp, id, sizeof(id));
    if (n <= 0) return;
    n++;
    if (n > (int)sizeof(id)) n = sizeof(id);
    if (str_buf_pos + n > str_buf_max) {
        str_buf_max = str_buf_max == 0 ? sizeof(id) : str_buf_max * 2;
        str_buf = (char *)loc_realloc(str_buf, str_buf_max);
    }
    memcpy(str_buf + str_buf_pos, id, n);
    ids_buf[ids_buf_pos++] = str_buf_pos;
    str_buf_pos += n;
}

static void read_register_property(InputStream * inp, const char * name, void * args) {
    RegisterProps * p = (RegisterProps *)args;
    if (strcmp(name, "ID") == 0) p->id = json_read_alloc_string(inp);
    else if (strcmp(name, "Role") == 0) p->def.role = json_read_alloc_string(inp);
    else if (strcmp(name, "Name") == 0) p->def.name = json_read_alloc_string(inp);
    else if (strcmp(name, "Size") == 0) p->def.size = (uint16_t)json_read_long(inp);
    else if (strcmp(name, "DwarfID") == 0) p->def.dwarf_id = (int16_t)json_read_long(inp);
    else if (strcmp(name, "EhFrameID") == 0) p->def.eh_frame_id = (int16_t)json_read_long(inp);
    else if (strcmp(name, "BigEndian") == 0) p->def.big_endian = (uint8_t)json_read_boolean(inp);
    else json_skip_object(inp);
}

static unsigned get_reg_index(ContextCache * cache, const char * id) {
    unsigned r = 0;
    while (*id++ == 'R') {
        for (;;) {
            if (*id == '.' || *id == '@') {
                return r;
            }
            else if (*id >= '0' && *id <= '9') {
                r = r * 10 + (*id++ - '0');
            }
            else {
                break;
            }
        }
    }
    str_exception(ERR_OTHER, "Invalid register ID");
    return 0;
}

static void validate_registers_cache(Channel * c, void * args, int error) {
    ContextCache * cache = (ContextCache *)args;
    Trap trap;

    assert(cache->pending_regs_cnt > 0);
    cache->pending_regs_cnt--;

    if (error) {
        if (cache->reg_error == NULL) cache->reg_error = get_error_report(error);
    }
    else if (cache->reg_error != NULL) {
        int i = 0;
        do i = read_stream(&c->inp);
        while (i != MARKER_EOM && i != MARKER_EOS);
    }
    else {
        if (set_trap(&trap)) {
            error = read_errno(&c->inp);
            if (!error && peek_stream(&c->inp) == '[') {
                /* Registers.getChildren reply */
                unsigned i;
                ids_buf_pos = 0;
                str_buf_pos = 0;
                json_read_array(&c->inp, read_ids_item, NULL);
                if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX);
                if (read_stream(&c->inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);
                for (i = 0; i < ids_buf_pos; i++) {
                    cache->pending_regs_cnt++;
                    protocol_send_command(c, "Registers", "getContext", validate_registers_cache, cache);
                    json_write_string(&c->out, str_buf + ids_buf[i]);
                    write_stream(&c->out, 0);
                    write_stream(&c->out, MARKER_EOM);
                    context_lock(cache->ctx);
                }
            }
            else if (!error && peek_stream(&c->inp) == '{') {
                /* Registers.getContext reply */
                unsigned i;
                RegisterProps props;
                memset(&props, 0, sizeof(props));
                props.def.dwarf_id = -1;
                props.def.eh_frame_id = -1;
                json_read_struct(&c->inp, read_register_property, &props);
                if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX);
                if (read_stream(&c->inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);
                i = get_reg_index(cache, props.id);
                if (i >= cache->reg_max) {
                    unsigned pos = cache->reg_max;
                    cache->reg_max += 256;
                    if (i >= cache->reg_max) cache->reg_max = i + 2;
                    cache->reg_props = (RegisterProps *)loc_realloc(cache->reg_props, cache->reg_max * sizeof(RegisterProps));
                    cache->reg_defs = (RegisterDefinition *)loc_realloc(cache->reg_defs, cache->reg_max * sizeof(RegisterDefinition));
                    memset(cache->reg_props + pos, 0, (cache->reg_max - pos) * sizeof(RegisterProps));
                    memset(cache->reg_defs + pos, 0, (cache->reg_max - pos) * sizeof(RegisterDefinition));
                }
                cache->reg_props[i] = props;
                cache->reg_defs[i] = props.def;
                cache->pending_regs_cnt++;
                protocol_send_command(c, "Registers", "getChildren", validate_registers_cache, cache);
                json_write_string(&c->out, props.id);
                write_stream(&c->out, 0);
                write_stream(&c->out, MARKER_EOM);
                context_lock(cache->ctx);
            }
            else {
                int i = 0;
                do i = read_stream(&c->inp);
                while (i != MARKER_EOM && i != MARKER_EOS);
            }
            clear_trap(&trap);
        }
        else {
            error = trap.error;
        }
        cache->reg_error = get_error_report(error);
    }
    if (cache->pending_regs_cnt == 0) {
        unsigned i;
        unsigned offs = 0;
        for (i = 0; i < cache->reg_max; i++) {
            RegisterDefinition * r = cache->reg_defs + i;
            if (r->name != NULL) {
                r->offset = offs;
                offs += r->size;
            }
            if (r->role != NULL && strcmp(r->role, "PC") == 0) {
                cache->pc_def = r;
            }
        }
        cache->reg_size = offs;
        cache_notify(&cache->regs_cache);
    }
    context_unlock(cache->ctx);
}

static void check_registers_cache(ContextCache * cache) {
    if (cache->pending_regs_cnt > 0) cache_wait(&cache->regs_cache);
    if (cache->reg_error != NULL) exception(set_error_report_errno(cache->reg_error));
    if (cache->reg_defs == NULL) {
        Channel * c = cache->peer->target;
        cache->pending_regs_cnt++;
        protocol_send_command(c, "Registers", "getChildren", validate_registers_cache, cache);
        json_write_string(&c->out, cache->ctx->id);
        write_stream(&c->out, 0);
        write_stream(&c->out, MARKER_EOM);
        context_lock(cache->ctx);
        cache_wait(&cache->regs_cache);
    }
}

RegisterDefinition * get_reg_definitions(Context * ctx) {
    ContextCache * cache = *EXT(ctx);
    check_registers_cache(cache);
    return cache->reg_defs;
}

RegisterDefinition * get_PC_definition(Context * ctx) {
    ContextCache * cache = *EXT(ctx);
    check_registers_cache(cache);
    return cache->pc_def;
}

static void validate_reg_values_cache(Channel * c, void * args, int error) {
    StackFrameCache * s = (StackFrameCache *)args;
    Context * ctx = s->ctx->ctx;
    Trap trap;

    assert(s->pending != NULL);
    assert(s->error == NULL);
    if (set_trap(&trap)) {
        s->pending = NULL;
        if (!error) {
            int r = 0;
            int n = s->info.is_top_frame ? s->ctx->reg_max : s->reg_cnt;
            JsonReadBinaryState state;
            error = read_errno(&c->inp);
            json_read_binary_start(&state, &c->inp);
            for (r = 0; r < n; r++) {
                RegisterDefinition * reg = s->info.is_top_frame ? s->ctx->reg_defs + r : s->reg_defs[r];
                if (reg->size > 0 && reg->dwarf_id >= 0) {
                    size_t pos = 0;
                    uint8_t * data = s->reg_data.data + reg->offset;
                    uint8_t * mask = s->reg_data.mask + reg->offset;
                    assert(reg->offset + reg->size <= s->ctx->reg_size);
                    while (pos < reg->size) {
                        size_t rd = json_read_binary_data(&state, data + pos, reg->size - pos);
                        assert(pos + rd <= reg->size);
                        memset(mask + pos, ~0, rd);
                        if (rd == 0) break;
                        pos += rd;
                    }
                }
            }
            json_read_binary_end(&state);
            if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX);
            if (read_stream(&c->inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);
        }
        clear_trap(&trap);
    }
    else {
        error = trap.error;
    }
    s->error = get_error_report(error);
    cache_notify(&s->cache);
    if (s->disposed) free_stack_frame_cache(s);
    context_unlock(ctx);
}

static void validate_reg_children_cache(Channel * c, void * args, int error) {
    StackFrameCache * s = (StackFrameCache *)args;
    Context * ctx = s->ctx->ctx;
    Trap trap;

    assert(s->pending != NULL);
    assert(s->error == NULL);
    if (set_trap(&trap)) {
        s->pending = NULL;
        if (!error) {
            ids_buf_pos = 0;
            str_buf_pos = 0;
            error = read_errno(&c->inp);
            json_read_array(&c->inp, read_ids_item, NULL);
            if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX);
            if (read_stream(&c->inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);
            if (!error && !s->disposed) {
                unsigned n = 0;
                s->reg_cnt = ids_buf_pos;
                s->reg_defs = (RegisterDefinition **)loc_alloc_zero(sizeof(RegisterDefinition *) * s->reg_cnt);
                for (n = 0; n < s->reg_cnt; n++) {
                    char * id = str_buf + ids_buf[n];
                    unsigned r = get_reg_index(s->ctx, id);
                    s->reg_defs[n] = s->ctx->reg_defs + r;
                }
                if (!error) {
                    s->pending = protocol_send_command(c, "Registers", "getm", validate_reg_values_cache, s);
                    write_stream(&c->out, '[');
                    for (n = 0; n < s->reg_cnt; n++) {
                        RegisterDefinition * reg = s->reg_defs[n];
                        if (reg->size > 0 && reg->dwarf_id >= 0) {
                            char * id = str_buf + ids_buf[n];
                            if (n > 0) write_stream(&c->out, ',');
                            write_stream(&c->out, '[');
                            json_write_string(&c->out, id);
                            write_stream(&c->out, ',');
                            json_write_long(&c->out, 0);
                            write_stream(&c->out, ',');
                            json_write_long(&c->out, reg->size);
                            write_stream(&c->out, ']');
                        }
                    }
                    write_stream(&c->out, ']');
                    write_stream(&c->out, 0);
                    write_stream(&c->out, MARKER_EOM);
                    clear_trap(&trap);
                    return;
                }
            }
        }
        clear_trap(&trap);
    }
    else {
        error = trap.error;
    }
    s->error = get_error_report(error);
    cache_notify(&s->cache);
    if (s->disposed) free_stack_frame_cache(s);
    context_unlock(ctx);
}

static void read_stack_frame_property(InputStream * inp, const char * name, void * args) {
    StackFrameCache * s = (StackFrameCache *)args;
    if (strcmp(name, "FP") == 0) s->info.fp = (ContextAddress)json_read_uint64(inp);
    else if (strcmp(name, "IP") == 0) s->ip = (ContextAddress)json_read_uint64(inp);
    else if (strcmp(name, "RP") == 0) s->rp = (ContextAddress)json_read_uint64(inp);
    else if (strcmp(name, "TopFrame") == 0) s->info.is_top_frame = json_read_boolean(inp);
    else json_skip_object(inp);
}

static void read_stack_frame(InputStream * inp, void * args) {
    json_read_struct(inp, read_stack_frame_property, args);
}

static void validate_stack_frame_cache(Channel * c, void * args, int error) {
    StackFrameCache * s = (StackFrameCache *)args;
    Context * ctx = s->ctx->ctx;
    Trap trap;

    assert(s->pending != NULL);
    assert(s->error == NULL);
    if (set_trap(&trap)) {
        s->pending = NULL;
        if (!error) {
            json_read_array(&c->inp, read_stack_frame, s);
            if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX);
            error = read_errno(&c->inp);
            if (read_stream(&c->inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX);
            if (!error && !s->disposed) {
                if (s->info.is_top_frame) {
                    unsigned cnt = 0;
                    RegisterDefinition * reg = s->ctx->reg_defs;
                    s->pending = protocol_send_command(c, "Registers", "getm", validate_reg_values_cache, s);
                    write_stream(&c->out, '[');
                    while (reg->name) {
                        if (reg->size > 0 && reg->dwarf_id >= 0) {
                            if (cnt > 0) write_stream(&c->out, ',');
                            write_stream(&c->out, '[');
                            json_write_string(&c->out, register2id(s->ctx->ctx, s->frame, reg));
                            write_stream(&c->out, ',');
                            json_write_long(&c->out, 0);
                            write_stream(&c->out, ',');
                            json_write_long(&c->out, reg->size);
                            write_stream(&c->out, ']');
                            cnt++;
                        }
                        reg++;
                    }
                    write_stream(&c->out, ']');
                }
                else {
                    s->pending = protocol_send_command(c, "Registers", "getChildren", validate_reg_children_cache, s);
                    json_write_string(&c->out, frame2id(s->ctx->ctx, s->frame));
                }
                write_stream(&c->out, 0);
                write_stream(&c->out, MARKER_EOM);
                clear_trap(&trap);
                return;
            }
        }
        clear_trap(&trap);
    }
    else {
        error = trap.error;
    }
    s->error = get_error_report(error);
    cache_notify(&s->cache);
    if (s->disposed) free_stack_frame_cache(s);
    context_unlock(ctx);
}

int get_frame_info(Context * ctx, int frame, StackFrame ** info) {
    ContextCache * cache = *EXT(ctx);
    Channel * c = cache->peer->target;
    StackFrameCache * s = NULL;
    LINK * l = NULL;
    const char * id = NULL;
    Trap trap;

    if (!cache->has_state) {
        errno = ERR_INV_CONTEXT;
        return -1;
    }
    if (cache->ctx->exited) {
        errno = ERR_ALREADY_EXITED;
        return -1;
    }

    if (!set_trap(&trap)) return -1;

    assert(frame >= 0);
    check_registers_cache(cache);
    for (l = cache->stk_cache_list.next; l != &cache->stk_cache_list; l = l->next) {
        s = ctx2stk(l);
        if (s->frame == frame) {
            assert(!s->disposed);
            if (s->pending != NULL) cache_wait(&s->cache);
            *info = &s->info;
            clear_trap(&trap);
            set_error_report_errno(s->error);
            return !errno ? 0 : -1;
        }
    }

    id = frame2id(cache->ctx, frame);
    if (id == NULL) {
        clear_trap(&trap);
        return -1;
    }

    s = (StackFrameCache *)loc_alloc_zero(sizeof(StackFrameCache));
    list_add_first(&s->link_ctx, &cache->stk_cache_list);
    s->ctx = cache;
    s->frame = frame;
    s->info.ctx = ctx;
    s->info.regs = &s->reg_data;
    s->reg_data.data = (uint8_t *)loc_alloc_zero(cache->reg_size);
    s->reg_data.mask = (uint8_t *)loc_alloc_zero(cache->reg_size);
    s->pending = protocol_send_command(c, "StackTrace", "getContext", validate_stack_frame_cache, s);
    write_stream(&c->out, '[');
    json_write_string(&c->out, id);
    write_stream(&c->out, ']');
    write_stream(&c->out, 0);
    write_stream(&c->out, MARKER_EOM);
    context_lock(ctx);
    cache_wait(&s->cache);
    return -1;
}

/* TODO: need a cahce for StackTrace.getChildren */
int get_top_frame(Context * ctx) {
    set_errno(ERR_UNSUPPORTED, "get_top_frame()");
    return STACK_TOP_FRAME;
}

int get_prev_frame(Context * ctx, int frame) {
    set_errno(ERR_UNSUPPORTED, "get_prev_frame()");
    return STACK_NO_FRAME;
}

int get_next_frame(Context * ctx, int frame) {
    set_errno(ERR_UNSUPPORTED, "get_next_frame()");
    return STACK_NO_FRAME;
}

unsigned context_word_size(Context * ctx) {
    RegisterDefinition * pc = get_PC_definition(ctx);
    return pc->size;
}

static void channel_close_listener(Channel * c) {
    LINK * l = NULL;

    for (l = peers.next; l != &peers; l = l->next) {
        PeerCache * p = peers2peer(l);
        if (p->target == c) {
            int i;
            assert(p->rc_pending_cnt == 0);
            for (i = 0; i < CTX_ID_HASH_SIZE; i++) {
                LINK * h = p->context_id_hash + i;
                while (!list_is_empty(h)) {
                    ContextCache * c = idhashl2ctx(h->next);
                    assert(*EXT(c->ctx) == c);
                    send_context_exited_event(c->ctx);
                }
            }
            channel_unlock(p->host);
            channel_unlock(p->target);
            cache_dispose(&p->rc_cache);
            release_error_report(p->rc_error);
            list_remove(&p->link_all);
            loc_free(p);
            return;
        }
    }
}

static void event_context_exited(Context * ctx, void * args) {
    ContextCache * c = *EXT(ctx);
    assert(!list_is_empty(&c->id_hash_link));
    list_remove(&c->id_hash_link);
}

static void event_context_disposed(Context * ctx, void * args) {
    ContextCache * c = *EXT(ctx);
    assert(c->ctx == ctx);
    c->ctx = NULL;
    free_context_cache(c);
}

static void event_path_mapping_changed(Channel * c, void * args) {
    LINK * x = context_root.next;
    while (x != &context_root) {
        Context * ctx = ctxl2ctxp(x);
        ContextCache * p = *EXT(ctx);
        crear_memory_map_data(p);
        x = x->next;
    }
}

void init_contexts_sys_dep(void) {
    static PathMapEventListener path_map_listener = {
        event_path_mapping_changed,
    };
    static ContextEventListener context_event_listener = {
        NULL,
        event_context_exited,
        NULL,
        NULL,
        NULL,
        event_context_disposed
    };
    add_path_map_event_listener(&path_map_listener, NULL);
    add_context_event_listener(&context_event_listener, NULL);
    add_channel_close_listener(channel_close_listener);
    context_extension_offset = context_extension(sizeof(ContextCache *));
}

#endif /* ENABLE_DebugContext && ENABLE_ContextProxy */

Back to the top