aboutsummaryrefslogtreecommitdiff
path: root/src/stub/core_impl/base.rs
blob: 91102976106ed38e796070564d77d7929b078610 (plain)
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
use super::prelude::*;
use super::DisconnectReason;
use crate::arch::Arch;
use crate::arch::Registers;
use crate::common::Pid;
use crate::common::Tid;
use crate::protocol::commands::ext::Base;
use crate::protocol::IdKind;
use crate::protocol::SpecificIdKind;
use crate::protocol::SpecificThreadId;
use crate::target::ext::base::BaseOps;
use crate::target::ext::base::ResumeOps;
use crate::FAKE_PID;
use crate::SINGLE_THREAD_TID;

impl<T: Target, C: Connection> GdbStubImpl<T, C> {
    #[inline(always)]
    fn get_sane_any_tid(
        &mut self,
        target: &mut T,
    ) -> Result<Option<Tid>, Error<T::Error, C::Error>> {
        let tid = match target.base_ops() {
            BaseOps::SingleThread(_) => Some(SINGLE_THREAD_TID),
            BaseOps::MultiThread(ops) => {
                let mut first_tid = None;
                ops.list_active_threads(&mut |tid| {
                    if first_tid.is_none() {
                        first_tid = Some(tid);
                    }
                })
                .map_err(Error::TargetError)?;
                // It is possible for this to be `None` in the case where the target has
                // not yet called `register_thread()`. This can happen, for example, if
                // there are no active threads in the current target process.
                first_tid
            }
        };
        Ok(tid)
    }

    pub(crate) fn get_current_pid(
        &mut self,
        target: &mut T,
    ) -> Result<Pid, Error<T::Error, C::Error>> {
        if let Some(ops) = target
            .support_extended_mode()
            .and_then(|ops| ops.support_current_active_pid())
        {
            ops.current_active_pid().map_err(Error::TargetError)
        } else {
            Ok(FAKE_PID)
        }
    }

    // Used by `?` and `vAttach` to return a "reasonable" stop reason.
    //
    // This is a bit of an implementation wart, since this is really something
    // the user ought to be able to customize.
    //
    // Works fine for now though...
    pub(crate) fn report_reasonable_stop_reason(
        &mut self,
        res: &mut ResponseWriter<'_, C>,
        target: &mut T,
    ) -> Result<HandlerStatus, Error<T::Error, C::Error>> {
        // Reply with a valid thread-id or GDB issues a warning when more
        // than one thread is active
        if let Some(tid) = self.get_sane_any_tid(target)? {
            res.write_str("T05thread:")?;
            res.write_specific_thread_id(SpecificThreadId {
                pid: self
                    .features
                    .multiprocess()
                    .then_some(SpecificIdKind::WithId(self.get_current_pid(target)?)),
                tid: SpecificIdKind::WithId(tid),
            })?;
        } else {
            res.write_str("W00")?;
        }
        res.write_str(";")?;
        Ok(HandlerStatus::Handled)
    }

    pub(crate) fn handle_base(
        &mut self,
        res: &mut ResponseWriter<'_, C>,
        target: &mut T,
        command: Base<'_>,
    ) -> Result<HandlerStatus, Error<T::Error, C::Error>> {
        let handler_status = match command {
            // ------------------ Handshaking and Queries ------------------- //
            Base::qSupported(cmd) => {
                use crate::protocol::commands::_qSupported::Feature;

                // perform incoming feature negotiation
                for feature in cmd.features.into_iter() {
                    let (feature, supported) = match feature {
                        Ok(Some(v)) => v,
                        Ok(None) => continue,
                        Err(()) => {
                            return Err(Error::PacketParse(
                                crate::protocol::PacketParseError::MalformedCommand,
                            ))
                        }
                    };

                    match feature {
                        Feature::Multiprocess => self.features.set_multiprocess(supported),
                    }
                }

                res.write_str("PacketSize=")?;
                res.write_num(cmd.packet_buffer_len)?;

                // these are the few features that gdbstub unconditionally supports
                res.write_str(concat!(";vContSupported+", ";multiprocess+",))?;

                if target.use_no_ack_mode() {
                    res.write_str(";QStartNoAckMode+")?;
                }

                if let Some(resume_ops) = target.base_ops().resume_ops() {
                    let (reverse_cont, reverse_step) = match resume_ops {
                        ResumeOps::MultiThread(ops) => (
                            ops.support_reverse_cont().is_some(),
                            ops.support_reverse_step().is_some(),
                        ),
                        ResumeOps::SingleThread(ops) => (
                            ops.support_reverse_cont().is_some(),
                            ops.support_reverse_step().is_some(),
                        ),
                    };

                    if reverse_cont {
                        res.write_str(";ReverseContinue+")?;
                    }

                    if reverse_step {
                        res.write_str(";ReverseStep+")?;
                    }
                }

                if let Some(ops) = target.support_extended_mode() {
                    if ops.support_configure_aslr().is_some() {
                        res.write_str(";QDisableRandomization+")?;
                    }

                    if ops.support_configure_env().is_some() {
                        res.write_str(";QEnvironmentHexEncoded+")?;
                        res.write_str(";QEnvironmentUnset+")?;
                        res.write_str(";QEnvironmentReset+")?;
                    }

                    if ops.support_configure_startup_shell().is_some() {
                        res.write_str(";QStartupWithShell+")?;
                    }

                    if ops.support_configure_working_dir().is_some() {
                        res.write_str(";QSetWorkingDir+")?;
                    }
                }

                if let Some(ops) = target.support_breakpoints() {
                    if ops.support_sw_breakpoint().is_some() {
                        res.write_str(";swbreak+")?;
                    }

                    if ops.support_hw_breakpoint().is_some()
                        || ops.support_hw_watchpoint().is_some()
                    {
                        res.write_str(";hwbreak+")?;
                    }
                }

                if target.support_catch_syscalls().is_some() {
                    res.write_str(";QCatchSyscalls+")?;
                }

                if target.use_target_description_xml()
                    && (T::Arch::target_description_xml().is_some()
                        || target.support_target_description_xml_override().is_some())
                {
                    res.write_str(";qXfer:features:read+")?;
                }

                if target.support_memory_map().is_some() {
                    res.write_str(";qXfer:memory-map:read+")?;
                }

                if target.support_exec_file().is_some() {
                    res.write_str(";qXfer:exec-file:read+")?;
                }

                if target.support_auxv().is_some() {
                    res.write_str(";qXfer:auxv:read+")?;
                }

                HandlerStatus::Handled
            }

            // -------------------- "Core" Functionality -------------------- //
            Base::QuestionMark(_) => {
                // TODO: Improve the '?' response.
                // this will be particularly relevant when working on non-stop mode.
                self.report_reasonable_stop_reason(res, target)?
            }
            Base::qAttached(cmd) => {
                let is_attached = match target.support_extended_mode() {
                    // when _not_ running in extended mode, just report that we're attaching to an
                    // existing process.
                    None => true, // assume attached to an existing process
                    // When running in extended mode, we must defer to the target
                    Some(ops) => {
                        match cmd.pid {
                            Some(pid) => ops.query_if_attached(pid).handle_error()?.was_attached(),
                            None => true, // assume attached to an existing process
                        }
                    }
                };
                res.write_str(if is_attached { "1" } else { "0" })?;
                HandlerStatus::Handled
            }
            Base::g(_) => {
                let mut regs: <T::Arch as Arch>::Registers = Default::default();
                match target.base_ops() {
                    BaseOps::SingleThread(ops) => ops.read_registers(&mut regs),
                    BaseOps::MultiThread(ops) => {
                        ops.read_registers(&mut regs, self.current_mem_tid)
                    }
                }
                .handle_error()?;

                let mut err = Ok(());
                regs.gdb_serialize(|val| {
                    let res = match val {
                        Some(b) => res.write_hex_buf(&[b]),
                        None => res.write_str("xx"),
                    };
                    if let Err(e) = res {
                        err = Err(e);
                    }
                });
                err?;
                HandlerStatus::Handled
            }
            Base::G(cmd) => {
                let mut regs: <T::Arch as Arch>::Registers = Default::default();
                regs.gdb_deserialize(cmd.vals)
                    .map_err(|_| Error::TargetMismatch)?;

                match target.base_ops() {
                    BaseOps::SingleThread(ops) => ops.write_registers(&regs),
                    BaseOps::MultiThread(ops) => ops.write_registers(&regs, self.current_mem_tid),
                }
                .handle_error()?;

                HandlerStatus::NeedsOk
            }
            Base::m(cmd) => {
                let buf = cmd.buf;
                let addr = <T::Arch as Arch>::Usize::from_be_bytes(cmd.addr)
                    .ok_or(Error::TargetMismatch)?;

                let mut i = 0;
                let mut n = cmd.len;
                while n != 0 {
                    let chunk_size = n.min(buf.len());

                    use num_traits::NumCast;

                    let addr = addr + NumCast::from(i).ok_or(Error::TargetMismatch)?;
                    let data = &mut buf[..chunk_size];
                    let data_len = match target.base_ops() {
                        BaseOps::SingleThread(ops) => ops.read_addrs(addr, data),
                        BaseOps::MultiThread(ops) => {
                            ops.read_addrs(addr, data, self.current_mem_tid)
                        }
                    }
                    .handle_error()?;

                    n -= chunk_size;
                    i += chunk_size;

                    // TODO: add more specific error variant?
                    let data = data.get(..data_len).ok_or(Error::PacketBufferOverflow)?;
                    res.write_hex_buf(data)?;
                }
                HandlerStatus::Handled
            }
            Base::M(cmd) => {
                let addr = <T::Arch as Arch>::Usize::from_be_bytes(cmd.addr)
                    .ok_or(Error::TargetMismatch)?;

                match target.base_ops() {
                    BaseOps::SingleThread(ops) => ops.write_addrs(addr, cmd.val),
                    BaseOps::MultiThread(ops) => {
                        ops.write_addrs(addr, cmd.val, self.current_mem_tid)
                    }
                }
                .handle_error()?;

                HandlerStatus::NeedsOk
            }
            Base::k(_) | Base::vKill(_) => {
                match target.support_extended_mode() {
                    // When not running in extended mode, stop the `GdbStub` and disconnect.
                    None => HandlerStatus::Disconnect(DisconnectReason::Kill),

                    // When running in extended mode, a kill command does not necessarily result in
                    // a disconnect...
                    Some(ops) => {
                        let pid = match command {
                            Base::vKill(cmd) => Some(cmd.pid),
                            _ => None,
                        };

                        let should_terminate = ops.kill(pid).handle_error()?;
                        if should_terminate.into_bool() {
                            // manually write OK, since we need to return a DisconnectReason
                            res.write_str("OK")?;
                            HandlerStatus::Disconnect(DisconnectReason::Kill)
                        } else {
                            HandlerStatus::NeedsOk
                        }
                    }
                }
            }
            Base::D(_) => {
                // TODO: plumb-through Pid when exposing full multiprocess + extended mode
                res.write_str("OK")?; // manually write OK, since we need to return a DisconnectReason
                HandlerStatus::Disconnect(DisconnectReason::Disconnect)
            }

            // ------------------- Multi-threading Support ------------------ //
            Base::H(cmd) => {
                use crate::protocol::commands::_h_upcase::Op;
                match cmd.kind {
                    Op::Other => match cmd.thread.tid {
                        IdKind::Any => match self.get_sane_any_tid(target)? {
                            Some(tid) => self.current_mem_tid = tid,
                            None => {
                                return Err(Error::NonFatalError(1));
                            }
                        },
                        // "All" threads doesn't make sense for memory accesses
                        IdKind::All => return Err(Error::PacketUnexpected),
                        IdKind::WithId(tid) => self.current_mem_tid = tid,
                    },
                    // technically, this variant is deprecated in favor of vCont...
                    Op::StepContinue => match cmd.thread.tid {
                        IdKind::Any => match self.get_sane_any_tid(target)? {
                            Some(tid) => self.current_resume_tid = SpecificIdKind::WithId(tid),
                            None => {
                                return Err(Error::NonFatalError(1));
                            }
                        },
                        IdKind::All => self.current_resume_tid = SpecificIdKind::All,
                        IdKind::WithId(tid) => {
                            self.current_resume_tid = SpecificIdKind::WithId(tid)
                        }
                    },
                }
                HandlerStatus::NeedsOk
            }
            Base::qfThreadInfo(_) => {
                res.write_str("m")?;
                let pid = self.get_current_pid(target)?;

                match target.base_ops() {
                    BaseOps::SingleThread(_) => res.write_specific_thread_id(SpecificThreadId {
                        pid: self
                            .features
                            .multiprocess()
                            .then_some(SpecificIdKind::WithId(pid)),
                        tid: SpecificIdKind::WithId(SINGLE_THREAD_TID),
                    })?,
                    BaseOps::MultiThread(ops) => {
                        let mut err: Result<_, Error<T::Error, C::Error>> = Ok(());
                        let mut first = true;
                        ops.list_active_threads(&mut |tid| {
                            // TODO: replace this with a try block (once stabilized)
                            let e = (|| {
                                if !first {
                                    res.write_str(",")?
                                }
                                first = false;
                                res.write_specific_thread_id(SpecificThreadId {
                                    pid: self
                                        .features
                                        .multiprocess()
                                        .then_some(SpecificIdKind::WithId(pid)),
                                    tid: SpecificIdKind::WithId(tid),
                                })?;
                                Ok(())
                            })();

                            if let Err(e) = e {
                                err = Err(e)
                            }
                        })
                        .map_err(Error::TargetError)?;
                        err?;
                    }
                }

                HandlerStatus::Handled
            }
            Base::qsThreadInfo(_) => {
                res.write_str("l")?;
                HandlerStatus::Handled
            }
            Base::T(cmd) => {
                let alive = match cmd.thread.tid {
                    IdKind::WithId(tid) => match target.base_ops() {
                        BaseOps::SingleThread(_) => tid == SINGLE_THREAD_TID,
                        BaseOps::MultiThread(ops) => {
                            ops.is_thread_alive(tid).map_err(Error::TargetError)?
                        }
                    },
                    _ => return Err(Error::PacketUnexpected),
                };
                if alive {
                    HandlerStatus::NeedsOk
                } else {
                    // any error code will do
                    return Err(Error::NonFatalError(1));
                }
            }
        };
        Ok(handler_status)
    }
}