probe_rs/probe/blackmagic/
mod.rs

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
//! Black Magic Probe implementation.
use std::{
    char,
    io::{BufReader, BufWriter, Read, Write},
    time::Duration,
};

use crate::{
    architecture::{
        arm::{
            communication_interface::{DapProbe, UninitializedArmProbe},
            ArmCommunicationInterface,
        },
        riscv::{communication_interface::RiscvInterfaceBuilder, dtm::jtag_dtm::JtagDtmBuilder},
        xtensa::communication_interface::{
            XtensaCommunicationInterface, XtensaDebugInterfaceState,
        },
    },
    probe::{DebugProbe, DebugProbeInfo, JTAGAccess, ProbeFactory},
};
use bitvec::{order::Lsb0, vec::BitVec};
use probe_rs_target::ScanChainElement;
use serialport::{available_ports, SerialPortType};

use super::{
    arm_debug_interface::{ProbeStatistics, RawProtocolIo, SwdSettings},
    common::{JtagDriverState, RawJtagIo},
    DebugProbeError, ProbeCreationError, ProbeError, WireProtocol,
};

const BLACK_MAGIC_PROBE_VID: u16 = 0x1d50;
const BLACK_MAGIC_PROBE_PID: u16 = 0x6018;
const BLACK_MAGIC_PROTOCOL_RESPONSE_START: u8 = b'&';
const BLACK_MAGIC_PROTOCOL_RESPONSE_END: u8 = b'#';
pub(crate) const BLACK_MAGIC_REMOTE_SIZE_MAX: usize = 1024;

mod arm;
use arm::UninitializedBlackMagicArmProbe;

/// A factory for creating [`BlackMagicProbe`] instances.
#[derive(Debug)]
pub struct BlackMagicProbeFactory;

#[derive(PartialEq)]
enum ProtocolVersion {
    V0,
    V0P,
    V1,
    V2,
    V3,
    V4,
}

#[derive(Debug, Copy, Clone)]
pub(crate) enum Align {
    U8 = 0,
    U16 = 1,
    U32 = 2,
    U64 = 3,
}

impl core::fmt::Display for ProtocolVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::V0 => "V0",
                Self::V0P => "V0P",
                Self::V1 => "V1",
                Self::V2 => "V2",
                Self::V3 => "V3",
                Self::V4 => "V4",
            }
        )
    }
}

#[allow(dead_code)]
#[derive(Debug)]
enum RemoteCommand<'a> {
    Handshake(&'a mut [u8]),
    GetAccelerators,
    HighLevelCheck,
    GetVoltage,
    GetSpeedKhz,
    SetNrst(bool),
    SetPower(bool),
    TargetClockOutput {
        enable: bool,
    },
    SetSpeedKhz(u32),
    SpeedKhz,
    TargetReset(bool),
    RawAccessV0P {
        rnw: u8,
        addr: u8,
        value: u32,
    },
    ReadDpV0P {
        addr: u8,
    },
    ReadApV0P {
        apsel: u8,
        addr: u8,
    },
    WriteApV0P {
        apsel: u8,
        addr: u8,
        value: u32,
    },
    MemReadV0P {
        apsel: u8,
        csw: u32,
        offset: u32,
        data: &'a mut [u8],
    },
    MemWriteV0P {
        apsel: u8,
        csw: u32,
        align: Align,
        offset: u32,
        data: &'a [u8],
    },
    RawAccessV1 {
        index: u8,
        rnw: u8,
        addr: u8,
        value: u32,
    },
    ReadDpV1 {
        index: u8,
        addr: u8,
    },
    ReadApV1 {
        index: u8,
        apsel: u8,
        addr: u8,
    },
    WriteApV1 {
        index: u8,
        apsel: u8,
        addr: u8,
        value: u32,
    },
    MemReadV1 {
        index: u8,
        apsel: u8,
        csw: u32,
        offset: u32,
        data: &'a mut [u8],
    },
    MemWriteV1 {
        index: u8,
        apsel: u8,
        csw: u32,
        align: Align,
        offset: u32,
        data: &'a [u8],
    },
    RawAccessV3 {
        index: u8,
        rnw: u8,
        addr: u8,
        value: u32,
    },
    ReadDpV3 {
        index: u8,
        addr: u8,
    },
    ReadApV3 {
        index: u8,
        apsel: u8,
        addr: u8,
    },
    WriteApV3 {
        index: u8,
        apsel: u8,
        addr: u8,
        value: u32,
    },
    MemReadV3 {
        index: u8,
        apsel: u8,
        csw: u32,
        offset: u32,
        data: &'a mut [u8],
    },
    MemWriteV3 {
        index: u8,
        apsel: u8,
        csw: u32,
        align: Align,
        offset: u32,
        data: &'a [u8],
    },
    MemReadV4 {
        index: u8,
        apsel: u8,
        csw: u32,
        offset: u64,
        data: &'a mut [u8],
    },
    MemWriteV4 {
        index: u8,
        apsel: u8,
        csw: u32,
        align: Align,
        offset: u64,
        data: &'a [u8],
    },
    JtagNext {
        tms: bool,
        tdi: bool,
    },
    JtagTms {
        bits: u32,
        length: usize,
    },
    JtagTdi {
        bits: u32,
        length: usize,
        tms: bool,
    },
    JtagInit,
    JtagReset,
    JtagAddDevice {
        index: u8,
        dr_prescan: u8,
        dr_postscan: u8,
        ir_len: u8,
        ir_prescan: u8,
        ir_postscan: u8,
        current_ir: u32,
    },
    SwdInit,
    SwdIn {
        length: usize,
    },
    SwdInParity {
        length: usize,
    },
    SwdOut {
        value: u32,
        length: usize,
    },
    SwdOutParity {
        value: u32,
        length: usize,
    },
}

impl RemoteCommand<'_> {
    /// Return the buffer from the payload of the specified value where the
    /// response should be written.
    fn response_buffer(&mut self) -> Option<&mut [u8]> {
        match self {
            RemoteCommand::Handshake(data) => Some(data),
            RemoteCommand::MemReadV0P { data, .. } => Some(data),
            RemoteCommand::MemReadV1 { data, .. } => Some(data),
            RemoteCommand::MemReadV3 { data, .. } => Some(data),
            RemoteCommand::MemReadV4 { data, .. } => Some(data),
            _ => None,
        }
    }

    /// Return `true` if the resulting buffer should have hex decoded.
    fn decode_hex(&self) -> bool {
        matches!(
            self,
            RemoteCommand::MemReadV0P { .. }
                | RemoteCommand::MemReadV1 { .. }
                | RemoteCommand::MemReadV3 { .. }
                | RemoteCommand::MemReadV4 { .. }
        )
    }
}

// Implement `ToString` instead of `Display` as this is for generating
// strings to send over the network, and is not meant for human consumption.
#[allow(clippy::to_string_trait_impl)]
impl std::string::ToString for RemoteCommand<'_> {
    fn to_string(&self) -> String {
        match self {
            RemoteCommand::Handshake(_) => "+#!GA#".to_string(),
            RemoteCommand::GetVoltage => " !GV#".to_string(),
            RemoteCommand::GetSpeedKhz => "!Gf#".to_string(),
            RemoteCommand::SetSpeedKhz(speed) => {
                format!("!GF{:08x}#", speed)
            }
            RemoteCommand::HighLevelCheck => "!HC#".to_string(),
            RemoteCommand::SetNrst(set) => format!("!GZ{}#", if *set { '1' } else { '0' }),
            RemoteCommand::SetPower(set) => format!("!GP{}#", if *set { '1' } else { '0' }),
            RemoteCommand::TargetClockOutput { enable } => {
                format!("!GE{}#", if *enable { '1' } else { '0' })
            }
            RemoteCommand::SpeedKhz => "!Gf#".to_string(),
            RemoteCommand::RawAccessV0P { rnw, addr, value } => {
                format!("!HL{:02x}{:04x}{:08x}#", rnw, addr, value)
            }
            RemoteCommand::ReadDpV0P { addr } => {
                format!("!Hdff{:04x}#", addr)
            }
            RemoteCommand::ReadApV0P { apsel, addr } => {
                format!("!Ha{:02x}{:04x}#", apsel, 0x100 | *addr as u16)
            }
            RemoteCommand::WriteApV0P { apsel, addr, value } => {
                format!("!HA{:02x}{:04x}{:08x}#", apsel, 0x100 | *addr as u16, value)
            }
            RemoteCommand::MemReadV0P {
                apsel,
                csw,
                offset,
                data,
            } => format!(
                "!HM{:02x}{:08x}{:08x}{:08x}#",
                apsel,
                csw,
                offset,
                data.len()
            ),
            RemoteCommand::MemWriteV0P {
                apsel,
                csw,
                align,
                offset,
                data,
            } => {
                let mut s = format!(
                    "!Hm{:02x}{:08x}{:02x}{:08x}{:08x}",
                    apsel,
                    csw,
                    *align as u8,
                    offset,
                    data.len(),
                );
                for b in data.iter() {
                    s.push_str(&format!("{:02x}", b));
                }
                s.push('#');
                s
            }

            RemoteCommand::RawAccessV1 {
                index,
                rnw,
                addr,
                value,
            } => {
                format!("!HL{:02x}{:02x}{:04x}{:08x}#", index, rnw, addr, value)
            }
            RemoteCommand::ReadDpV1 { index, addr } => {
                format!("!Hd{:02x}ff{:04x}#", index, addr)
            }
            RemoteCommand::ReadApV1 { index, apsel, addr } => {
                format!("!Ha{:02x}{:02x}{:04x}#", index, apsel, 0x100 | *addr as u16)
            }
            RemoteCommand::WriteApV1 {
                index,
                apsel,
                addr,
                value,
            } => format!(
                "!HA{:02x}{:02x}{:04x}{:08x}#",
                index,
                apsel,
                0x100 | *addr as u16,
                value
            ),
            RemoteCommand::MemReadV1 {
                index,
                apsel,
                csw,
                offset,
                data,
            } => format!(
                "!HM{:02x}{:02x}{:08x}{:08x}{:08x}#",
                index,
                apsel,
                csw,
                offset,
                data.len()
            ),
            RemoteCommand::MemWriteV1 {
                index,
                apsel,
                csw,
                align,
                offset,
                data,
            } => {
                let mut s = format!(
                    "!Hm{:02x}{:02x}{:08x}{:02x}{:08x}{:08x}",
                    index,
                    apsel,
                    csw,
                    *align as u8,
                    offset,
                    data.len()
                );
                for b in data.iter() {
                    s.push_str(&format!("{:02x}", b));
                }
                s.push('#');
                s
            }

            RemoteCommand::RawAccessV3 {
                index,
                rnw,
                addr,
                value,
            } => {
                format!("!AR{:02x}{:02x}{:04x}{:08x}#", index, rnw, addr, value)
            }
            RemoteCommand::ReadDpV3 { index, addr } => {
                format!("!Ad{:02x}ff{:04x}#", index, addr)
            }
            RemoteCommand::ReadApV3 { index, apsel, addr } => {
                format!("!Aa{:02x}{:02x}{:04x}#", index, apsel, 0x100 | *addr as u16)
            }
            RemoteCommand::WriteApV3 {
                index,
                apsel,
                addr,
                value,
            } => format!(
                "!AA{:02x}{:02x}{:04x}{:08x}#",
                index,
                apsel,
                0x100 | *addr as u16,
                value.to_be()
            ),
            RemoteCommand::MemReadV3 {
                index,
                apsel,
                csw,
                offset,
                data,
            } => format!(
                "!Am{:02x}{:02x}{:08x}{:08x}{:08x}#",
                index,
                apsel,
                csw,
                offset,
                data.len()
            ),
            RemoteCommand::MemWriteV3 {
                index,
                apsel,
                csw,
                align,
                offset,
                data,
            } => {
                let mut s = format!(
                    "!AM{:02x}{:02x}{:08x}{:02x}{:08x}{:08x}",
                    index,
                    apsel,
                    csw,
                    *align as u8,
                    offset,
                    data.len()
                );
                for b in data.iter() {
                    s.push_str(&format!("{:02x}", b));
                }
                s.push('#');
                s
            }

            RemoteCommand::MemReadV4 {
                index,
                apsel,
                csw,
                offset,
                data,
            } => format!(
                "!Am{:02x}{:02x}{:08x}{:016x}{:08x}#",
                index,
                apsel,
                csw,
                offset,
                data.len()
            ),
            RemoteCommand::MemWriteV4 {
                index,
                apsel,
                csw,
                align,
                offset,
                data,
            } => {
                let mut s = format!(
                    "!AM{:02x}{:02x}{:08x}{:02x}{:016x}{:08x}",
                    index,
                    apsel,
                    csw,
                    *align as u8,
                    offset,
                    data.len()
                );
                for b in data.iter() {
                    s.push_str(&format!("{:02x}", b));
                }
                s.push('#');
                s
            }

            RemoteCommand::JtagNext { tms, tdi } => format!(
                "!JN{}{}#",
                if *tms { '1' } else { '0' },
                if *tdi { '1' } else { '0' }
            ),
            RemoteCommand::JtagInit => "+#!JS#".to_string(),
            RemoteCommand::JtagReset => "+#!JR#".to_string(),
            RemoteCommand::JtagTms { bits, length } => {
                format!("!JT{:02x}{:x}#", *length, *bits)
            }
            RemoteCommand::JtagTdi { bits, length, tms } => format!(
                "!J{}{:02x}{:x}#",
                if *tms { 'D' } else { 'd' },
                *length,
                *bits
            ),
            RemoteCommand::JtagAddDevice {
                index,
                dr_prescan,
                dr_postscan,
                ir_len,
                ir_prescan,
                ir_postscan,
                current_ir,
            } => format!(
                "!HJ{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:08x}#",
                *index, *dr_prescan, *dr_postscan, *ir_len, *ir_prescan, *ir_postscan, *current_ir
            ),
            RemoteCommand::SwdInit => "!SS#".to_string(),
            RemoteCommand::SwdIn { length: bits } => {
                format!("!Si{:02x}#", *bits)
            }
            RemoteCommand::SwdInParity { length } => {
                format!("!SI{:02x}#", *length)
            }
            RemoteCommand::SwdOut { value, length } => {
                format!("!So{:02x}{:x}#", *length, *value)
            }
            RemoteCommand::SwdOutParity { value, length } => {
                format!("!SO{:02x}{:x}#", *length, *value)
            }
            RemoteCommand::TargetReset(reset) => {
                format!("!GZ{}#", if *reset { '1' } else { '0' })
            }
            RemoteCommand::GetAccelerators => "!HA#".to_string(),
        }
    }
}

#[derive(Debug, thiserror::Error)]
enum RemoteError {
    ParameterError(u64),
    Error(u64),
    Unsupported(u64),
    ProbeError(std::io::Error),
    UnsupportedVersion(u64),
}

impl core::fmt::Display for RemoteError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ParameterError(e) => write!(f, "Remote paramater error with result {:016x}", *e),
            Self::Error(e) => write!(f, "Remote error with result {:016x}", *e),
            Self::Unsupported(e) => write!(f, "Remote command unsupported with result {:016x}", *e),
            Self::ProbeError(e) => write!(f, "Probe error {}", e),
            Self::UnsupportedVersion(e) => write!(f, "Only versions 0-4 are supported, not {}", e),
        }
    }
}

impl ProbeError for RemoteError {}

struct RemoteResponse(u64);

#[derive(PartialEq, Copy, Clone)]
enum SwdDirection {
    Input,
    Output,
}

impl From<bool> for SwdDirection {
    fn from(value: bool) -> Self {
        if value {
            SwdDirection::Output
        } else {
            SwdDirection::Input
        }
    }
}

/// A Black Magic Probe.
pub struct BlackMagicProbe {
    reader: BufReader<Box<dyn Read + Send>>,
    writer: BufWriter<Box<dyn Write + Send>>,
    protocol: Option<WireProtocol>,
    version: String,
    remote_protocol: ProtocolVersion,
    speed_khz: u32,
    jtag_state: JtagDriverState,
    probe_statistics: ProbeStatistics,
    swd_settings: SwdSettings,
    in_bits: BitVec<u8, Lsb0>,
    swd_direction: SwdDirection,
}

impl core::fmt::Debug for BlackMagicProbe {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        write!(
            f,
            "Black Magic Probe {} with remote protocol {}",
            self.version, self.remote_protocol
        )
    }
}

impl core::fmt::Display for BlackMagicProbeFactory {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        write!(f, "Black Magic Probe")
    }
}

impl BlackMagicProbe {
    fn new(
        reader: Box<dyn Read + Send>,
        writer: Box<dyn Write + Send>,
    ) -> Result<Self, DebugProbeError> {
        let mut reader = BufReader::new(reader);
        let mut writer = BufWriter::new(writer);

        let mut handshake_response = [0u8; 1024];
        Self::send(
            &mut writer,
            &RemoteCommand::Handshake(&mut handshake_response),
        )?;
        let response_len = Self::recv(&mut reader, Some(&mut handshake_response), false)
            .map_err(|e| {
                tracing::error!("Unable to receive command: {:?}", e);
                DebugProbeError::ProbeCouldNotBeCreated(ProbeCreationError::CouldNotOpen)
            })?
            .0;
        let version =
            String::from_utf8_lossy(&handshake_response[0..response_len as usize]).to_string();
        tracing::info!("Probe version {}", version);

        Self::send(&mut writer, &RemoteCommand::HighLevelCheck)?;
        let remote_protocol = if let Ok(response) = Self::recv(&mut reader, None, false) {
            match response.0 {
                0 => ProtocolVersion::V0P,
                1 => ProtocolVersion::V1,
                2 => ProtocolVersion::V2,
                3 => ProtocolVersion::V3,
                4 => ProtocolVersion::V4,
                version => {
                    return Err(DebugProbeError::ProbeCouldNotBeCreated(
                        ProbeCreationError::ProbeSpecific(
                            RemoteError::UnsupportedVersion(version).into(),
                        ),
                    ))
                }
            }
        } else {
            ProtocolVersion::V0
        };

        tracing::info!("Using BMP protocol {}", remote_protocol);

        let mut probe = Self {
            reader,
            writer,
            protocol: None,
            version,
            speed_khz: 0,
            remote_protocol,
            jtag_state: JtagDriverState::default(),
            swd_settings: SwdSettings::default(),
            probe_statistics: ProbeStatistics::default(),
            in_bits: BitVec::new(),
            swd_direction: SwdDirection::Output,
        };

        probe.command(RemoteCommand::SetPower(false)).ok();
        probe.command(RemoteCommand::SetNrst(false)).ok();
        probe.command(RemoteCommand::GetVoltage).ok();
        probe.command(RemoteCommand::SetSpeedKhz(400_0000)).ok();
        probe.command(RemoteCommand::GetSpeedKhz).ok();

        Ok(probe)
    }

    fn command(&mut self, mut command: RemoteCommand) -> Result<RemoteResponse, RemoteError> {
        let result = Self::send(&mut self.writer, &command);
        if let Err(e) = result {
            tracing::error!("Error sending command: {:?}", e);
            return Err(e);
        }
        let should_decode = command.decode_hex();

        Self::recv(&mut self.reader, command.response_buffer(), should_decode)
    }

    fn send(
        writer: &mut BufWriter<Box<dyn Write + Send>>,
        command: &RemoteCommand,
    ) -> Result<(), RemoteError> {
        let s = command.to_string();
        tracing::debug!(" > {}", s);
        write!(writer, "{}", s).map_err(RemoteError::ProbeError)?;
        writer.flush().map_err(RemoteError::ProbeError)
    }

    fn hex_val(c: u8) -> Result<u8, char> {
        match c {
            b'A'..=b'F' => Ok(c - b'A' + 10),
            b'a'..=b'f' => Ok(c - b'a' + 10),
            b'0'..=b'9' => Ok(c - b'0'),
            _ => Err(c as char),
        }
    }

    fn from_hex_u64(hex: &[u8]) -> Result<u64, ()> {
        // Strip off leading `0x` if present
        let hex = if hex.first() == Some(&b'0')
            && (hex.get(1) == Some(&b'x') || hex.get(1) == Some(&b'X'))
        {
            &hex[2..]
        } else {
            hex
        };

        let mut val = 0u64;

        for (index, c) in hex.iter().rev().enumerate() {
            let decoded_val: u64 = Self::hex_val(*c).or(Err(()))?.into();
            val += decoded_val << (index * 4);
        }
        Ok(val)
    }

    fn recv_u64(reader: &mut BufReader<Box<dyn Read + Send>>) -> Result<u64, RemoteError> {
        let mut response_buffer = [0u8; 16];
        let mut response_len = 0;
        for dest in response_buffer.iter_mut() {
            let mut byte = [0u8; 1];
            reader
                .read_exact(&mut byte)
                .map_err(RemoteError::ProbeError)?;
            if byte[0] == BLACK_MAGIC_PROTOCOL_RESPONSE_END {
                break;
            }
            *dest = byte[0];
            response_len += 1;
        }
        // Convert the hex in the buffer to a u64.
        Self::from_hex_u64(&response_buffer[0..response_len])
            .or(Err(RemoteError::ParameterError(0)))
    }

    fn recv(
        reader: &mut BufReader<Box<dyn Read + Send>>,
        buffer: Option<&mut [u8]>,
        decode_hex: bool,
    ) -> Result<RemoteResponse, RemoteError> {
        // Responses begin with `&`
        loop {
            let mut byte = [0u8; 1];
            reader
                .read_exact(&mut byte)
                .map_err(RemoteError::ProbeError)?;
            if byte[0] == BLACK_MAGIC_PROTOCOL_RESPONSE_START {
                break;
            }
        }
        let mut response_code = [0u8; 1];
        reader
            .read_exact(&mut response_code)
            .map_err(RemoteError::ProbeError)?;
        let response_code = response_code[0];

        // If there was no incoming buffer, then we will read up to 64 bits of data and
        // return a response based on that.

        if response_code == b'K' {
            let Some(buffer) = buffer else {
                let response = Self::recv_u64(reader)?;
                tracing::trace!(" < K{:x}", response);
                return Ok(RemoteResponse(response));
            };
            let mut output_count = 0;
            for dest in buffer.iter_mut() {
                let mut byte = [0u8; 1];

                // Read the first nibble
                reader
                    .read_exact(&mut byte)
                    .map_err(RemoteError::ProbeError)?;
                if byte[0] == BLACK_MAGIC_PROTOCOL_RESPONSE_END {
                    break;
                }

                // Add one byte to the resulting output value. This is the case whether we
                // get one or two nibbles.
                output_count += 1;

                if decode_hex {
                    *dest = Self::hex_val(byte[0])
                        .or(Err(RemoteError::ParameterError(byte[0] as _)))?;

                    // Read the second nibble, if present.
                    reader
                        .read_exact(&mut byte)
                        .map_err(RemoteError::ProbeError)?;
                    if byte[0] == BLACK_MAGIC_PROTOCOL_RESPONSE_END {
                        break;
                    }

                    *dest = *dest << 4
                        | Self::hex_val(byte[0])
                            .or(Err(RemoteError::ParameterError(byte[0] as _)))?;
                } else {
                    *dest = byte[0];
                }
            }
            tracing::trace!(" < K{:x?}", &buffer[0..output_count as usize]);
            Ok(RemoteResponse(output_count))
        } else {
            let response = Self::recv_u64(reader)?;
            tracing::trace!(" < {}{:x}", char::from(response_code), response);
            if response_code == b'E' {
                Err(RemoteError::Error(response))
            } else if response_code == b'P' {
                Err(RemoteError::ParameterError(response))
            } else {
                Err(RemoteError::Unsupported(response))
            }
        }
    }

    fn get_speed(&mut self) -> Result<u32, DebugProbeError> {
        let speed = self.command(RemoteCommand::SpeedKhz)?.0.try_into().unwrap();
        Ok(speed)
    }

    fn drain_swd_accumulator(
        &mut self,
        output: &mut Vec<bool>,
        accumulator: u32,
        accumulator_length: usize,
    ) -> Result<(), DebugProbeError> {
        if self.swd_direction == SwdDirection::Output {
            match self.command(RemoteCommand::SwdOut {
                value: accumulator,
                length: accumulator_length,
            }) {
                Ok(response) => tracing::debug!(
                    "Doing SWD out of {} bits: {:x} -- {}",
                    accumulator_length,
                    accumulator,
                    response.0
                ),
                Err(e) => tracing::error!(
                    "Error doing SWD OUT of {} bits ({:x}) -- {}",
                    accumulator_length,
                    accumulator,
                    e
                ),
            }
            for bit in 0..accumulator_length {
                output.push(accumulator & (1 << bit) != 0);
            }
        } else {
            let result = self.command(RemoteCommand::SwdIn {
                length: accumulator_length,
            });
            match &result {
                Ok(response) => {
                    let response = response.0;
                    tracing::debug!(
                        "Doing SWD in of {} bits: {:x}",
                        accumulator_length,
                        response
                    );
                    for bit in 0..accumulator_length {
                        output.push(response & (1 << bit) != 0);
                    }
                }
                Err(e) => tracing::error!(
                    "Error doing SWD IN operation of {} bits: {}",
                    accumulator_length,
                    e
                ),
            }
        }
        Ok(())
    }

    /// Perform a single SWDIO command
    ///
    /// The caller needs to ensure that the given iterators are not longer than the maximum transfer size
    /// allowed. It seems that the maximum transfer size is determined by [`self.max_mem_block_size`].
    fn perform_swdio_transfer<D, S>(
        &mut self,
        dir: D,
        swdio: S,
    ) -> Result<Vec<bool>, DebugProbeError>
    where
        D: IntoIterator<Item = bool>,
        S: IntoIterator<Item = bool>,
    {
        let dir = dir.into_iter();
        let swdio = swdio.into_iter();
        let mut output = vec![];

        let mut accumulator = 0u32;
        let mut accumulator_length = 0;

        for (dir, swdio) in dir.zip(swdio) {
            let dir = SwdDirection::from(dir);
            if dir != self.swd_direction
                || accumulator_length >= core::mem::size_of_val(&accumulator) * 8
            {
                // Inputs are off-by-one due to how J-Link is built. Remove one bit
                // from the accumulator and store the turnaround bit at the end of
                // the transaction.
                if self.swd_direction == SwdDirection::Input && dir == SwdDirection::Output {
                    accumulator_length -= 2;
                }

                // Drain the accumulator to the BMP, either writing bits to the device
                // or reading bits from the device.
                self.drain_swd_accumulator(&mut output, accumulator, accumulator_length)?;

                // Input -> Output transition
                if self.swd_direction == SwdDirection::Input && dir == SwdDirection::Output {
                    output.push(false);
                    output.push(false);
                }

                accumulator = 0;
                accumulator_length = 0;
            }
            self.swd_direction = dir;
            accumulator |= if swdio { 1 << accumulator_length } else { 0 };
            accumulator_length += 1;
        }

        if accumulator_length > 0 {
            self.drain_swd_accumulator(&mut output, accumulator, accumulator_length)?;
        }

        Ok(output)
    }

    fn drain_jtag_accumulator(
        &mut self,
        accumulator: u32,
        mut accumulator_length: usize,
        final_tms: bool,
        capture: bool,
        final_transaction: bool,
    ) -> Result<(), DebugProbeError> {
        let response = self.command(RemoteCommand::JtagTdi {
            bits: accumulator,
            length: accumulator_length,
            tms: final_tms && final_transaction,
        })?;

        if capture {
            // If this is the last bit, then `cap` may be false.
            if capture && final_transaction {
                accumulator_length -= 1;
            }
            let value = response.0;
            for bit in 0..accumulator_length {
                self.in_bits.push(value & (1 << bit) != 0);
            }
        }
        Ok(())
    }

    fn perform_jtag_transfer(
        &mut self,
        transaction: Vec<(bool, bool, bool)>,
        final_tms: bool,
        capture: bool,
    ) -> Result<(), DebugProbeError> {
        let mut accumulator = 0;
        let mut accumulator_length = 0;
        let bit_count = transaction.len();

        for (index, (_, tdi, _)) in transaction.into_iter().enumerate() {
            accumulator |= if tdi { 1 << accumulator_length } else { 0 };
            accumulator_length += 1;
            if accumulator_length >= core::mem::size_of_val(&accumulator) * 8 {
                let is_final = index + 1 >= bit_count;
                self.drain_jtag_accumulator(
                    accumulator,
                    accumulator_length,
                    final_tms,
                    capture,
                    is_final,
                )?;
                accumulator = 0;
                accumulator_length = 0;
            }
        }

        if accumulator_length > 0 {
            self.drain_jtag_accumulator(accumulator, accumulator_length, final_tms, capture, true)?;
        }
        Ok(())
    }
}

impl DebugProbe for BlackMagicProbe {
    fn get_name(&self) -> &str {
        "Black Magic probe"
    }

    fn speed_khz(&self) -> u32 {
        self.speed_khz
    }

    fn set_speed(&mut self, speed_khz: u32) -> Result<u32, DebugProbeError> {
        Self::send(&mut self.writer, &RemoteCommand::SetSpeedKhz(speed_khz))?;
        self.speed_khz = self.get_speed()?;
        Ok(self.speed_khz)
    }

    fn set_scan_chain(&mut self, scan_chain: Vec<ScanChainElement>) -> Result<(), DebugProbeError> {
        tracing::info!("Setting scan chain to {:?}", scan_chain);
        self.jtag_state.expected_scan_chain = Some(scan_chain);
        Ok(())
    }

    fn scan_chain(&self) -> Result<&[ScanChainElement], DebugProbeError> {
        if let Some(scan_chain) = &self.jtag_state.expected_scan_chain {
            Ok(scan_chain)
        } else {
            Ok(&[])
        }
    }

    fn attach(&mut self) -> Result<(), DebugProbeError> {
        tracing::debug!("Attaching with protocol '{:?}'", self.protocol);

        // Enable output on the clock pin (if supported)
        if let ProtocolVersion::V2 | ProtocolVersion::V3 | ProtocolVersion::V4 =
            self.remote_protocol
        {
            self.command(RemoteCommand::TargetClockOutput { enable: true })
                .ok();
        }

        match self.protocol {
            Some(WireProtocol::Jtag) => {
                self.scan_chain()?;
                self.select_target(0)?;

                if let ProtocolVersion::V1
                | ProtocolVersion::V2
                | ProtocolVersion::V3
                | ProtocolVersion::V4 = self.remote_protocol
                {
                    let sc = &self.jtag_state.chain_params;
                    self.command(RemoteCommand::JtagAddDevice {
                        index: 0,
                        dr_prescan: sc.drpre.try_into().unwrap(),
                        dr_postscan: sc.drpost.try_into().unwrap(),
                        ir_len: sc.irlen.try_into().unwrap(),
                        ir_prescan: sc.irpre.try_into().unwrap(),
                        ir_postscan: sc.irpost.try_into().unwrap(),
                        current_ir: u32::MAX,
                    })?;
                }
                Ok(())
            }
            Some(WireProtocol::Swd) => Ok(()),
            _ => Err(DebugProbeError::InterfaceNotAvailable {
                interface_name: "no protocol specified",
            }),
        }
    }

    fn select_jtag_tap(&mut self, index: usize) -> Result<(), DebugProbeError> {
        self.select_target(index)
    }

    fn detach(&mut self) -> Result<(), crate::Error> {
        Ok(())
    }

    fn target_reset(&mut self) -> Result<(), DebugProbeError> {
        // TODO we could add this by using a GPIO. However, different probes may connect
        // different pins (if any) to the reset line, so we would need to make this configurable.
        Err(DebugProbeError::NotImplemented {
            function_name: "target_reset",
        })
    }

    fn target_reset_assert(&mut self) -> Result<(), DebugProbeError> {
        self.command(RemoteCommand::TargetReset(true))?;
        Ok(())
    }

    fn target_reset_deassert(&mut self) -> Result<(), DebugProbeError> {
        self.command(RemoteCommand::TargetReset(false))?;
        Ok(())
    }

    fn select_protocol(&mut self, protocol: WireProtocol) -> Result<(), DebugProbeError> {
        self.protocol = Some(protocol);

        tracing::debug!("Switching to protocol {}", protocol);
        match protocol {
            WireProtocol::Jtag => {
                self.command(RemoteCommand::JtagInit)?;
                self.command(RemoteCommand::JtagReset)?;
            }
            WireProtocol::Swd => {
                self.command(RemoteCommand::SwdInit)?;
            }
        }
        Ok(())
    }

    fn active_protocol(&self) -> Option<WireProtocol> {
        self.protocol
    }

    fn try_get_riscv_interface_builder<'probe>(
        &'probe mut self,
    ) -> Result<Box<dyn RiscvInterfaceBuilder<'probe> + 'probe>, DebugProbeError> {
        Ok(Box::new(JtagDtmBuilder::new(self)))
    }

    fn has_riscv_interface(&self) -> bool {
        true
    }

    fn into_probe(self: Box<Self>) -> Box<dyn DebugProbe> {
        self
    }

    /// Turn this probe into an ARM probe
    fn try_get_arm_interface<'probe>(
        mut self: Box<Self>,
    ) -> Result<Box<dyn UninitializedArmProbe + 'probe>, (Box<dyn DebugProbe>, DebugProbeError)>
    {
        let has_adiv5 = match self.remote_protocol {
            ProtocolVersion::V0 => false,
            ProtocolVersion::V0P
            | ProtocolVersion::V1
            | ProtocolVersion::V2
            | ProtocolVersion::V3 => true,
            ProtocolVersion::V4 => {
                if let Ok(accelerators) = self.command(RemoteCommand::GetAccelerators) {
                    accelerators.0 & 1 != 0
                } else {
                    false
                }
            }
        };

        if has_adiv5 {
            Ok(Box::new(UninitializedBlackMagicArmProbe::new(self)))
        } else {
            Ok(Box::new(ArmCommunicationInterface::new(self, true)))
        }
    }

    fn has_arm_interface(&self) -> bool {
        true
    }

    fn try_get_xtensa_interface<'probe>(
        &'probe mut self,
        state: &'probe mut XtensaDebugInterfaceState,
    ) -> Result<XtensaCommunicationInterface<'probe>, DebugProbeError> {
        Ok(XtensaCommunicationInterface::new(self, state))
    }

    fn has_xtensa_interface(&self) -> bool {
        true
    }
}

impl DapProbe for BlackMagicProbe {}

impl RawProtocolIo for BlackMagicProbe {
    fn jtag_shift_tms<M>(&mut self, tms: M, _tdi: bool) -> Result<(), DebugProbeError>
    where
        M: IntoIterator<Item = bool>,
    {
        self.probe_statistics.report_io();

        let tms = tms.into_iter().collect::<Vec<bool>>();
        let mut accumulator = 0;
        let mut accumulator_length = 0;
        for tms in tms.into_iter() {
            accumulator |= if tms { 1 << accumulator_length } else { 0 };
            accumulator_length += 1;

            if accumulator_length >= core::mem::size_of_val(&accumulator) * 8 {
                self.command(RemoteCommand::JtagTms {
                    bits: accumulator,
                    length: accumulator_length,
                })?;
                accumulator_length = 0;
                accumulator = 0;
            }
        }

        if accumulator_length > 0 {
            self.command(RemoteCommand::JtagTms {
                bits: accumulator,
                length: accumulator_length,
            })?;
        }

        Ok(())
    }

    fn jtag_shift_tdi<I>(&mut self, _tms: bool, tdi: I) -> Result<(), DebugProbeError>
    where
        I: IntoIterator<Item = bool>,
    {
        self.probe_statistics.report_io();

        let tdi = tdi.into_iter().collect::<Vec<bool>>();
        let mut accumulator = 0;
        let mut accumulator_length = 0;
        for tms in tdi.into_iter() {
            accumulator |= if tms { 1 << accumulator_length } else { 0 };
            accumulator_length += 1;

            if accumulator_length >= core::mem::size_of_val(&accumulator) * 8 {
                self.command(RemoteCommand::JtagTdi {
                    bits: accumulator,
                    length: accumulator_length,
                    tms: false,
                })?;
                accumulator_length = 0;
                accumulator = 0;
            }
        }

        if accumulator_length > 0 {
            self.command(RemoteCommand::JtagTdi {
                bits: accumulator,
                length: accumulator_length,
                tms: false,
            })?;
        }

        Ok(())
    }

    fn swd_io<D, S>(&mut self, dir: D, swdio: S) -> Result<Vec<bool>, DebugProbeError>
    where
        D: IntoIterator<Item = bool>,
        S: IntoIterator<Item = bool>,
    {
        self.probe_statistics.report_io();
        self.perform_swdio_transfer(dir, swdio)
    }

    fn swj_pins(
        &mut self,
        pin_out: u32,
        pin_select: u32,
        _pin_wait: u32,
    ) -> Result<u32, DebugProbeError> {
        // The Black Magic Probe doesn't support setting TCK/TMS/TDI/TDO directly,
        // and has no separate nTRST.
        if pin_select & 0x2f != 0 {
            return Err(DebugProbeError::CommandNotSupportedByProbe {
                command_name: "swj_pins",
            });
        }
        // Set the nRST pin according to the specified value
        if pin_select & 0x80 != 0 {
            self.command(RemoteCommand::TargetReset(pin_out & 0x80 == 0))?;
        }
        Ok(pin_out)
    }

    fn swd_settings(&self) -> &SwdSettings {
        &self.swd_settings
    }

    fn probe_statistics(&mut self) -> &mut ProbeStatistics {
        &mut self.probe_statistics
    }
}

impl RawJtagIo for BlackMagicProbe {
    fn shift_bit(
        &mut self,
        tms: bool,
        tdi: bool,
        capture_tdo: bool,
    ) -> Result<(), DebugProbeError> {
        self.jtag_state.state.update(tms);
        let response = self.command(RemoteCommand::JtagNext { tms, tdi }).unwrap();
        if capture_tdo {
            self.in_bits.push(response.0 != 0);
        }
        Ok(())
    }

    fn shift_bits(
        &mut self,
        tms: impl IntoIterator<Item = bool>,
        tdi: impl IntoIterator<Item = bool>,
        cap: impl IntoIterator<Item = bool>,
    ) -> Result<(), DebugProbeError> {
        let mut transaction = vec![];
        let mut last_tms = false;
        let mut last_cap = false;

        let mut special_transaction = false;
        let mut tms_true_count = 0;
        let mut cap_count = 0;
        for (tms, (tdi, cap)) in tms.into_iter().zip(tdi.into_iter().zip(cap)) {
            if tms {
                tms_true_count += 1;
            }
            if cap {
                cap_count += 1;
            }
            last_tms = tms;
            last_cap = cap;
            transaction.push((tms, tdi, cap));
        }

        // A strange number of bits are captured, such as including the last bit or
        // including a smattering of bits in the middle of the transaction.
        if (cap_count != 0 && (cap_count + 1 != transaction.len())) || last_cap {
            special_transaction = true;
        }

        // The TMS value is `true` for a field other than the last bit
        if tms_true_count > 1 || (tms_true_count == 1 && !last_tms) {
            special_transaction = true;
        }

        if special_transaction {
            for (tms, tdi, cap) in transaction {
                self.shift_bit(tms, tdi, cap)?;
            }
        } else {
            self.jtag_state.state.update(tms_true_count > 0);
            self.perform_jtag_transfer(transaction, tms_true_count > 0, cap_count > 0)?;
        }

        Ok(())
    }

    fn read_captured_bits(&mut self) -> Result<BitVec<u8, Lsb0>, DebugProbeError> {
        tracing::trace!("reading captured bits");
        Ok(std::mem::take(&mut self.in_bits))
    }

    fn state_mut(&mut self) -> &mut JtagDriverState {
        &mut self.jtag_state
    }

    fn state(&self) -> &JtagDriverState {
        &self.jtag_state
    }
}

/// Determine if a given serial port is a Black Magic Probe GDB interface.
/// The BMP has at least two serial ports, and we want to make sure we get
/// the correct one.
fn black_magic_debug_port_info(
    port_type: SerialPortType,
    port_name: &str,
) -> Option<DebugProbeInfo> {
    // Only accept /dev/cu.* values on macos, to avoid having two
    // copies of the port (both /dev/tty.* and /dev/cu.*)
    if cfg!(target_os = "macos") && !port_name.contains("/cu.") {
        return None;
    }

    let (vendor_id, product_id, serial_number, hid_interface, identifier) = match port_type {
        SerialPortType::UsbPort(info) => (
            info.vid,
            info.pid,
            info.serial_number.map(|s| s.to_string()),
            info.interface,
            info.product
                .unwrap_or_else(|| "Black Magic Probe".to_string()),
        ),
        _ => return None,
    };

    if vendor_id != BLACK_MAGIC_PROBE_VID {
        return None;
    }
    if product_id != BLACK_MAGIC_PROBE_PID {
        return None;
    }

    // Mac specifies the interface as the CDC Data interface, whereas Linux and
    // Windows use the CDC Communications interface. Accept either one here.
    if hid_interface != Some(0) && hid_interface != Some(1) {
        return None;
    }

    Some(DebugProbeInfo {
        identifier,
        vendor_id,
        product_id,
        serial_number,
        probe_factory: &BlackMagicProbeFactory,
        hid_interface,
    })
}

impl ProbeFactory for BlackMagicProbeFactory {
    fn open(
        &self,
        selector: &super::DebugProbeSelector,
    ) -> Result<Box<dyn DebugProbe>, DebugProbeError> {
        // Ensure the VID and PID match Black Magic Probes
        if selector.vendor_id != BLACK_MAGIC_PROBE_VID
            || selector.product_id != BLACK_MAGIC_PROBE_PID
        {
            return Err(DebugProbeError::ProbeCouldNotBeCreated(
                ProbeCreationError::NotFound,
            ));
        }

        // If the serial number is a valid "address:port" string, attempt to
        // connect to it via TCP.
        if let Some(serial_number) = &selector.serial_number {
            if let Ok(connection) = std::net::TcpStream::connect(serial_number) {
                let reader = connection;
                let writer = reader.try_clone().map_err(|e| {
                    DebugProbeError::ProbeCouldNotBeCreated(ProbeCreationError::Usb(e))
                })?;
                return BlackMagicProbe::new(Box::new(reader), Box::new(writer))
                    .map(|p| Box::new(p) as Box<dyn DebugProbe>);
            }
        }

        // Otherwise, treat it as a serial port and iterate through all ports.
        let Ok(ports) = available_ports() else {
            return Err(DebugProbeError::ProbeCouldNotBeCreated(
                ProbeCreationError::CouldNotOpen,
            ));
        };

        for port_description in ports {
            let Some(info) = black_magic_debug_port_info(
                port_description.port_type,
                &port_description.port_name,
            ) else {
                continue;
            };

            if selector.serial_number != info.serial_number {
                continue;
            }

            // Open with the baud rate 115200. This baud rate is arbitrary, since it's
            // a soft USB device and will run at the same speed regardless of the baud rate.
            let mut port = serialport::new(port_description.port_name, 115200)
                .timeout(std::time::Duration::from_secs(1))
                .open()
                .map_err(|_| {
                    DebugProbeError::ProbeCouldNotBeCreated(ProbeCreationError::CouldNotOpen)
                })?;

            // Set DTR, indicating we're ready to communicate.
            port.write_data_terminal_ready(true).map_err(|_| {
                DebugProbeError::ProbeCouldNotBeCreated(ProbeCreationError::CouldNotOpen)
            })?;
            // A delay appears necessary to allow the BMP to recognize the DTR signal.
            std::thread::sleep(Duration::from_millis(250));
            let reader = port;
            let writer = reader.try_clone().map_err(|_| {
                DebugProbeError::ProbeCouldNotBeCreated(ProbeCreationError::CouldNotOpen)
            })?;
            return BlackMagicProbe::new(Box::new(reader), Box::new(writer))
                .map(|p| Box::new(p) as Box<dyn DebugProbe>);
        }

        Err(DebugProbeError::ProbeCouldNotBeCreated(
            ProbeCreationError::NotFound,
        ))
    }

    fn list_probes(&self) -> Vec<super::DebugProbeInfo> {
        let mut probes = vec![];
        let Ok(ports) = available_ports() else {
            return probes;
        };
        for port in ports {
            let Some(info) = black_magic_debug_port_info(port.port_type, &port.port_name) else {
                continue;
            };
            probes.push(info);
        }
        probes
    }
}