binaryninja/
workflow.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
use binaryninjacore_sys::*;

// Needed for documentation.
#[allow(unused)]
use crate::binary_view::{memory_map::MemoryMap, BinaryViewBase, BinaryViewExt};

use crate::basic_block::BasicBlock;
use crate::binary_view::{AddressRange, BinaryView};
use crate::flowgraph::FlowGraph;
use crate::function::{Function, NativeBlock};
use crate::high_level_il::HighLevelILFunction;
use crate::low_level_il::{LowLevelILMutableFunction, LowLevelILRegularFunction};
use crate::medium_level_il::MediumLevelILFunction;
use crate::rc::{Array, CoreArrayProvider, CoreArrayProviderInner, Guard, Ref, RefCountable};
use crate::section::Section;
use crate::segment::{Segment, SegmentFlags};
use crate::string::{BnString, IntoCStr};
use std::ffi::c_char;
use std::ptr;
use std::ptr::NonNull;

pub mod activity;
pub use activity::Activity;

#[repr(transparent)]
/// The AnalysisContext struct is used to represent the current state of
/// analysis for a given function. It allows direct modification of IL and other
/// analysis information.
pub struct AnalysisContext {
    handle: NonNull<BNAnalysisContext>,
}

impl AnalysisContext {
    pub(crate) unsafe fn from_raw(handle: NonNull<BNAnalysisContext>) -> Self {
        Self { handle }
    }

    #[allow(unused)]
    pub(crate) unsafe fn ref_from_raw(handle: NonNull<BNAnalysisContext>) -> Ref<Self> {
        Ref::new(Self { handle })
    }

    /// BinaryView for the current AnalysisContext
    pub fn view(&self) -> Ref<BinaryView> {
        let result = unsafe { BNAnalysisContextGetBinaryView(self.handle.as_ptr()) };
        assert!(!result.is_null());
        unsafe { BinaryView::ref_from_raw(result) }
    }

    /// [`Function`] for the current AnalysisContext
    pub fn function(&self) -> Ref<Function> {
        let result = unsafe { BNAnalysisContextGetFunction(self.handle.as_ptr()) };
        assert!(!result.is_null());
        unsafe { Function::ref_from_raw(result) }
    }

    /// [`LowLevelILMutableFunction`] used to represent Lifted Level IL
    pub unsafe fn lifted_il_function(&self) -> Option<Ref<LowLevelILMutableFunction>> {
        let result = unsafe { BNAnalysisContextGetLiftedILFunction(self.handle.as_ptr()) };
        unsafe {
            Some(LowLevelILMutableFunction::ref_from_raw(
                NonNull::new(result)?.as_ptr(),
            ))
        }
    }

    pub fn set_lifted_il_function(&self, value: &LowLevelILRegularFunction) {
        unsafe { BNSetLiftedILFunction(self.handle.as_ptr(), value.handle) }
    }

    /// [`LowLevelILMutableFunction`] used to represent Low Level IL
    pub unsafe fn llil_function(&self) -> Option<Ref<LowLevelILMutableFunction>> {
        let result = unsafe { BNAnalysisContextGetLowLevelILFunction(self.handle.as_ptr()) };
        unsafe {
            Some(LowLevelILMutableFunction::ref_from_raw(
                NonNull::new(result)?.as_ptr(),
            ))
        }
    }

    pub fn set_llil_function(&self, value: &LowLevelILRegularFunction) {
        unsafe { BNSetLowLevelILFunction(self.handle.as_ptr(), value.handle) }
    }

    /// [`MediumLevelILFunction`] used to represent Medium Level IL
    pub fn mlil_function(&self) -> Option<Ref<MediumLevelILFunction>> {
        let result = unsafe { BNAnalysisContextGetMediumLevelILFunction(self.handle.as_ptr()) };
        unsafe {
            Some(MediumLevelILFunction::ref_from_raw(
                NonNull::new(result)?.as_ptr(),
            ))
        }
    }

    pub fn set_mlil_function(&self, value: &MediumLevelILFunction) {
        // TODO: Mappings FFI
        unsafe {
            BNSetMediumLevelILFunction(
                self.handle.as_ptr(),
                value.handle,
                ptr::null_mut(),
                0,
                ptr::null_mut(),
                0,
            )
        }
    }

    /// [`HighLevelILFunction`] used to represent High Level IL
    pub fn hlil_function(&self, full_ast: bool) -> Option<Ref<HighLevelILFunction>> {
        let result = unsafe { BNAnalysisContextGetHighLevelILFunction(self.handle.as_ptr()) };
        unsafe {
            Some(HighLevelILFunction::ref_from_raw(
                NonNull::new(result)?.as_ptr(),
                full_ast,
            ))
        }
    }

    pub fn inform(&self, request: &str) -> bool {
        let request = request.to_cstr();
        unsafe { BNAnalysisContextInform(self.handle.as_ptr(), request.as_ptr()) }
    }

    pub fn set_basic_blocks<I>(&self, blocks: I)
    where
        I: IntoIterator<Item = BasicBlock<NativeBlock>>,
    {
        let blocks: Vec<_> = blocks.into_iter().collect();
        let mut blocks_raw: Vec<*mut BNBasicBlock> =
            blocks.iter().map(|block| block.handle).collect();
        unsafe { BNSetBasicBlockList(self.handle.as_ptr(), blocks_raw.as_mut_ptr(), blocks.len()) }
    }

    // Settings cache access - lock-free access to cached settings

    /// Get a boolean setting from the cached settings
    pub fn get_setting_bool(&self, key: &str) -> bool {
        let key = key.to_cstr();
        unsafe { BNAnalysisContextGetSettingBool(self.handle.as_ptr(), key.as_ptr()) }
    }

    /// Get a double setting from the cached settings
    pub fn get_setting_double(&self, key: &str) -> f64 {
        let key = key.to_cstr();
        unsafe { BNAnalysisContextGetSettingDouble(self.handle.as_ptr(), key.as_ptr()) }
    }

    /// Get a signed 64-bit integer setting from the cached settings
    pub fn get_setting_int64(&self, key: &str) -> i64 {
        let key = key.to_cstr();
        unsafe { BNAnalysisContextGetSettingInt64(self.handle.as_ptr(), key.as_ptr()) }
    }

    /// Get an unsigned 64-bit integer setting from the cached settings
    pub fn get_setting_uint64(&self, key: &str) -> u64 {
        let key = key.to_cstr();
        unsafe { BNAnalysisContextGetSettingUInt64(self.handle.as_ptr(), key.as_ptr()) }
    }

    /// Get a string setting from the cached settings
    pub fn get_setting_string(&self, key: &str) -> BnString {
        let key = key.to_cstr();
        unsafe {
            let result = BNAnalysisContextGetSettingString(self.handle.as_ptr(), key.as_ptr());
            BnString::from_raw(result)
        }
    }

    /// Get a string list setting from the cached settings
    pub fn get_setting_string_list(&self, key: &str) -> Array<BnString> {
        let key = key.to_cstr();
        unsafe {
            let mut count = 0;
            let result = BNAnalysisContextGetSettingStringList(
                self.handle.as_ptr(),
                key.as_ptr(),
                &mut count,
            );
            Array::new(result, count, ())
        }
    }

    /// Check if an offset is mapped in the cached [`MemoryMap`].
    ///
    /// NOTE: This is a lock-free alternative to [`BinaryView::offset_valid`].
    pub fn is_offset_valid(&self, offset: u64) -> bool {
        unsafe { BNAnalysisContextIsValidOffset(self.handle.as_ptr(), offset) }
    }

    /// Check if an offset is readable in the cached [`MemoryMap`].
    ///
    /// NOTE: This is a lock-free alternative to [`BinaryView::offset_readable`].
    pub fn is_offset_readable(&self, offset: u64) -> bool {
        unsafe { BNAnalysisContextIsOffsetReadable(self.handle.as_ptr(), offset) }
    }

    /// Check if an offset is writable in the cached [`MemoryMap`].
    ///
    /// NOTE: This is a lock-free alternative to [`BinaryView::offset_writable`].
    pub fn is_offset_writable(&self, offset: u64) -> bool {
        unsafe { BNAnalysisContextIsOffsetWritable(self.handle.as_ptr(), offset) }
    }

    /// Check if an offset is executable in the cached [`MemoryMap`].
    ///
    /// NOTE: This is a lock-free alternative to [`BinaryView::offset_executable`].
    pub fn is_offset_executable(&self, offset: u64) -> bool {
        unsafe { BNAnalysisContextIsOffsetExecutable(self.handle.as_ptr(), offset) }
    }

    /// Check if an offset is backed by file in the cached [`MemoryMap`].
    ///
    /// NOTE: This is a lock-free alternative to [`BinaryView::offset_backed_by_file`].
    pub fn is_offset_backed_by_file(&self, offset: u64) -> bool {
        unsafe { BNAnalysisContextIsOffsetBackedByFile(self.handle.as_ptr(), offset) }
    }

    /// Check if an offset has code semantics in the cached section map.
    ///
    /// NOTE: This is a lock-free alternative to [`BinaryViewExt::offset_has_code_semantics`].
    pub fn is_offset_code_semantics(&self, offset: u64) -> bool {
        unsafe { BNAnalysisContextIsOffsetCodeSemantics(self.handle.as_ptr(), offset) }
    }

    /// Check if an offset has external semantics in the cached section map.
    ///
    /// NOTE: This is a lock-free alternative to [`BinaryViewExt::offset_has_extern_semantics`].
    pub fn is_offset_extern_semantics(&self, offset: u64) -> bool {
        unsafe { BNAnalysisContextIsOffsetExternSemantics(self.handle.as_ptr(), offset) }
    }

    /// Check if an offset has writable semantics in the cached section map.
    ///
    /// NOTE: This is a lock-free alternative to [`BinaryViewExt::offset_has_writable_semantics`].
    pub fn is_offset_writable_semantics(&self, offset: u64) -> bool {
        unsafe { BNAnalysisContextIsOffsetWritableSemantics(self.handle.as_ptr(), offset) }
    }

    /// Check if an offset has read-only semantics in the cached section map.
    ///
    /// NOTE: This is a lock-free alternative to [`BinaryViewExt::offset_has_read_only_semantics`].
    pub fn is_offset_readonly_semantics(&self, offset: u64) -> bool {
        unsafe { BNAnalysisContextIsOffsetReadOnlySemantics(self.handle.as_ptr(), offset) }
    }

    /// Get all sections from the cached section map.
    ///
    /// NOTE: This is a lock-free alternative to [`BinaryViewExt::sections`].
    pub fn sections(&self) -> Array<Section> {
        unsafe {
            let mut count = 0;
            let sections = BNAnalysisContextGetSections(self.handle.as_ptr(), &mut count);
            Array::new(sections, count, ())
        }
    }

    /// Get a section by name from the cached section map.
    ///
    /// NOTE: This is a lock-free alternative to [`BinaryViewExt::section_by_name`].
    pub fn section_by_name(&self, name: impl IntoCStr) -> Option<Ref<Section>> {
        unsafe {
            let raw_name = name.to_cstr();
            let name_ptr = raw_name.as_ptr();
            let raw_section_ptr = BNAnalysisContextGetSectionByName(self.handle.as_ptr(), name_ptr);
            match raw_section_ptr.is_null() {
                false => Some(Section::ref_from_raw(raw_section_ptr)),
                true => None,
            }
        }
    }

    /// Get all sections containing the given address from the cached section map.
    ///
    /// NOTE: This is a lock-free alternative to [`BinaryViewExt::sections_at`].
    pub fn sections_at(&self, addr: u64) -> Array<Section> {
        unsafe {
            let mut count = 0;
            let sections = BNAnalysisContextGetSectionsAt(self.handle.as_ptr(), addr, &mut count);
            Array::new(sections, count, ())
        }
    }

    /// Get the start address (the lowest address) from the cached [`MemoryMap`].
    ///
    /// NOTE: This is a lock-free alternative to [`BinaryView::start`].
    pub fn start(&self) -> u64 {
        unsafe { BNAnalysisContextGetStart(self.handle.as_ptr()) }
    }

    /// Get the end address (the highest address) from the cached [`MemoryMap`].
    ///
    /// NOTE: This is a lock-free alternative to [`BinaryViewExt::end`].
    pub fn end(&self) -> u64 {
        unsafe { BNAnalysisContextGetEnd(self.handle.as_ptr()) }
    }

    /// Get the length of the cached [`MemoryMap`].
    ///
    /// NOTE: This is a lock-free alternative to [`BinaryViewBase::len`].
    pub fn length(&self) -> u64 {
        unsafe { BNAnalysisContextGetLength(self.handle.as_ptr()) }
    }

    /// Get the next valid offset after the given offset from the cached [`MemoryMap`].
    ///
    /// NOTE: This is a lock-free alternative to [`BinaryView::next_valid_offset_after`].
    pub fn next_valid_offset(&self, offset: u64) -> u64 {
        unsafe { BNAnalysisContextGetNextValidOffset(self.handle.as_ptr(), offset) }
    }

    /// Get the next mapped address after the given address from the cached [`MemoryMap`].
    pub fn next_mapped_address(&self, addr: u64, flags: &SegmentFlags) -> u64 {
        unsafe {
            BNAnalysisContextGetNextMappedAddress(self.handle.as_ptr(), addr, flags.into_raw())
        }
    }

    /// Get the next backed address after the given address from the cached [`MemoryMap`].
    pub fn next_backed_address(&self, addr: u64, flags: &SegmentFlags) -> u64 {
        unsafe {
            BNAnalysisContextGetNextBackedAddress(self.handle.as_ptr(), addr, flags.into_raw())
        }
    }

    /// Get the segment containing the given address from the cached [`MemoryMap`].
    ///
    /// NOTE: This is a lock-free alternative to [`BinaryViewExt::segment_at`].
    pub fn segment_at(&self, addr: u64) -> Option<Ref<Segment>> {
        unsafe {
            let result = BNAnalysisContextGetSegmentAt(self.handle.as_ptr(), addr);
            if result.is_null() {
                None
            } else {
                Some(Segment::ref_from_raw(result))
            }
        }
    }

    /// Get all mapped address ranges from the cached [`MemoryMap`].
    pub fn mapped_address_ranges(&self) -> Array<AddressRange> {
        unsafe {
            let mut count = 0;
            let ranges = BNAnalysisContextGetMappedAddressRanges(self.handle.as_ptr(), &mut count);
            Array::new(ranges, count, ())
        }
    }

    /// Get all backed address ranges from the cached [`MemoryMap`].
    pub fn backed_address_ranges(&self) -> Array<AddressRange> {
        unsafe {
            let mut count = 0;
            let ranges = BNAnalysisContextGetBackedAddressRanges(self.handle.as_ptr(), &mut count);
            Array::new(ranges, count, ())
        }
    }
}

impl ToOwned for AnalysisContext {
    type Owned = Ref<Self>;

    fn to_owned(&self) -> Self::Owned {
        unsafe { RefCountable::inc_ref(self) }
    }
}

unsafe impl RefCountable for AnalysisContext {
    unsafe fn inc_ref(handle: &Self) -> Ref<Self> {
        Ref::new(Self {
            handle: NonNull::new(BNNewAnalysisContextReference(handle.handle.as_ptr()))
                .expect("valid handle"),
        })
    }

    unsafe fn dec_ref(handle: &Self) {
        BNFreeAnalysisContext(handle.handle.as_ptr());
    }
}

#[repr(transparent)]
pub struct Workflow {
    handle: NonNull<BNWorkflow>,
}

impl Workflow {
    pub(crate) unsafe fn from_raw(handle: NonNull<BNWorkflow>) -> Self {
        Self { handle }
    }

    pub(crate) unsafe fn ref_from_raw(handle: NonNull<BNWorkflow>) -> Ref<Self> {
        Ref::new(Self { handle })
    }

    /// Create a new unregistered [Workflow] with no activities.
    /// Returns a [WorkflowBuilder] that can be used to configure and register the new [Workflow].
    ///
    /// To get a copy of an existing registered [Workflow] use [Workflow::clone_to].
    pub fn build(name: &str) -> WorkflowBuilder {
        let name = name.to_cstr();
        let result = unsafe { BNCreateWorkflow(name.as_ptr()) };
        WorkflowBuilder {
            handle: unsafe { Workflow::ref_from_raw(NonNull::new(result).unwrap()) },
        }
    }

    /// Make a new unregistered [Workflow], copying all activities and the execution strategy.
    /// Returns a [WorkflowBuilder] that can be used to configure and register the new [Workflow].
    ///
    /// * `name` - the name for the new [Workflow]
    pub fn clone_to(&self, name: &str) -> WorkflowBuilder {
        self.clone_to_with_root(name, "")
    }

    /// Make a new unregistered [Workflow], copying all activities, within `root_activity`, and the execution strategy.
    ///
    /// * `name` - the name for the new [Workflow]
    /// * `root_activity` - perform the clone operation with this activity as the root
    pub fn clone_to_with_root(&self, name: &str, root_activity: &str) -> WorkflowBuilder {
        let raw_name = name.to_cstr();
        let activity = root_activity.to_cstr();
        let workflow = unsafe {
            Self::ref_from_raw(
                NonNull::new(BNWorkflowClone(
                    self.handle.as_ptr(),
                    raw_name.as_ptr(),
                    activity.as_ptr(),
                ))
                .unwrap(),
            )
        };
        WorkflowBuilder { handle: workflow }
    }

    /// Get an existing [Workflow] by name.
    pub fn get(name: &str) -> Option<Ref<Workflow>> {
        let name = name.to_cstr();
        let result = unsafe { BNWorkflowGet(name.as_ptr()) };
        let handle = NonNull::new(result)?;
        Some(unsafe { Workflow::ref_from_raw(handle) })
    }

    /// Clone the existing [Workflow] named `name`.
    /// Returns a [WorkflowBuilder] that can be used to configure and register the new [Workflow].
    pub fn cloned(name: &str) -> Option<WorkflowBuilder> {
        Self::get(name).map(|workflow| workflow.clone_to(name))
    }

    /// List of all registered [Workflow]'s
    pub fn list() -> Array<Workflow> {
        let mut count = 0;
        let result = unsafe { BNGetWorkflowList(&mut count) };
        assert!(!result.is_null());
        unsafe { Array::new(result, count, ()) }
    }

    pub fn name(&self) -> String {
        let result = unsafe { BNGetWorkflowName(self.handle.as_ptr()) };
        assert!(!result.is_null());
        unsafe { BnString::into_string(result) }
    }

    /// Determine if an Activity exists in this [Workflow].
    pub fn contains(&self, activity: &str) -> bool {
        let activity = activity.to_cstr();
        unsafe { BNWorkflowContains(self.handle.as_ptr(), activity.as_ptr()) }
    }

    /// Retrieve the configuration as an adjacency list in JSON for the [Workflow].
    pub fn configuration(&self) -> String {
        self.configuration_with_activity("")
    }

    /// Retrieve the configuration as an adjacency list in JSON for the
    /// [Workflow], just for the given `activity`.
    ///
    /// `activity` - return the configuration for the `activity`
    pub fn configuration_with_activity(&self, activity: &str) -> String {
        let activity = activity.to_cstr();
        let result = unsafe { BNWorkflowGetConfiguration(self.handle.as_ptr(), activity.as_ptr()) };
        assert!(!result.is_null());
        unsafe { BnString::into_string(result) }
    }

    /// Whether this [Workflow] is registered or not. A [Workflow] becomes immutable once registered.
    pub fn registered(&self) -> bool {
        unsafe { BNWorkflowIsRegistered(self.handle.as_ptr()) }
    }

    pub fn size(&self) -> usize {
        unsafe { BNWorkflowSize(self.handle.as_ptr()) }
    }

    /// Retrieve the Activity object for the specified `name`.
    pub fn activity(&self, name: &str) -> Option<Ref<Activity>> {
        let name = name.to_cstr();
        let result = unsafe { BNWorkflowGetActivity(self.handle.as_ptr(), name.as_ptr()) };
        NonNull::new(result).map(|a| unsafe { Activity::ref_from_raw(a) })
    }

    /// Retrieve the list of activity roots for the [Workflow], or if
    /// specified just for the given `activity`.
    ///
    /// * `activity` - if specified, return the roots for the `activity`
    pub fn activity_roots(&self, activity: &str) -> Array<BnString> {
        let activity = activity.to_cstr();
        let mut count = 0;
        let result = unsafe {
            BNWorkflowGetActivityRoots(self.handle.as_ptr(), activity.as_ptr(), &mut count)
        };
        assert!(!result.is_null());
        unsafe { Array::new(result as *mut *mut c_char, count, ()) }
    }

    /// Retrieve the list of all activities, or optionally a filtered list.
    ///
    /// * `activity` - if specified, return the direct children and optionally the descendants of the `activity` (includes `activity`)
    /// * `immediate` - whether to include only direct children of `activity` or all descendants
    pub fn subactivities(&self, activity: &str, immediate: bool) -> Array<BnString> {
        let activity = activity.to_cstr();
        let mut count = 0;
        let result = unsafe {
            BNWorkflowGetSubactivities(
                self.handle.as_ptr(),
                activity.as_ptr(),
                immediate,
                &mut count,
            )
        };
        assert!(!result.is_null());
        unsafe { Array::new(result as *mut *mut c_char, count, ()) }
    }

    /// Generate a FlowGraph object for the current [Workflow] and optionally show it in the UI.
    ///
    /// * `activity` - if specified, generate the Flowgraph using `activity` as the root
    /// * `sequential` - whether to generate a **Composite** or **Sequential** style graph
    pub fn graph(&self, activity: &str, sequential: Option<bool>) -> Option<Ref<FlowGraph>> {
        let sequential = sequential.unwrap_or(false);
        let activity = activity.to_cstr();
        let graph =
            unsafe { BNWorkflowGetGraph(self.handle.as_ptr(), activity.as_ptr(), sequential) };
        if graph.is_null() {
            return None;
        }
        Some(unsafe { FlowGraph::ref_from_raw(graph) })
    }

    /// Not yet implemented.
    pub fn show_metrics(&self) {
        unsafe { BNWorkflowShowReport(self.handle.as_ptr(), c"metrics".as_ptr()) }
    }

    /// Show the Workflow topology in the UI.
    pub fn show_topology(&self) {
        unsafe { BNWorkflowShowReport(self.handle.as_ptr(), c"topology".as_ptr()) }
    }

    /// Not yet implemented.
    pub fn show_trace(&self) {
        unsafe { BNWorkflowShowReport(self.handle.as_ptr(), c"trace".as_ptr()) }
    }
}

impl ToOwned for Workflow {
    type Owned = Ref<Self>;

    fn to_owned(&self) -> Self::Owned {
        unsafe { RefCountable::inc_ref(self) }
    }
}

unsafe impl RefCountable for Workflow {
    unsafe fn inc_ref(handle: &Self) -> Ref<Self> {
        Ref::new(Self {
            handle: NonNull::new(BNNewWorkflowReference(handle.handle.as_ptr()))
                .expect("valid handle"),
        })
    }

    unsafe fn dec_ref(handle: &Self) {
        BNFreeWorkflow(handle.handle.as_ptr());
    }
}

impl CoreArrayProvider for Workflow {
    type Raw = *mut BNWorkflow;
    type Context = ();
    type Wrapped<'a> = Guard<'a, Workflow>;
}

unsafe impl CoreArrayProviderInner for Workflow {
    unsafe fn free(raw: *mut Self::Raw, count: usize, _context: &Self::Context) {
        BNFreeWorkflowList(raw, count)
    }

    unsafe fn wrap_raw<'a>(raw: &'a Self::Raw, context: &'a Self::Context) -> Self::Wrapped<'a> {
        Guard::new(
            Workflow::from_raw(NonNull::new(*raw).expect("valid handle")),
            context,
        )
    }
}

#[must_use = "Workflow is not registered until `register` is called"]
pub struct WorkflowBuilder {
    handle: Ref<Workflow>,
}

impl WorkflowBuilder {
    fn raw_handle(&self) -> *mut BNWorkflow {
        self.handle.handle.as_ptr()
    }

    /// Register an [Activity] with this Workflow and insert it before the designated position.
    ///
    /// * `activity` - the [Activity] to register
    /// * `sibling` - the activity to insert the new activity before
    pub fn activity_before(self, activity: &Activity, sibling: &str) -> Result<Self, ()> {
        self.register_activity(activity)?
            .insert(sibling, vec![activity.name()])
    }

    /// Register an [Activity] with this Workflow and insert it in the designated position.
    ///
    /// * `activity` - the [Activity] to register
    /// * `sibling` - the activity to insert the new activity after
    pub fn activity_after(self, activity: &Activity, sibling: &str) -> Result<Self, ()> {
        self.register_activity(activity)?
            .insert_after(sibling, vec![activity.name()])
    }

    /// Register an [Activity] with this Workflow.
    ///
    /// * `activity` - the [Activity] to register
    pub fn register_activity(self, activity: &Activity) -> Result<Self, ()> {
        self.register_activity_with_subactivities::<Vec<String>>(activity, vec![])
    }

    /// Register an [Activity] with this Workflow.
    ///
    /// * `activity` - the [Activity] to register
    /// * `subactivities` - the list of Activities to assign
    pub fn register_activity_with_subactivities<I>(
        self,
        activity: &Activity,
        subactivities: I,
    ) -> Result<Self, ()>
    where
        I: IntoIterator,
        I::Item: IntoCStr,
    {
        let subactivities_raw: Vec<_> = subactivities.into_iter().map(|x| x.to_cstr()).collect();
        let mut subactivities_ptr: Vec<*const _> =
            subactivities_raw.iter().map(|x| x.as_ptr()).collect();
        let result = unsafe {
            BNWorkflowRegisterActivity(
                self.raw_handle(),
                activity.handle.as_ptr(),
                subactivities_ptr.as_mut_ptr(),
                subactivities_ptr.len(),
            )
        };
        let Some(activity_ptr) = NonNull::new(result) else {
            return Err(());
        };
        let _ = unsafe { Activity::ref_from_raw(activity_ptr) };
        Ok(self)
    }

    /// Register this [Workflow], making it immutable and available for use.
    pub fn register(self) -> Result<Ref<Workflow>, ()> {
        self.register_with_config("")
    }

    /// Register this [Workflow], making it immutable and available for use.
    ///
    /// * `configuration` - a JSON representation of the workflow configuration
    pub fn register_with_config(self, config: &str) -> Result<Ref<Workflow>, ()> {
        // TODO: We need to hide the JSON here behind a sensible/typed API.
        let config = config.to_cstr();
        if unsafe { BNRegisterWorkflow(self.raw_handle(), config.as_ptr()) } {
            Ok(self.handle)
        } else {
            Err(())
        }
    }

    /// Assign the list of `activities` as the new set of children for the specified `activity`.
    ///
    /// * `activity` - the Activity node to assign children
    /// * `activities` - the list of Activities to assign
    pub fn subactivities<I>(self, activity: &str, activities: I) -> Result<Self, ()>
    where
        I: IntoIterator,
        I::Item: IntoCStr,
    {
        let activity = activity.to_cstr();
        let input_list: Vec<_> = activities.into_iter().map(|a| a.to_cstr()).collect();
        let mut input_list_ptr: Vec<*const _> = input_list.iter().map(|x| x.as_ptr()).collect();
        let result = unsafe {
            BNWorkflowAssignSubactivities(
                self.raw_handle(),
                activity.as_ptr(),
                input_list_ptr.as_mut_ptr(),
                input_list.len(),
            )
        };
        if result {
            Ok(self)
        } else {
            Err(())
        }
    }

    /// Remove all Activity nodes from this [Workflow].
    pub fn clear(self) -> Result<Self, ()> {
        let result = unsafe { BNWorkflowClear(self.raw_handle()) };
        if result {
            Ok(self)
        } else {
            Err(())
        }
    }

    /// Insert the list of `activities` before the specified `activity` and at the same level.
    ///
    /// * `activity` - the Activity node for which to insert `activities` before
    /// * `activities` - the list of Activities to insert
    pub fn insert<I>(self, activity: &str, activities: I) -> Result<Self, ()>
    where
        I: IntoIterator,
        I::Item: IntoCStr,
    {
        let activity = activity.to_cstr();
        let input_list: Vec<_> = activities.into_iter().map(|a| a.to_cstr()).collect();
        let mut input_list_ptr: Vec<*const _> = input_list.iter().map(|x| x.as_ptr()).collect();
        let result = unsafe {
            BNWorkflowInsert(
                self.raw_handle(),
                activity.as_ptr(),
                input_list_ptr.as_mut_ptr(),
                input_list.len(),
            )
        };
        if result {
            Ok(self)
        } else {
            Err(())
        }
    }

    /// Insert the list of `activities` after the specified `activity` and at the same level.
    ///
    /// * `activity` - the Activity node for which to insert `activities` after
    /// * `activities` - the list of Activities to insert
    pub fn insert_after<I>(self, activity: &str, activities: I) -> Result<Self, ()>
    where
        I: IntoIterator,
        I::Item: IntoCStr,
    {
        let activity = activity.to_cstr();
        let input_list: Vec<_> = activities.into_iter().map(|a| a.to_cstr()).collect();
        let mut input_list_ptr: Vec<*const _> = input_list.iter().map(|x| x.as_ptr()).collect();
        let result = unsafe {
            BNWorkflowInsertAfter(
                self.raw_handle(),
                activity.as_ptr(),
                input_list_ptr.as_mut_ptr(),
                input_list.len(),
            )
        };
        if result {
            Ok(self)
        } else {
            Err(())
        }
    }

    /// Remove the specified `activity`
    pub fn remove(self, activity: &str) -> Result<Self, ()> {
        let activity = activity.to_cstr();
        let result = unsafe { BNWorkflowRemove(self.raw_handle(), activity.as_ptr()) };
        if result {
            Ok(self)
        } else {
            Err(())
        }
    }

    /// Replace the specified `activity`.
    ///
    /// * `activity` - the Activity to replace
    /// * `new_activity` - the replacement Activity
    pub fn replace(self, activity: &str, new_activity: &str) -> Result<Self, ()> {
        let activity = activity.to_cstr();
        let new_activity = new_activity.to_cstr();
        let result = unsafe {
            BNWorkflowReplace(self.raw_handle(), activity.as_ptr(), new_activity.as_ptr())
        };
        if result {
            Ok(self)
        } else {
            Err(())
        }
    }
}