udbg 0.3.1

cross-platform library for binary debugging and memory hacking
Documentation
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
use super::*;
use crate::elf::*;
use crate::os::udbg::{EventHandler, HandleResult};
use crate::range::RangeValue;

use anyhow::Context;
use goblin::elf::sym::Sym;
use nix::sys::ptrace::Options;
use nix::sys::wait::waitpid;
use parking_lot::RwLock;
use procfs::process::{Stat as ThreadStat, Task};
use serde_value::Value;
use std::cell::{Cell, UnsafeCell};
use std::collections::HashSet;
use std::mem::transmute;
use std::ops::Deref;
use std::time::{Duration, Instant};

const TRAP_BRKPT: i32 = 1;
const TRAP_TRACE: i32 = 2;
const TRAP_BRANCH: i32 = 3;
const TRAP_HWBKPT: i32 = 4;
const TRAP_UNK: i32 = 5;

cfg_if! {
    if #[cfg(target_os = "android")] {
        const PTRACE_INTERRUPT: c_uint = 0x4207;
        const PTRACE_SEIZE: c_uint = 0x4206;
    }
}

pub struct ElfSymbol {
    pub sym: Sym,
    pub name: Arc<str>,
}

impl Deref for ElfSymbol {
    type Target = Sym;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.sym
    }
}

impl From<ElfSym<'_>> for ElfSymbol {
    fn from(s: ElfSym<'_>) -> Self {
        ElfSymbol {
            sym: s.sym,
            name: s.name.into(),
        }
    }
}

#[derive(Deref)]
pub struct NixThread {
    #[deref]
    base: ThreadData,
    stat: ThreadStat,
}

impl TryFrom<Task> for NixThread {
    type Error = procfs::ProcError;

    fn try_from(task: Task) -> Result<Self, Self::Error> {
        Ok(NixThread {
            base: ThreadData {
                tid: task.tid,
                wow64: false,
            },
            stat: task.stat()?,
        })
    }
}

impl GetProp for NixThread {}

impl UDbgThread for NixThread {
    fn name(&self) -> Arc<str> {
        self.stat.comm.as_str().into()
    }
    fn status(&self) -> Arc<str> {
        self.stat.state.to_string().into()
    }
    fn priority(&self) -> Option<i64> {
        Some(self.stat.priority)
    }
}

#[inline(always)]
fn to_symbol(s: ElfSym) -> Symbol {
    let flags = if s.is_function() {
        SymbolFlags::FUNCTION
    } else {
        SymbolFlags::NONE
    };
    Symbol {
        offset: s.st_value as u32,
        name: s.name.into(),
        flags: flags.bits(),
        len: s.st_size as u32,
        type_id: 0,
    }
}

impl SymbolsData {
    fn from_elf(path: &str) -> Self {
        let mut this = Self::default();
        this.load(path);
        this
    }

    fn load(&mut self, path: &str) -> anyhow::Result<()> {
        let map = Utils::mapfile(path.as_ref()).context("map")?;
        let e = ElfHelper::parse(&map).context("parse")?;
        let mut push_symbol = |s: ElfSym| {
            if s.name.starts_with("$x.") {
                return;
            }
            self.exports
                .entry(s.offset())
                .or_insert_with(|| to_symbol(s));
        };
        e.enum_symbol().for_each(&mut push_symbol);
        e.enum_export().for_each(&mut push_symbol);
        Ok(())
    }
}

struct TimeCheck {
    last: Cell<Instant>,
    pub duration: Cell<Duration>,
}

impl TimeCheck {
    pub fn new(duration: Duration) -> Self {
        Self {
            last: Instant::now().checked_sub(duration).unwrap().into(),
            duration: duration.into(),
        }
    }

    pub fn check(&self, mut callback: impl FnMut()) {
        if self.last.get().elapsed() > self.duration.get() {
            callback();
            self.last.set(Instant::now());
        }
    }
}

#[derive(Deref)]
pub struct TargetCommon {
    #[deref]
    _base: CommonBase,
    pub threads: RwLock<HashSet<tid_t>>,
    tc_module: TimeCheck,
    tc_memory: TimeCheck,
    mem_pages: RwLock<Vec<MemoryPage>>,
    waiting: Cell<bool>,
    pub trace_opts: Options,
    pub hwbps: UnsafeCell<user_hwdebug_state>,
}

impl TargetCommon {
    pub fn new(ps: Process) -> Self {
        const TIMEOUT: Duration = Duration::from_secs(5);

        let mut base = CommonBase::new(ps);
        let image_path = base.process.image_path().unwrap_or_default();
        base.process
            .enum_module()
            .ok()
            .and_then(|mut iter| iter.find(|m| m.path.as_ref() == &image_path))
            .map(|m| base.image_base = m.base);

        let trace_opts = Options::PTRACE_O_EXITKILL
            | Options::PTRACE_O_TRACECLONE
            | Options::PTRACE_O_TRACEEXEC
            | Options::PTRACE_O_TRACEVFORK
            | Options::PTRACE_O_TRACEFORK;
        Self {
            _base: base,
            tc_module: TimeCheck::new(Duration::from_secs(10)),
            tc_memory: TimeCheck::new(Duration::from_secs(10)),
            mem_pages: RwLock::new(Vec::new()),
            threads: RwLock::new(HashSet::new()),
            trace_opts,
            waiting: Cell::new(false),
            hwbps: unsafe { core::mem::zeroed() },
        }
    }

    pub fn update_memory_page(&self) -> IoResult<()> {
        *self.mem_pages.write() = self.process.enum_memory()?.collect::<Vec<_>>();
        Ok(())
    }

    fn update_memory_page_check_time(&self) {
        self.tc_memory.check(|| {
            self.update_memory_page();
        });
    }

    // fn update_thread(&self) {
    //     let ts = unsafe { mutable(&self.threads) };
    //     let mut maps: HashSet<pid_t> = HashSet::new();
    //     for tid in process_tasks(self.pid) {
    //         if !ts.contains(&tid) {
    //             self.dbg.map(|d| d.thread_create(tid as u32));
    //         }
    //         maps.insert(tid);
    //     }
    //     *ts = maps;
    // }

    fn module_name<'a>(&self, name: &'a str) -> &'a str {
        let tv = trim_ver(name);
        let te = trim_allext(name);
        let base = self.symgr.base.read();
        if tv.len() < te.len() && !base.contains(tv) {
            return tv;
        }
        if !base.contains(te) {
            return te;
        }
        let te = trim_lastext(name);
        if !base.contains(te) {
            return te;
        }
        name
    }

    pub fn update_module(&self) -> IoResult<()> {
        use goblin::elf::header::header32::Header as Header32;
        use goblin::elf::header::header64::Header as Header64;
        use std::io::Read;

        // self.md.write().clear();
        for m in self.process.enum_module()? {
            if self.find_module(m.base).is_some()
                || m.name.ends_with(".oat")
                || m.name.ends_with(".apk")
            {
                continue;
            }
            let name = self.module_name(&m.name);

            // TODO: use memory data
            let mut f = match File::open(m.path.as_ref()) {
                Ok(f) => f,
                Err(_) => {
                    // error!("open module file: {}", m.path);
                    continue;
                }
            };

            // Non-File device will block the progress
            if !f
                .metadata()
                .map(|m| m.file_type().is_file())
                .unwrap_or(false)
            {
                continue;
            }

            let mut buf: Header64 = unsafe { core::mem::zeroed() };
            if f.read(buf.as_mut_byte_array()).is_err() {
                // error!("read file: {}", m.path);
                continue;
            }

            let arch = match ElfHelper::arch_name(buf.e_machine) {
                Some(a) => a,
                None => {
                    // error!("error e_machine: {} {}", buf.e_machine, m.path);
                    continue;
                }
            };

            let entry = match arch {
                "arm64" | "x86_64" => buf.e_entry as usize,
                "x86" | "arm" => unsafe { transmute::<_, &Header32>(&buf).e_entry as usize },
                a => {
                    // error!("error arch: {}", a);
                    continue;
                }
            };

            let base = m.base;
            let path = m.path.clone();
            self.symgr.base.write().add(Module {
                data: ModuleData {
                    base,
                    size: m.size,
                    arch,
                    entry,
                    user_module: false.into(),
                    name: name.into(),
                    path: path.clone(),
                },
                loaded: false.into(),
                syms: SymbolsData::from_elf(&path).into(),
            });
            // TODO:
            // self.base.module_load(&path, base);
        }
        Ok(())
    }

    fn wait_event(&self, tb: &mut TraceBuf) -> Option<WaitStatus> {
        self.waiting.set(true);
        let mut status = 0;
        let tid = unsafe { libc::waitpid(-1, &mut status, __WALL | WUNTRACED) };
        // let status = ::nix::sys::wait::waitpid(None, WaitPidFlag::__WALL | WaitPidFlag::__WNOTHREAD | WaitPidFlag::WNOHANG).unwrap();
        self.waiting.set(false);
        self.base.event_tid.set(tid);

        if tid <= 0 {
            return None;
        }

        let status = WaitStatus::from_raw(Pid::from_raw(tid), status).unwrap();
        println!("[status] {status:?}");
        Some(status)
    }

    pub fn hwbps(&self) -> &mut user_hwdebug_state {
        unsafe { self.hwbps.get().as_mut().unwrap() }
    }

    pub fn get_bp_(&self, id: BpID) -> Option<Arc<Breakpoint>> {
        Some(self.bp_map.read().get(&id)?.clone())
    }

    pub fn handle_breakpoint(
        &self,
        this: &dyn UDbgTarget,
        eh: &mut dyn EventHandler,
        tb: &mut TraceBuf,
    ) -> UDbgResult<HandleResult> {
        // correct the pc register
        let mut address = *tb.user.regs.ip();
        let is_step = tb.si.si_code == TRAP_TRACE;
        if IS_X86 {
            if is_step || tb.si.si_code == TRAP_HWBKPT {
                address = unsafe { tb.si.si_addr() as _ };
            } else {
                address -= 1;
            }
        }
        *tb.user.regs.ip() = address;

        let tid = self.base.event_tid.get();
        let bp = match self
            .get_bp_(address as _)
            .or_else(|| self.get_hwbp(tb))
            .ok_or(UDbgError::NotFound)
        {
            Ok(bp) => bp,
            Err(_) if is_step => {
                tb.user.set_step(false);
                self.handle_reply(this, tb.call(UEvent::Step), &mut tb.user);
                return Ok(None);
            }
            Err(err) => return Err(err),
        };

        bp.hit_count.set(bp.hit_count.get() + 1);
        if bp.temp.get() {
            self.remove_breakpoint(this, &bp);
        }

        // handle by user
        let hitted = bp.hit_tid.map(|t| t == tid).unwrap_or(true);
        if hitted {
            self.handle_reply(this, tb.call(UEvent::Breakpoint(bp.clone())), &mut tb.user);
        }

        let id = bp.get_id();

        #[cfg(target_arch = "x86_64")]
        if bp.is_hard() && self.get_bp(id).is_some() {
            tb.user.disable_hwbp_temporarily();
        }

        // int3 breakpoint revert
        if bp.is_soft() && self.get_bp(id).is_some() {
            // if bp is not deleted by user during the interruption
            if bp.enabled.get() {
                // disabled temporarily, in order to be able to continue
                self.enable_breadpoint(this, &bp, false)
                    .log_error("disable bp");
                assert_ne!(&this.read_value::<BpInsn>(bp.address()).unwrap(), BP_INSN);

                let user_step = tb.user.is_step();

                // step once and revert
                tb.user.set_step(true);
                #[cfg(any(target_arch = "aarch64"))]
                ptrace::step(Pid::from_raw(tid), None);
                loop {
                    eh.cont(None, tb);
                    match eh.fetch(tb) {
                        Some(_) => {
                            if core::ptr::eq(self, &tb.target.0) && self.base.event_tid.get() == tid
                            {
                                break;
                            } else if let Some(s) = eh.handle(tb) {
                                eh.cont(s, tb);
                            } else {
                                return Ok(None);
                            }
                        }
                        None => return Ok(None),
                    }
                }

                self.enable_breadpoint(this, &bp, true)
                    .log_error("enable bp");
                return if user_step {
                    Ok(eh.handle(tb).unwrap_or(None))
                } else {
                    tb.user.set_step(false);
                    // tb.regs_dirty = false;
                    Ok(None)
                };
            }
        }

        Ok(None)
    }

    fn enum_module<'a>(
        &'a self,
    ) -> UDbgResult<Box<dyn Iterator<Item = Arc<dyn UDbgModule + 'a>> + 'a>> {
        self.update_module();
        Ok(self.symgr.enum_module())
    }

    fn enum_memory<'a>(&'a self) -> Result<Box<dyn Iterator<Item = MemoryPage> + 'a>, UDbgError> {
        self.update_memory_page();
        Ok(Box::new(self.mem_pages.read().clone().into_iter()))
    }

    fn enum_handle<'a>(&'a self) -> UDbgResult<Box<dyn Iterator<Item = HandleInfo> + 'a>> {
        use procfs::process::FDTarget;

        Ok(Box::new(
            self.process.fd().context("fd iter")?.flatten().map(|fd| {
                let (ty, name) = match fd.target {
                    FDTarget::Path(p) => ("Path".into(), p.to_string_lossy().into_owned()),
                    FDTarget::Socket(s) => ("Socket".into(), s.to_string()),
                    FDTarget::Net(n) => ("Net".into(), n.to_string()),
                    FDTarget::Pipe(p) => ("Pipe".into(), p.to_string()),
                    FDTarget::AnonInode(i) => ("INode".into(), i),
                    FDTarget::MemFD(m) => ("MemFD".into(), m),
                    FDTarget::Other(a, b) => (a.into(), b.to_string()),
                };
                HandleInfo {
                    pid: self.process.pid,
                    ty: 0,
                    handle: fd.fd as _,
                    name,
                    type_name: ty,
                }
            }),
        ))
    }

    pub fn enable_hwbp(
        &self,
        dbg: &dyn UDbgTarget,
        bp: &Breakpoint,
        info: HwbpInfo,
        enable: bool,
    ) -> UDbgResult<bool> {
        let mut result = Ok(enable);
        // Set Context for each thread
        for &tid in self.threads.read().iter() {
            if bp.hit_tid.is_some() && bp.hit_tid != Some(tid) {
                continue;
            }
            // Set Debug Register
            result = self.enable_hwbp_for_thread(tid, bp, info, enable);
            if let Err(e) = &result {
                udbg_ui().error(format!("enable_hwbp_for_thread for {} failed {:?}", tid, e));
                // break;
            }
        }
        // TODO: Set Context for current thread, update eflags from user

        if result.is_ok() {
            bp.enabled.set(enable);
        }
        result
    }

    // #[cfg(target_arch = "x86_64")]
    // fn get_reg(&self, reg: &str, r: Option<&mut Registers>) -> Result<CpuReg, UDbgError> {
    //     let regs = self.regs();
    //     if let Some(r) = r {
    //         r.rax = regs.rax;
    //         r.rbx = regs.rbx;
    //         r.rcx = regs.rcx;
    //         r.rdx = regs.rdx;
    //         r.rbp = regs.rbp;
    //         r.rsp = regs.rsp;
    //         r.rsi = regs.rsi;
    //         r.rdi = regs.rdi;
    //         r.r8 = regs.r8;
    //         r.r9 = regs.r9;
    //         r.r10 = regs.r10;
    //         r.r11 = regs.r11;
    //         r.r12 = regs.r12;
    //         r.r13 = regs.r13;
    //         r.r14 = regs.r14;
    //         r.r15 = regs.r15;
    //         r.rip = regs.rip;
    //         r.rflags = regs.eflags as reg_t;
    //         Ok(0.into())
    //     } else {
    //         Ok(CpuReg::Int(match reg {
    //             "rax" => regs.rax,
    //             "rbx" => regs.rbx,
    //             "rcx" => regs.rcx,
    //             "rdx" => regs.rdx,
    //             "rbp" => regs.rbp,
    //             "rsp" | "_sp" => regs.rsp,
    //             "rsi" => regs.rsi,
    //             "rdi" => regs.rdi,
    //             "r8" => regs.r8,
    //             "r9" => regs.r9,
    //             "r10" => regs.r10,
    //             "r11" => regs.r11,
    //             "r12" => regs.r12,
    //             "r13" => regs.r13,
    //             "r14" => regs.r14,
    //             "r15" => regs.r15,
    //             "rip" | "_pc" => regs.rip,
    //             "rflags" => regs.eflags as reg_t,
    //             _ => return Err(UDbgError::InvalidRegister),
    //         } as usize))
    //     }
    // }

    // #[cfg(target_arch = "arm")]
    // fn get_reg(&self, reg: &str, r: Option<&mut Registers>) -> Result<CpuReg, UDbgError> {
    //     let regs = self.regs();
    //     if let Some(r) = r {
    //         *r = unsafe { transmute(*regs) };
    //         Ok(CpuReg::Int(0))
    //     } else {
    //         Ok(CpuReg::Int(match reg {
    //             "r0" => regs.regs[0],
    //             "r1" => regs.regs[1],
    //             "r2" => regs.regs[2],
    //             "r3" => regs.regs[3],
    //             "r4" => regs.regs[4],
    //             "r5" => regs.regs[5],
    //             "r6" => regs.regs[6],
    //             "r7" => regs.regs[7],
    //             "r8" => regs.regs[8],
    //             "r9" => regs.regs[9],
    //             "r10" => regs.regs[10],
    //             "r11" => regs.regs[11],
    //             "r12" => regs.regs[12],
    //             "_sp" | "r13" => regs.regs[13],
    //             "r14" => regs.regs[14],
    //             "_pc" | "r15" => regs.regs[15],
    //             "r16" => regs.regs[16],
    //             "r17" => regs.regs[17],
    //             _ => return Err(UDbgError::InvalidRegister),
    //         } as usize))
    //     }
    // }

    // #[cfg(target_arch = "aarch64")]
    // fn get_reg(&self, reg: &str, r: Option<&mut Registers>) -> Result<CpuReg, UDbgError> {
    //     let regs = self.regs();
    //     if let Some(r) = r {
    //         *r = unsafe { transmute(*regs) };
    //         Ok(CpuReg::Int(0))
    //     } else {
    //         Ok(CpuReg::Int(match reg {
    //             "pc" | "_pc" => regs.pc,
    //             "sp" | "_sp" => regs.sp,
    //             "pstate" => regs.pstate,
    //             "x0" => regs.regs[0],
    //             "x1" => regs.regs[1],
    //             "x2" => regs.regs[2],
    //             "x3" => regs.regs[3],
    //             "x4" => regs.regs[4],
    //             "x5" => regs.regs[5],
    //             "x6" => regs.regs[6],
    //             "x7" => regs.regs[7],
    //             "x8" => regs.regs[8],
    //             "x9" => regs.regs[9],
    //             "x10" => regs.regs[10],
    //             "x11" => regs.regs[11],
    //             "x12" => regs.regs[12],
    //             "x13" => regs.regs[13],
    //             "x14" => regs.regs[14],
    //             "x15" => regs.regs[15],
    //             "x16" => regs.regs[16],
    //             "x17" => regs.regs[17],
    //             "x18" => regs.regs[18],
    //             "x19" => regs.regs[19],
    //             "x20" => regs.regs[20],
    //             "x21" => regs.regs[21],
    //             "x22" => regs.regs[22],
    //             "x23" => regs.regs[23],
    //             "x24" => regs.regs[24],
    //             "x25" => regs.regs[25],
    //             "x26" => regs.regs[26],
    //             "x27" => regs.regs[27],
    //             "x28" => regs.regs[28],
    //             "x29" => regs.regs[29],
    //             "x30" => regs.regs[30],
    //             _ => return Err(UDbgError::InvalidRegister),
    //         } as usize))
    //     }
    // }
}

fn trim_ver(name: &str) -> &str {
    use regex::Regex;
    &name[..Regex::new(r"-\d")
        .unwrap()
        .find(name)
        .map(|p| p.start())
        .unwrap_or(name.len())]
}

#[inline]
fn trim_allext(name: &str) -> &str {
    &name[..name.find(|c| c == '.').unwrap_or(name.len())]
}

#[inline]
fn trim_lastext(name: &str) -> &str {
    &name[..name.rfind(|c| c == '.').unwrap_or(name.len())]
}

pub fn ptrace_interrupt(tid: tid_t) -> bool {
    unsafe { ptrace(PTRACE_INTERRUPT as _, tid, 0, 0) == 0 }
}

pub fn ptrace_seize(tid: tid_t, flags: c_int) -> bool {
    unsafe { ptrace(PTRACE_SEIZE as _, tid, 0, flags) == 0 }
}

pub fn ptrace_getevtmsg<T: Copy>(tid: tid_t, result: &mut T) -> bool {
    unsafe { ptrace(PTRACE_GETEVENTMSG, tid, 0, result) == 0 }
}

pub fn ptrace_step_and_wait(tid: pid_t) -> bool {
    let tid = Pid::from_raw(tid);
    ptrace::step(tid, None);
    match waitpid(tid, None) {
        Ok(t) => {
            let pid = t.pid();
            if pid == Some(tid) {
                return true;
            }
            udbg_ui().error(format!("step unexpect tid: {pid:?}"));
            false
        }
        Err(_) => false,
    }
}

#[derive(Deref)]
pub struct ProcessTarget(pub TargetCommon);

unsafe impl Send for ProcessTarget {}
unsafe impl Sync for ProcessTarget {}

impl ProcessTarget {
    pub fn open(pid: pid_t) -> UDbgResult<Arc<Self>> {
        let ps = Process::from_pid(pid)?;
        Ok(Arc::new(Self(TargetCommon::new(ps))))
    }

    pub fn insert_thread(&self, tid: tid_t) -> bool {
        if self.threads.write().insert(tid) {
            if let Err(err) = ptrace::setoptions(Pid::from_raw(tid), self.trace_opts) {
                udbg_ui().error(format!("ptrace_setopt {tid} {err:?}",));
            }
            true
        } else {
            false
        }
    }

    pub fn remove_thread(&self, tid: tid_t, s: i32, tb: &mut TraceBuf) -> bool {
        let mut threads = self.threads.write();
        if threads.remove(&tid) {
            tb.call(UEvent::ThreadExit(s as u32));
            if threads.is_empty() {
                tb.call(UEvent::ProcessExit(s as u32));
            }
        } else {
            udbg_ui().error(&format!("tid {tid} not found"));
        }
        threads.is_empty()
    }
}

impl WriteMemory for ProcessTarget {
    fn write_memory(&self, addr: usize, data: &[u8]) -> Option<usize> {
        self.process.write_memory(addr, data)
        // ptrace_write(self.pid.get(), addr, data);
        // Some(data.len())
    }
}

impl TargetMemory for ProcessTarget {
    fn enum_memory<'a>(&'a self) -> UDbgResult<Box<dyn Iterator<Item = MemoryPage> + 'a>> {
        self.0.enum_memory()
    }

    fn virtual_query(&self, address: usize) -> Option<MemoryPage> {
        self.update_memory_page_check_time();
        RangeValue::binary_search(&self.mem_pages.read().as_slice(), address).map(|r| r.clone())
    }

    fn collect_memory_info(&self) -> Vec<MemoryPage> {
        self.0.enum_memory().unwrap().collect::<Vec<_>>()
    }
}

impl GetProp for ProcessTarget {
    fn get_prop(&self, key: &str) -> UDbgResult<serde_value::Value> {
        // match key {
        //     "moduleTimeout" => { self.tc_module.duration.set(Duration::from_secs_f64(s.args(3))); }
        //     "memoryTimeout" => { self.tc_memory.duration.set(Duration::from_secs_f64(s.args(3))); }
        //     _ => {}
        // }
        Ok(Value::Unit)
    }
}

impl TargetControl for ProcessTarget {
    fn detach(&self) -> UDbgResult<()> {
        let attached = self.base.status.get() == UDbgStatus::Attached;
        self.base.status.set(UDbgStatus::Detaching);
        if attached {
            self.breakk()
        } else {
            Ok(())
        }
    }

    fn kill(&self) -> UDbgResult<()> {
        if unsafe { kill(self.process.pid, SIGKILL) } == 0 {
            Ok(())
        } else {
            Err(UDbgError::system())
        }
    }

    fn breakk(&self) -> UDbgResult<()> {
        self.base.check_attached()?;
        // for tid in self.enum_thread()? {
        //     if ptrace_interrupt(tid) {
        //         return Ok(());
        //     } else {
        //         println!("ptrace_interrupt({tid}) failed");
        //     }
        // }
        // return Err(UDbgError::system());
        Ok(nix::sys::signal::kill(
            Pid::from_raw(self.pid()),
            Signal::SIGSTOP,
        )?)
    }

    fn wait_exit(&self, timeout: Option<u32>) -> UDbgResult<Option<u32>> {
        match nix::sys::wait::waitpid(Pid::from_raw(self.pid()), None).context("wait")? {
            WaitStatus::Exited(_, code) => Ok(Some(code as _)),
            err => Err(anyhow::anyhow!("unexpected status: {err:?}").into()),
        }
    }

    fn suspend(&self) -> UDbgResult<()> {
        if self.status() == UDbgStatus::Detaching || self.status() == UDbgStatus::Attached {
            return Err(anyhow::anyhow!("target is attached").into());
        }

        Ok(nix::sys::signal::kill(
            Pid::from_raw(self.pid()),
            Signal::SIGSTOP,
        )?)
    }

    fn resume(&self) -> UDbgResult<()> {
        if self.status() == UDbgStatus::Detaching || self.status() == UDbgStatus::Attached {
            return Err(anyhow::anyhow!("target is attached").into());
        }

        Ok(nix::sys::signal::kill(
            Pid::from_raw(self.pid()),
            Signal::SIGCONT,
        )?)
    }
}

// impl TargetSymbol for ProcessTarget {
// }

impl Target for ProcessTarget {
    fn base(&self) -> &TargetBase {
        &self._base
    }

    fn process(&self) -> Option<&Process> {
        Some(&self.process)
    }

    fn enum_module<'a>(
        &'a self,
    ) -> UDbgResult<Box<dyn Iterator<Item = Arc<dyn UDbgModule + 'a>> + 'a>> {
        self.0.enum_module()
    }

    fn find_module(&self, module: usize) -> Option<Arc<dyn UDbgModule>> {
        let mut result = self.symgr.find_module(module);
        self.tc_module.check(|| {
            self.update_module();
            result = self.symgr.find_module(module);
        });
        Some(result?)
    }

    fn get_module(&self, module: &str) -> Option<Arc<dyn UDbgModule>> {
        Some(self.symgr.get_module(module).or_else(|| {
            self.0.update_module();
            self.symgr.get_module(module)
        })?)
    }

    fn open_thread(&self, tid: tid_t) -> UDbgResult<Box<dyn UDbgThread>> {
        let task = self.process.task_from_tid(tid).context("task")?;
        Ok(Box::new(NixThread {
            base: ThreadData { tid, wow64: false },
            stat: task.stat().context("stat")?,
        }))
    }

    fn enum_handle<'a>(&'a self) -> UDbgResult<Box<dyn Iterator<Item = HandleInfo> + 'a>> {
        self.0.enum_handle()
    }

    fn enum_thread(
        &self,
        detail: bool,
    ) -> UDbgResult<Box<dyn Iterator<Item = Box<dyn UDbgThread>> + '_>> {
        Ok(Box::new(
            self.process
                .tasks()?
                .filter_map(Result::ok)
                .filter_map(|task| {
                    Some(Box::new(NixThread::try_from(task).log_error("task stat")?)
                        as Box<dyn UDbgThread>)
                }),
        ))
    }
}

impl UDbgTarget for ProcessTarget {}

impl EventHandler for DefaultEngine {
    fn fetch(&mut self, buf: &mut TraceBuf) -> Option<()> {
        loop {
            self.status = waitpid(None, Some(WaitPidFlag::__WALL)).ok()?;
            // info!("[status] {:?}", self.status);
            self.tid = self
                .status
                .pid()
                .map(|p| p.as_raw() as tid_t)
                .unwrap_or_default();

            if matches!(
                self.status,
                WaitStatus::Stopped(_, _) //  | WaitStatus::Signaled(_, _, _)
            ) {
                buf.update_regs(self.tid);
                buf.update_siginfo(self.tid);
                // info!(
                //     "si: {:?}, address: {:p}, ip: {:x}",
                //     buf.si,
                //     unsafe { buf.si.si_addr() },
                //     *crate::register::AbstractRegs::ip(&mut buf.user)
                // );
            }

            let target = self
                .targets
                .iter()
                .find(|&t| self.tid == t.pid() as tid_t || t.threads.read().contains(&self.tid))
                .cloned()
                .or_else(|| {
                    self.targets
                        .iter()
                        .find(|&t| t.process.task_from_tid(self.tid).is_ok())
                        .cloned()
                });

            if let Some(target) = target {
                buf.target = target.clone();
                buf.target.base.event_tid.set(self.tid as _);

                if target.base.status.get() == UDbgStatus::Detaching {
                    break;
                }

                let mut cont = false;
                if target.base.status.get() < UDbgStatus::Attached {
                    target.base.status.set(UDbgStatus::Attached);
                    // buf.call(UEvent::ProcessCreate);
                    cont = true;
                }

                // set trace options for new thread
                if buf.target.insert_thread(self.tid) {
                    buf.call(UEvent::ThreadCreate(self.tid));
                    cont = true;
                }

                if cont {
                    ptrace::cont(Pid::from_raw(self.tid), None);
                    continue;
                }

                break;
            } else {
                udbg_ui().warn(format!("{} is not traced", self.tid));
                ptrace::cont(Pid::from_raw(self.tid), None);
            }
        }
        Some(())
    }

    fn handle(&mut self, buf: &mut TraceBuf) -> Option<HandleResult> {
        let status = self.status.clone();
        let this = buf.target.clone();
        let tid = self.tid;

        if this.base.status.get() == UDbgStatus::Detaching {
            return Some(None);
        }
        Some(match status {
            WaitStatus::Stopped(_, sig) => loop {
                if sig == Signal::SIGTRAP {
                    if let Some(result) = this
                        .handle_breakpoint(this.as_ref(), self, buf)
                        .log_error("handle trap")
                    {
                        break result;
                    }
                }
                break match buf.call(UEvent::Exception {
                    first: true,
                    code: sig as _,
                }) {
                    UserReply::Run(false) => Some(sig),
                    reply => {
                        this.handle_reply(this.as_ref(), reply, &mut buf.user);
                        None
                    }
                };
            },
            WaitStatus::PtraceEvent(_, sig, code) => {
                match code {
                    PTRACE_EVENT_STOP => {
                        this.insert_thread(tid);
                    }
                    PTRACE_EVENT_CLONE => {
                        let new_tid =
                            ptrace::getevent(Pid::from_raw(tid)).unwrap_or_default() as tid_t;
                        buf.call(UEvent::ThreadCreate(new_tid));
                        // trace new thread
                        ptrace::attach(Pid::from_raw(new_tid));
                    }
                    PTRACE_EVENT_FORK | PTRACE_EVENT_VFORK => {
                        let new_pid =
                            ptrace::getevent(Pid::from_raw(tid)).unwrap_or_default() as pid_t;
                        // info!("forked new pid: {new_pid}");
                        // let newpid = Pid::from_raw(new_pid);
                        // ptrace::detach(newpid, None);
                        // ptrace::cont(newpid, None);
                        ProcessTarget::open(new_pid)
                            .log_error("open child")
                            .map(|t| {
                                t.base.status.set(if udbg_ui().base().trace_child.get() {
                                    UDbgStatus::Attached
                                } else {
                                    UDbgStatus::Detaching
                                });
                                self.targets.push(t);
                            });
                    }
                    PTRACE_EVENT_EXEC => {
                        buf.call(UEvent::ProcessCreate);
                    }
                    _ => {}
                }
                None
            }
            // exited with exception
            WaitStatus::Signaled(_, sig, coredump) => {
                buf.call(UEvent::Exception {
                    first: false,
                    code: sig as _,
                });
                let code = ptrace::getevent(Pid::from_raw(self.tid)).unwrap_or(-1);
                if !matches!(sig, Signal::SIGSTOP) {
                    if this.remove_thread(tid, code as _, buf) {
                        self.targets.retain(|t| !Arc::ptr_eq(t, &this));
                    }
                }
                Some(sig)
            }
            // exited normally
            WaitStatus::Exited(_, code) => {
                if this.remove_thread(tid, code, buf) {
                    self.targets.retain(|t| !Arc::ptr_eq(t, &this));
                }
                None
            }
            _ => unreachable!("status: {status:?}"),
        })
    }

    fn cont(&mut self, sig: HandleResult, buf: &mut TraceBuf) {
        let this = buf.target.clone();
        let tid = Pid::from_raw(self.tid as _);

        if this.base.status.get() == UDbgStatus::Detaching {
            for bp in this.get_breakpoints() {
                bp.enable(false);
            }
            for &tid in this.threads.read().iter() {
                ptrace::detach(Pid::from_raw(tid as _), None)
                    .log_error_with(|err| format!("ptrace_detach({tid}) failed: {err:?}"));
            }
            self.targets.retain(|t| !Arc::ptr_eq(&this, t));
            this.base.status.set(UDbgStatus::Detached);
        } else if buf.regs_dirty {
            buf.regs_dirty = false;
            buf.write_regs(self.tid);
        }

        ptrace::cont(tid, sig);
    }
}

pub struct DefaultEngine {
    pub targets: Vec<Arc<ProcessTarget>>,
    pub status: WaitStatus,
    pub inited: bool,
    pub cloned_tids: HashSet<tid_t>,
    pub tid: tid_t,
}

impl Default for DefaultEngine {
    fn default() -> Self {
        Self {
            targets: Default::default(),
            status: WaitStatus::StillAlive,
            inited: false,
            tid: 0,
            cloned_tids: Default::default(),
        }
    }
}

impl UDbgEngine for DefaultEngine {
    fn open(&mut self, pid: pid_t) -> UDbgResult<Arc<dyn UDbgTarget>> {
        Ok(ProcessTarget::open(pid)?)
    }

    fn attach(&mut self, pid: pid_t) -> UDbgResult<Arc<dyn UDbgTarget>> {
        let this = ProcessTarget::open(pid)?;
        // attach each of threads
        for tid in this.process.tasks()?.filter_map(|t| t.ok().map(|t| t.tid)) {
            ptrace::attach(Pid::from_raw(tid)).with_context(|| format!("attach {tid}"))?;
        }
        // wait main thread
        waitpid(Pid::from_raw(pid), Some(WaitPidFlag::WUNTRACED))
            .with_context(|| format!("waitpid({pid})"))?;
        self.targets.push(this.clone());
        Ok(this)
    }

    fn create(
        &mut self,
        path: &str,
        cwd: Option<&str>,
        args: &[&str],
    ) -> UDbgResult<Arc<dyn UDbgTarget>> {
        match unsafe { libc::fork() } {
            0 => unsafe {
                use std::ffi::CString;
                ptrace::traceme();
                let path = CString::new(path).unwrap();
                let args = args
                    .iter()
                    .map(|&arg| CString::new(arg).unwrap())
                    .collect::<Vec<_>>();
                let mut argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>();
                argv.insert(0, path.as_ptr());
                argv.push(core::ptr::null());
                libc::execvp(path.as_ptr().cast(), argv.as_ptr());
                unreachable!();
            },
            -1 => Err(UDbgError::system()),
            pid => {
                waitpid(Pid::from_raw(pid), Some(WaitPidFlag::WUNTRACED))
                    .with_context(|| format!("waitpid({pid})"))?;
                let ps = Process::from_pid(pid).context("open")?;
                let this = Arc::new(ProcessTarget(TargetCommon::new(ps)));
                self.targets.push(this.clone());
                Ok(this)
            }
        }
    }

    fn event_loop<'a>(&mut self, callback: &mut UDbgCallback<'a>) -> UDbgResult<()> {
        self.targets.iter().for_each(|t| {
            t.update_module();
            t.update_memory_page();
        });

        let target = self
            .targets
            .iter()
            .next()
            .map(Clone::clone)
            .context("no attached target")?;

        self.tid = target.process.pid;
        let buf = &mut TraceBuf {
            callback,
            user: unsafe { core::mem::zeroed() },
            si: unsafe { core::mem::zeroed() },
            regs_dirty: false,
            target,
        };

        buf.target.base.event_tid.set(self.tid);
        buf.target.insert_thread(self.tid);

        if buf.target.base.status.get() == UDbgStatus::Detaching {
            self.cont(None, buf);
            return Ok(());
        }
        buf.target.base.status.set(UDbgStatus::Attached);

        buf.call(UEvent::InitBp);
        buf.call(UEvent::ProcessCreate);
        buf.call(UEvent::ThreadCreate(self.tid));
        self.cont(None, buf);

        while let Some(s) = self.fetch(buf).and_then(|_| self.handle(buf)) {
            self.cont(s, buf);
            if self.targets.is_empty() {
                break;
            }
        }

        Ok(())
    }
}