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
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::ffi::{CStr, CString};
use std::fmt;
use super::attachinfo::SBAttachInfo;
use super::breakpoint::SBBreakpoint;
use super::broadcaster::SBBroadcaster;
use super::debugger::SBDebugger;
use super::error::SBError;
use super::event::SBEvent;
use super::expressionoptions::SBExpressionOptions;
use super::filespec::SBFileSpec;
use super::launchinfo::SBLaunchInfo;
use super::module::SBModule;
use super::modulespec::SBModuleSpec;
use super::platform::SBPlatform;
use super::process::SBProcess;
use super::stream::SBStream;
use super::value::SBValue;
use super::watchpoint::SBWatchpoint;
use super::{DescriptionLevel, lldb_addr_t};
use sys;

/// The target program running under the debugger.
///
/// # Process Management
///
/// Starting a debug session is done by launching the target,
/// attaching to a running process, or loading a core file.
///
/// ## Launching
///
/// Launching a process can be done by creating and filling
/// out an [`SBLaunchInfo`] and calling [`launch`].
///
/// ```no_run
/// use lldb::*;
/// fn launch_target(target: &SBTarget) -> Result<SBProcess, SBError> {
///     let launch_info = SBLaunchInfo::new();
///     launch_info.set_launch_flags(LAUNCH_FLAG_STOP_AT_ENTRY);
///     // Probably want to set up a listener here.
///     target.launch(launch_info)
/// }
/// ```
///
/// ## Attaching
///
/// Attaching to a process can be done by creating and filling
/// out an [`SBAttachInfo`] and calling [`attach`].
///
/// ```no_run
/// use lldb::{lldb_pid_t, SBAttachInfo, SBError, SBProcess, SBTarget};
/// fn attach_to_pid(target: &SBTarget, pid: lldb_pid_t) -> Result<SBProcess, SBError> {
///     let attach_info = SBAttachInfo::new_with_pid(pid);
///     // Probably want to set up a listener here.
///     target.attach(attach_info)
/// }
/// ```
///
/// ## Core Files
///
/// ...
///
/// # Breakpoints and Watchpoints
///
/// ...
///
/// # Modules
///
/// ...
///
/// # Events
///
/// ...
///
/// [`SBLaunchInfo`]: struct.SBLaunchInfo.html
/// [`launch`]: #method.launch
/// [`SBAttachInfo`]: struct.SBAttachInfo.html
/// [`attach`]: #method.attach
pub struct SBTarget {
    /// The underlying raw `SBTargetRef`.
    pub raw: sys::SBTargetRef,
}

impl SBTarget {
    /// Construct a new `SBTarget`.
    pub fn wrap(raw: sys::SBTargetRef) -> SBTarget {
        SBTarget { raw: raw }
    }

    /// Construct a new `Some(SBTarget)` or `None`.
    pub fn maybe_wrap(raw: sys::SBTargetRef) -> Option<SBTarget> {
        if unsafe { sys::SBTargetIsValid(raw) != 0 } {
            Some(SBTarget { raw: raw })
        } else {
            None
        }
    }

    /// Check whether or not this is a valid `SBTarget` value.
    pub fn is_valid(&self) -> bool {
        unsafe { sys::SBTargetIsValid(self.raw) != 0 }
    }

    #[allow(missing_docs)]
    pub fn broadcaster_class_name() -> &'static str {
        unsafe {
            match CStr::from_ptr(sys::SBTargetGetBroadcasterClassName()).to_str() {
                Ok(s) => s,
                _ => panic!("Invalid string?"),
            }
        }
    }

    /// Get the [`SBPlatform`] associated with this target.
    ///
    /// After return, the platform object should be checked for validity.
    ///
    /// [`SBPlatform`]: strut.SBPlatform.html
    pub fn platform(&self) -> SBPlatform {
        unsafe { SBPlatform { raw: sys::SBTargetGetPlatform(self.raw) } }
    }

    /// Get the [`SBProcess`] associated with this target.
    ///
    /// [`SBProcess`]: strut.SBProcess.html
    pub fn process(&self) -> SBProcess {
        unsafe { SBProcess { raw: sys::SBTargetGetProcess(self.raw) } }
    }

    /// Launch a target for debugging.
    pub fn launch(&self, launch_info: SBLaunchInfo) -> Result<SBProcess, SBError> {
        let error: SBError = SBError::new();
        let process = SBProcess::wrap(unsafe {
            sys::SBTargetLaunch2(self.raw, launch_info.raw, error.raw)
        });
        if error.is_success() {
            Ok(process)
        } else {
            Err(error)
        }
    }

    #[allow(missing_docs)]
    pub fn attach(&self, attach_info: SBAttachInfo) -> Result<SBProcess, SBError> {
        let error: SBError = SBError::new();
        let process = SBProcess::wrap(unsafe {
            sys::SBTargetAttach(self.raw, attach_info.raw, error.raw)
        });
        if error.is_success() {
            Ok(process)
        } else {
            Err(error)
        }
    }

    /// Get a filespec for the executable.
    pub fn executable(&self) -> Option<SBFileSpec> {
        SBFileSpec::maybe_wrap(unsafe { sys::SBTargetGetExecutable(self.raw) })
    }

    /// Add a module to the target.
    pub fn add_module(&self, module: &SBModule) -> bool {
        unsafe { sys::SBTargetAddModule(self.raw, module.raw) != 0 }
    }

    /// Add a module to the target using an `SBModuleSpec`.
    pub fn add_module_spec(&self, module_spec: &SBModuleSpec) -> Option<SBModule> {
        SBModule::maybe_wrap(unsafe {
            sys::SBTargetAddModuleSpec(self.raw, module_spec.raw)
        })
    }

    /// Remove a module from the target.
    pub fn remove_module(&self, module: &SBModule) -> bool {
        unsafe { sys::SBTargetRemoveModule(self.raw, module.raw) != 0 }
    }

    /// Get the debugger controlling this target.
    pub fn debugger(&self) -> SBDebugger {
        SBDebugger { raw: unsafe { sys::SBTargetGetDebugger(self.raw) } }
    }

    /// Get an iterator over the [modules] known to this target instance.
    ///
    /// [modules]: struct.SBModule.html
    pub fn modules(&self) -> SBTargetModuleIter {
        SBTargetModuleIter {
            target: self,
            idx: 0,
        }
    }

    /// Find the module for the given `SBFileSpec`.
    pub fn find_module(&self, file_spec: &SBFileSpec) -> Option<SBModule> {
        SBModule::maybe_wrap(unsafe { sys::SBTargetFindModule(self.raw, file_spec.raw) })
    }

    #[allow(missing_docs)]
    pub fn delete_breakpoint(&self, break_id: i32) {
        unsafe { sys::SBTargetBreakpointDelete(self.raw, break_id) };
    }

    #[allow(missing_docs)]
    pub fn find_breakpoint_by_id(&self, break_id: i32) -> Option<SBBreakpoint> {
        SBBreakpoint::maybe_wrap(unsafe {
            sys::SBTargetFindBreakpointByID(self.raw, break_id)
        })
    }

    #[allow(missing_docs)]
    pub fn enable_all_breakpoints(&self) {
        unsafe { sys::SBTargetEnableAllBreakpoints(self.raw) };
    }

    #[allow(missing_docs)]
    pub fn disable_all_breakpoints(&self) {
        unsafe { sys::SBTargetDisableAllBreakpoints(self.raw) };
    }

    #[allow(missing_docs)]
    pub fn delete_all_breakpoints(&self) {
        unsafe { sys::SBTargetDeleteAllBreakpoints(self.raw) };
    }

    #[allow(missing_docs)]
    pub fn breakpoints(&self) -> SBTargetBreakpointIter {
        SBTargetBreakpointIter {
            target: self,
            idx: 0,
        }
    }

    #[allow(missing_docs)]
    pub fn delete_watchpoint(&self, watch_id: i32) {
        unsafe { sys::SBTargetDeleteWatchpoint(self.raw, watch_id) };
    }

    #[allow(missing_docs)]
    pub fn find_watchpoint_by_id(&self, watch_id: i32) -> Option<SBWatchpoint> {
        SBWatchpoint::maybe_wrap(unsafe {
            sys::SBTargetFindWatchpointByID(self.raw, watch_id)
        })
    }

    #[allow(missing_docs)]
    pub fn enable_all_watchpoints(&self) {
        unsafe { sys::SBTargetEnableAllWatchpoints(self.raw) };
    }

    #[allow(missing_docs)]
    pub fn disable_all_watchpoints(&self) {
        unsafe { sys::SBTargetDisableAllWatchpoints(self.raw) };
    }

    #[allow(missing_docs)]
    pub fn delete_all_watchpoints(&self) {
        unsafe { sys::SBTargetDeleteAllWatchpoints(self.raw) };
    }

    #[allow(missing_docs)]
    pub fn watch_address(
        &self,
        addr: lldb_addr_t,
        size: usize,
        read: bool,
        write: bool,
    ) -> Result<SBWatchpoint, SBError> {
        let error: SBError = SBError::new();
        let watchpoint = unsafe {
            sys::SBTargetWatchAddress(self.raw, addr, size, read as u8, write as u8, error.raw)
        };
        if error.is_success() {
            Ok(SBWatchpoint::wrap(watchpoint))
        } else {
            Err(error)
        }
    }

    #[allow(missing_docs)]
    pub fn watchpoints(&self) -> SBTargetWatchpointIter {
        SBTargetWatchpointIter {
            target: self,
            idx: 0,
        }
    }

    #[allow(missing_docs)]
    pub fn broadcaster(&self) -> SBBroadcaster {
        SBBroadcaster::wrap(unsafe { sys::SBTargetGetBroadcaster(self.raw) })
    }

    /// Evaluate an expression.
    pub fn evaluate_expression(&self, expression: &str, options: &SBExpressionOptions) -> SBValue {
        let expression = CString::new(expression).unwrap();
        SBValue::wrap(unsafe {
            sys::SBTargetEvaluateExpression(self.raw, expression.as_ptr(), options.raw)
        })
    }

    #[allow(missing_docs)]
    pub fn event_as_target_event(event: &SBEvent) -> Option<SBTargetEvent> {
        if unsafe { sys::SBTargetEventIsTargetEvent(event.raw) != 0 } {
            Some(SBTargetEvent::new(event))
        } else {
            None
        }
    }
}

impl fmt::Debug for SBTarget {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        let stream = SBStream::new();
        unsafe { sys::SBTargetGetDescription(self.raw, stream.raw, DescriptionLevel::Brief) };
        write!(fmt, "SBTarget {{ {} }}", stream.data())
    }
}

impl Drop for SBTarget {
    fn drop(&mut self) {
        unsafe { sys::DisposeSBTarget(self.raw) };
    }
}

/// Iterate over the [breakpoints] in a [target].
///
/// [breakpoints]: struct.SBBreakpoint.html
/// [target]: struct.SBTarget.html
pub struct SBTargetBreakpointIter<'d> {
    target: &'d SBTarget,
    idx: usize,
}

impl<'d> Iterator for SBTargetBreakpointIter<'d> {
    type Item = SBBreakpoint;

    fn next(&mut self) -> Option<SBBreakpoint> {
        if self.idx < unsafe { sys::SBTargetGetNumBreakpoints(self.target.raw) as usize } {
            let r = Some(SBBreakpoint::wrap(unsafe {
                sys::SBTargetGetBreakpointAtIndex(self.target.raw, self.idx as u32)
            }));
            self.idx += 1;
            r
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let sz = unsafe { sys::SBTargetGetNumBreakpoints(self.target.raw) } as usize;
        (sz - self.idx, Some(sz))
    }
}

/// Iterate over the [watchpoints] in a [target].
///
/// [watchpoints]: struct.SBWatchpoint.html
/// [target]: struct.SBTarget.html
pub struct SBTargetWatchpointIter<'d> {
    target: &'d SBTarget,
    idx: usize,
}

impl<'d> Iterator for SBTargetWatchpointIter<'d> {
    type Item = SBWatchpoint;

    fn next(&mut self) -> Option<SBWatchpoint> {
        if self.idx < unsafe { sys::SBTargetGetNumWatchpoints(self.target.raw) as usize } {
            let r = Some(SBWatchpoint::wrap(unsafe {
                sys::SBTargetGetWatchpointAtIndex(self.target.raw, self.idx as u32)
            }));
            self.idx += 1;
            r
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let sz = unsafe { sys::SBTargetGetNumWatchpoints(self.target.raw) } as usize;
        (sz - self.idx, Some(sz))
    }
}

#[allow(missing_docs)]
pub struct SBTargetEvent<'e> {
    event: &'e SBEvent,
}

#[allow(missing_docs)]
impl<'e> SBTargetEvent<'e> {
    pub fn new(event: &'e SBEvent) -> Self {
        SBTargetEvent { event: event }
    }

    pub fn target(&self) -> SBTarget {
        SBTarget::wrap(unsafe { sys::SBTargetGetTargetFromEvent(self.event.raw) })
    }

    pub fn modules(&self) -> SBTargetEventModuleIter {
        SBTargetEventModuleIter {
            event: self,
            idx: 0,
        }
    }
}

/// Iterate over the [modules] referenced from a [target event].
///
/// [modules]: struct.SBModule.html
/// [target event]: struct.SBTargetEvent.html
pub struct SBTargetEventModuleIter<'d> {
    event: &'d SBTargetEvent<'d>,
    idx: usize,
}

impl<'d> Iterator for SBTargetEventModuleIter<'d> {
    type Item = SBModule;

    fn next(&mut self) -> Option<SBModule> {
        if self.idx <
            unsafe { sys::SBTargetGetNumModulesFromEvent(self.event.event.raw) as usize }
        {
            let r = Some(SBModule::wrap(unsafe {
                sys::SBTargetGetModuleAtIndexFromEvent(self.idx as u32, self.event.event.raw)
            }));
            self.idx += 1;
            r
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let sz = unsafe { sys::SBTargetGetNumModulesFromEvent(self.event.event.raw) } as usize;
        (sz - self.idx, Some(sz))
    }
}

/// Iterate over the [modules] in a [target].
///
/// [modules]: struct.SBModule.html
/// [target]: struct.SBTarget.html
pub struct SBTargetModuleIter<'d> {
    target: &'d SBTarget,
    idx: u32,
}

impl<'d> Iterator for SBTargetModuleIter<'d> {
    type Item = SBModule;

    fn next(&mut self) -> Option<SBModule> {
        if self.idx < unsafe { sys::SBTargetGetNumModules(self.target.raw) } {
            let r = Some(SBModule::wrap(unsafe {
                sys::SBTargetGetModuleAtIndex(self.target.raw, self.idx)
            }));
            self.idx += 1;
            r
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let sz = unsafe { sys::SBTargetGetNumModules(self.target.raw) } as usize;
        (sz - self.idx as usize, Some(sz))
    }
}

#[cfg(feature = "graphql")]
graphql_object!(SBTarget: SBDebugger | &self | {
    field is_valid() -> bool {
        self.is_valid()
    }

    field platform() -> SBPlatform {
        self.platform()
    }

    field process() -> SBProcess {
        self.process()
    }

    field executable() -> Option<SBFileSpec> {
        self.executable()
    }

    field debugger() -> SBDebugger {
        self.debugger()
    }

    field breakpoints() -> Vec<SBBreakpoint> {
        self.breakpoints().collect()
    }

    field watchpoints() -> Vec<SBWatchpoint> {
        self.watchpoints().collect()
    }
});