steroid 0.5.0

A lightweight framework for dynamic binary instrumentation
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
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
//! The buffer module contains high-level constructs to perform IO in the remote process' memory.
//!
//! While abstractions provided by modules such as [`process`], [`breakpoint`] or [`syscall`] allow
//! the user to manipulate a remote process' execution, the buffer module enable the manipulation of
//! the memory of the remote process. This module provides the user with the trait
//! [`Buffer`]. Buffers are types that represent a portion of memory in the remote process.
//!
//! # Buffers
//!
//! Steroid has two types of buffers: [`RemoteView`] and [`AllocatedBuffer`].
//!
//! ## Remote views
//!
//! The former is just a view over a contiguous address span in the remote process that already
//! exists. No allocation is performed by the steroid client to create a remote view, only checks to
//! ensure the address span is valid. They are created using the function [`remote_view`].
//!
//! ```no_run
//! # use anyhow::Error;
//! # use steroid::buffer::remote_view;
//! # use steroid::process::spawn_process;
//! let process = spawn_process("/usr/local/bin/my_program", ["-l"])?;
//! let buffer = remote_view(&process, 0x0040_1126, 30)?;
//! # Ok::<(), Error>(())
//! ```
//!
//! Remote views do not make any assumption on how the user wants to use them. There are no
//! permission constraints on the remote process memory mappings, neither is the steroid client
//! limited to reading the memory, it is possible to write in it too.
//!
//! ## Allocated buffers
//!
//! [`AllocatedBuffer`] is the type of buffers that the steroid client forces the remote process
//! allocate in its address space. Just like remote views, allocated buffers are essentially just an
//! address and a size, all the checks are done during the construction of the buffer using either
//! [`allocate_buffer`] or the full-featured [`BufferBuilder`].
//!
//! # Readers and Writers
//!
//! By themselves, buffers are pretty useless. They become an interesting feature once the user can
//! read from and write into them. Steroid provides three pairs of readers and writers that are
//! types implementing the standard [`Read`] and [`Write`] traits. The difference between these
//! three pairs of types is the prerequisites needed to instanciate them and, first and foremost,
//! the guaranties they provide.
//!
//! ## `SyncReader` and `SyncWriter`
//!
//! [`SyncReader`] and [`SyncWriter`] are _synchronous_ readers and writers. They are synchronous in
//! the sense that they are created whilst the remote process is stopped and their lifetime cannot
//! exceed the process being resumed. In more technical terms, synchronous readers and writers are
//! created using the [`TargetController`] of a process and their lifetime is bounded by the
//! lifetime of this controller.
//!
//! The following code compiles correctly:
//!
//! ```
//! # use std::io::Read;
//! # use std::path::PathBuf;
//! # use anyhow::Error;
//! # use steroid::process::spawn_process;
//! # use steroid::run::{Executing};
//! # use steroid::buffer::{remote_view, SyncReader};
//! # use steroid::breakpoint::{breakpoint, Breakpoint, Mode};
//! #
//! # let mut SOME_PROCESS = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
//! # SOME_PROCESS.push("resources/test/say_hello_no_pie");
//! # let SOME_ADDRESS: usize = 0x401126;
//! # let mut process = spawn_process(SOME_PROCESS, [""])?;
//! let mut ctrl = process.wait()?.assume_alive()?;
//! let buffer = remote_view(ctrl.process(), SOME_ADDRESS, 50).unwrap();
//! let mut reader = SyncReader::new(&mut ctrl, &buffer).unwrap();
//!
//! // Read things
//! let mut buf: [u8; 10] = Default::default();
//! reader.read(&mut buf).unwrap();
//! ctrl.resume()?;
//! # Ok::<(), Error>(())
//! ```
//!
//! While this one fails to compile:
//!
//! ```compile_fail
//! # use std::io::Read;
//! # use std::path::PathBuf;
//! # use anyhow::Error;
//! # use steroid::process::spawn_process;
//! # use steroid::run::{Executing};
//! # use steroid::buffer::{remote_view, SyncReader};
//! # use steroid::breakpoint::{breakpoint, Breakpoint, Mode};
//! #
//! # let mut SOME_PROCESS = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
//! # SOME_PROCESS.push("resources/test/say_hello_no_pie");
//! # let SOME_ADDRESS: usize = 0x401126;
//! # let mut process = spawn_process(SOME_PROCESS, [""])?;
//! let mut ctrl = process.wait()?.assume_alive()?;
//! let buffer = remote_view(ctrl.process(), SOME_ADDRESS, 50).unwrap();
//! let mut reader = SyncReader::new(&mut ctrl, &buffer).unwrap();
//!
//! // Read things
//! let mut buf: [u8; 10] = Default::default();
//! reader.read(&mut buf).unwrap();
//! ctrl.resume()?;
//!
//! // Try reading after the process restarted
//! let mut buf: [u8; 10] = Default::default();
//! reader.read(&mut buf).unwrap();
//! # Ok::<(), Error>(())
//! ```
//! ```text
//!    | let mut reader = SyncReader::new(&mut ctrl, &buffer).unwrap();
//!    |                                  --------- borrow of `ctrl` occurs here
//! ...
//!    | ctrl.resume()?;
//!    | ^^^^ move out of `ctrl` occurs here
//! ...
//!    | reader.read(&mut buf).unwrap();
//!    | --------------------- borrow later used here
//! ```
//!
//! ## `AsyncReader` and `AsyncWriter`
//!
//! [`AsyncReader`] and [`AsyncWriter`] and asynchronous readers and writers. They are asynchronous
//! in the sense that the process is allowed to run while the reader or writer is still manipulating
//! the buffer. This enables the user to perform long writes or reads without needlessly blocking
//! the execution of the process.
//!
//! However, in order to prevent the user from corrupting the state of the remote process or reading
//! outdated data, an asynchronous reader or writer requires that the buffer meets some permission
//! prerequisites. A buffer needs to not be writable by the remote process for an [`AsyncReader`] to
//! be created. On the other hand, if one wants to create an [`AsyncWriter`], then the buffer must
//! be neither readable nor writable nor even executable by the remote process.
//!
//! Note nonetheless that while **these prerequisites are checked on the creation of the reader or
//! writer, they are not enforced anymore after that**. This is one of the current limitations of
//! steroid's buffers that we hope to lift in the future.
//!
//! ## `UnsafeReader` and `UnsafeWriter`
//!
//! [`UnsafeReader`] and [ `UnsafeWriter`] are readers and writers that do not require any safety
//! criteria to be met in order to be created. On the other hand, these readers and writers do not
//! provide any guaranties on the manipulation the user is performing. The data they write can
//! totally corrupt the remote process' memory while it is reading or executing it.
//!
//! The reason these types exist is to enable the user to manipulate the memory of the remote
//! process in ways that are not possible using the other reader and writer types. These may be
//! complex manipulations or high-performance interactions with the remote process.
//!
//! **The existence of these type is probably a big mistake**, but until steroid implements a better
//! I/O model to manipulate a remote process' memory, they are a necessity. One must assume that the
//! whole reader/writer model will change in future versions and the current API is temporary.
//!
//! # Steroid's limitations regarding buffers
//!
//! The current API suffers from some limitations:
//!
//! - Buffer variable lifetimes are not bound to the one of the process they live in. This means
//! that the rust compiler cannot spot obvious manipulation of buffers on a dead process at
//! compile-time.
//! - All the guaranties provided by the synchronous and asynchronous readers and writers do not
//! hold on multithreaded applications (that steroid currently do not support).
//! - Asynchronous readers and writers prerequisites are checked when the reader or writer is
//! created but they are not enforced anymore after that.
//! - Unsafe readers and writers by themselves should not exist as-is.
//!
//! [`process`]: ../process/index.html
//! [`breakpoint`]: ../breakpoint/index.html
//! [`syscall`]: ../syscall/index.html
use std::io::Error as IOError;
use std::io::IoSlice;
use std::io::Result as IOResult;
use std::io::Write;
use std::io::{ErrorKind, IoSliceMut, Read, Seek, SeekFrom};

use nix::libc::{
    MAP_ANONYMOUS, MAP_FIXED, MAP_PRIVATE, MAP_SHARED, PROT_EXEC, PROT_READ, PROT_WRITE,
};
use nix::sys::uio::{process_vm_readv, process_vm_writev, RemoteIoVec};

use crate::error::{
    CouldNotAllocate, CouldNotCreateAsyncReaderWriter, CouldNotCreateRemoteView,
    CouldNotCreateSyncReaderWriter, CouldNotDeallocate, CouldNotRestorePermissions, MprotectError,
};
use crate::mapping::{memory_mapping, PermissionMatcher, Permissions};
use crate::process::{Pid, TargetController, TargetProcess};
use crate::run::Executing;
use crate::syscall;

/// Common trait for all buffer types in steroid. This trait serves as a common denominator for
/// buffers that live in a remote process.
pub trait Buffer {
    /// The start address of the buffer in the remote address space.
    fn address(&self) -> usize;
    /// The length of the buffer.
    fn length(&self) -> usize;
    /// The pid of the remote process.
    fn pid(&self) -> Pid;
}

/// View over the remote process address space. A [`RemoteView`] does not allocate any memory in the
/// remote process and is created using [`remote_view`] that ensures the view maps a valid address
/// range.
pub struct RemoteView {
    address: usize,
    length: usize,
    pid: Pid,
}

impl Buffer for RemoteView {
    fn address(&self) -> usize {
        self.address
    }

    fn length(&self) -> usize {
        self.length
    }

    fn pid(&self) -> Pid {
        self.pid
    }
}

/// Create a [`RemoteView`] of the remote process given as argument starting at the given address
/// with the given length.
///
/// This function ensures the address range the remote view must map corresponds to a valid address
/// range in the remote process - i.e. the address range is a subrange of a mapping in the
/// process. See [`mapping`].
///
/// # Errors
///
/// If the address range does not correspond to a valid address range mapped in the remote process'
/// address space, a [`CouldNotCreateRemoteView::InvalidAddressRange`] is returned.
///
/// If the memory mapping of the remote process could not be read and parsed by the steroid client,
/// a [`CouldNotCreateRemoteView::CouldNotReadMemoryMapping`] is returned.
///
/// [`mapping`]: ../mapping/index.html
pub fn remote_view(
    process: &TargetProcess,
    address: usize,
    length: usize,
) -> Result<RemoteView, CouldNotCreateRemoteView> {
    let mapping = memory_mapping(process)?;
    let upper_bound = address + length - 1;

    mapping
        .find(|m| m.start <= address && upper_bound <= m.end)
        .ok_or(CouldNotCreateRemoteView::InvalidAddressRange {
            pid: process.pid(),
            start: address,
            end: upper_bound,
        })
        .map(|_| RemoteView {
            address,
            length,
            pid: process.pid(),
        })
}

/// Buffer that is allocated by the steroid client in the remote process.
#[allow(clippy::module_name_repetitions)]
pub struct AllocatedBuffer {
    address: usize,
    length: usize,
    pid: Pid,
}

impl Buffer for AllocatedBuffer {
    fn address(&self) -> usize {
        self.address
    }

    fn length(&self) -> usize {
        self.length
    }

    fn pid(&self) -> Pid {
        self.pid
    }
}

impl AllocatedBuffer {
    /// Deallocate the buffer in the remote process. Note that this method consumes the buffer
    /// object, as it does not represent a valid buffer anymore. On failure, this function returns a
    /// [`CouldNotDeallocate::MunmapFailed`] error with the value of the remote [`errno(3)`].
    ///
    /// # Errors
    ///
    /// This function may return an error if the whole process of calling the system call in the
    /// remote process fails or if [`munmap(2)`] itself fails.
    ///
    /// [`errno(3)`]: https://man7.org/linux/man-pages/man3/errno.3.html
    /// [`munmap(2)`]: https://man7.org/linux/man-pages/man2/mmap.2.html
    pub fn deallocate<E>(self, ctrl: &mut TargetController<E>) -> Result<(), CouldNotDeallocate>
    where
        E: Executing,
    {
        let ret = syscall::munmap(ctrl, self.address as u64, self.length as u64)?;

        if ret == 0 {
            Ok(())
        } else {
            Err(CouldNotDeallocate::MunmapFailed {
                pid: ctrl.process().pid(),
                source: IOError::from_raw_os_error(ret as i32),
            })
        }
    }
}

/// Builder structure that helps creating an allocated buffer in a remote process.
///
/// The user can specify the different properties of the buffer one after the other until they call
/// [`BufferBuilder::build`], which consumes the builder and allocates the buffer in the remote
/// process. By default, no address hint is set, meaning that [`mmap(2)`] will place the buffer whre
/// it can.
///
/// [`mmap(2)`]: https://man7.org/linux/man-pages/man2/mmap.2.html
#[allow(clippy::module_name_repetitions)]
pub struct BufferBuilder {
    address: Option<usize>,
    length: usize,
    permissions: i32,
    flags: i32,
}

impl BufferBuilder {
    /// Create a new buffer builder.
    #[must_use]
    pub const fn new(length: usize) -> Self {
        Self {
            address: None,
            length,
            permissions: 0,
            flags: MAP_ANONYMOUS,
        }
    }

    /// Give an address hint for [`mmap(2)`] to place the buffer. Used this
    /// [`BufferBuilder::fixed`], this function gives a definite address to allocate the buffer at.
    ///
    /// [`mmap(2)`]: https://man7.org/linux/man-pages/man2/mmap.2.html
    #[must_use]
    pub const fn at_address(self, address: usize) -> Self {
        Self {
            address: Some(address),
            length: self.length,
            permissions: self.permissions,
            flags: self.flags,
        }
    }

    /// Make the buffer readable by the remote process.
    #[must_use]
    pub const fn readable(self) -> Self {
        Self {
            address: self.address,
            length: self.length,
            permissions: self.permissions | PROT_READ,
            flags: self.flags,
        }
    }

    /// Make the buffer writable by the remote process.
    #[must_use]
    pub const fn writable(self) -> Self {
        Self {
            address: self.address,
            length: self.length,
            permissions: self.permissions | PROT_WRITE,
            flags: self.flags,
        }
    }

    /// Make the buffer executable by the remote process.
    #[must_use]
    pub const fn executable(self) -> Self {
        Self {
            address: self.address,
            length: self.length,
            permissions: self.permissions | PROT_EXEC,
            flags: self.flags,
        }
    }

    /// Make the mapping private to the remote process.
    #[must_use]
    pub const fn private(self) -> Self {
        Self {
            address: self.address,
            length: self.length,
            permissions: self.permissions,
            flags: (self.flags | MAP_PRIVATE) & !MAP_SHARED,
        }
    }

    /// Make the mapping shared with other processes, see [`mmap(2)`].
    ///
    /// [`mmap(2)`]: https://man7.org/linux/man-pages/man2/mmap.2.html
    #[must_use]
    pub const fn shared(self) -> Self {
        Self {
            address: self.address,
            length: self.length,
            permissions: self.permissions,
            flags: (self.flags | MAP_SHARED) & !MAP_PRIVATE,
        }
    }

    /// Tell [`mmap(2)`] to place the buffer exactly at the address specified with
    /// [`BufferBuilder::at_address`] instead of using it as a hint.
    ///
    /// [`mmap(2)`]: https://man7.org/linux/man-pages/man2/mmap.2.html
    #[must_use]
    pub const fn fixed(self) -> Self {
        Self {
            address: self.address,
            length: self.length,
            permissions: self.permissions,
            flags: self.flags | MAP_FIXED,
        }
    }

    /// Allocate the buffer in the remote process using the given controller.
    ///
    /// # Errors
    ///
    /// This function will return an error if the manipulation of the remote process
    /// fails. Otherwise, if the call to [`mmap(2)`] fails, an error is returned as well.
    ///
    /// [`mmap(2)`]: https://man7.org/linux/man-pages/man2/mmap.2.html
    #[allow(clippy::cast_sign_loss)]
    #[allow(clippy::cast_possible_wrap)]
    pub fn build<E>(
        self,
        ctrl: &mut TargetController<E>,
    ) -> Result<AllocatedBuffer, CouldNotAllocate>
    where
        E: Executing,
    {
        let pid = ctrl.process().pid();
        let address = self.address.unwrap_or(0);
        let length = self.length;

        let ret = syscall::mmap(
            ctrl,
            address as u64,
            length as u64,
            self.permissions as u64,
            self.flags as u64,
            -1_i64 as u64,
            0,
        )? as i64;

        if -4096 < ret && ret < 0 {
            let errno = -ret as i32;
            Err(CouldNotAllocate::MmapFailed {
                pid,
                source: IOError::from_raw_os_error(errno),
            })
        } else {
            let address = ret as usize;

            Ok(AllocatedBuffer {
                address,
                length,
                pid,
            })
        }
    }
}

/// Allocate memory in the remote process for a private buffer.
///
/// This function needs the length of the buffer and the permissions given to the remote process to
/// use it, see [`mmap(2)`]. On failure, this function returns a [`CouldNotAllocate::MmapFailed`]
/// with the value of [`errno(3)`] in the remote process.
///
/// This function is shortcut to build a private buffer at any address without explicitly using a
/// [`BufferBuilder`].
///
/// # Errors
///
/// See [`BufferBuilder::build`].
///
/// [`mmap(2)`]: https://man7.org/linux/man-pages/man2/mmap.2.html
/// [`errno(3)`]: https://man7.org/linux/man-pages/man3/errno.3.html
#[allow(clippy::module_name_repetitions)]
pub fn allocate_buffer<E>(
    ctrl: &mut TargetController<E>,
    length: usize,
    permissions: i32,
) -> Result<AllocatedBuffer, CouldNotAllocate>
where
    E: Executing,
{
    let mut builder = BufferBuilder::new(length).private();

    builder.permissions = permissions;
    builder.build(ctrl)
}

fn common_buffer_read<B>(remote_buffer: &B, offset: &mut usize, buf: &mut [u8]) -> IOResult<usize>
where
    B: Buffer,
{
    let buffer_len = buf.len();

    let local_iov = IoSliceMut::new(buf);
    let remote_iov = RemoteIoVec {
        base: remote_buffer.address() + *offset,
        len: buffer_len,
    };

    let count = process_vm_readv(remote_buffer.pid().into(), &mut [local_iov], &[remote_iov])?;
    *offset += count;

    Ok(count)
}

fn common_buffer_write<B>(remote_buffer: &B, offset: &mut usize, buf: &[u8]) -> IOResult<usize>
where
    B: Buffer,
{
    let buffer_len = buf.len();

    let local_iov = IoSlice::new(buf);
    let remote_iov = RemoteIoVec {
        base: remote_buffer.address() + *offset,
        len: buffer_len,
    };

    let count = process_vm_writev(remote_buffer.pid().into(), &[local_iov], &[remote_iov])?;
    *offset += count;

    Ok(count)
}

#[allow(clippy::cast_sign_loss)]
#[allow(clippy::cast_possible_wrap)]
fn common_buffer_seek<B>(buffer: &B, offset: &mut usize, pos: SeekFrom) -> IOResult<u64>
where
    B: Buffer,
{
    let new_offset = match pos {
        SeekFrom::Start(off) => off as i64,
        SeekFrom::End(off) => buffer.length() as i64 + off,
        SeekFrom::Current(off) => *offset as i64 + off,
    };

    if new_offset < 0 || (buffer.length() as i64) < new_offset {
        Err(ErrorKind::InvalidData.into())
    } else {
        *offset = new_offset as usize;
        Ok(*offset as u64)
    }
}

/// Unsafe reader over a steroid [`Buffer`].
///
/// This type enables the user to read the contents of the buffer using the standard [`Read`]
/// API. Note that the reader borrows the buffer immutably, which means that many readers can read
/// from it at the same time.
///
/// # Safety
///
/// [`UnsafeReader`] is used to expressed complex interactions with a remote buffer that cannot be
/// expressed safely with steroid data integrity model. This type allows the user to manipulate a
/// buffer in a way that they know is valid - or they do not need data integrity - but cannot
/// express efficiently using safer approaches provided by steroid.
///
/// When an unsafe reader is created, the permissions of the buffer given to the remote process are
/// neither checked nor altered. This means that the process can write into the buffer while the
/// steroid client is reading. Such an event would obviously result in the reading of corrupted
/// data.
///
/// [`UnsafeReader`]s are built using [`UnsafeReader::new`] which is an unsafe function. Rust does
/// not allow marking [`Read`] and [`Write`] functions as unsafe themselves so only the creation of
/// the reader is marked as such, but consider the manipulation of an unsafe reader as a whole as
/// unsafe. Whenever possible, consider switching to safer alternatives provided by steroid, such as
/// [`SyncReader`] or [`AsyncReader`].
pub struct UnsafeReader<'buffer, B>
where
    B: Buffer,
{
    offset: usize,
    buffer: &'buffer B,
}

impl<'buffer, B> Read for UnsafeReader<'buffer, B>
where
    B: Buffer,
{
    fn read(&mut self, buf: &mut [u8]) -> IOResult<usize> {
        common_buffer_read(self.buffer, &mut self.offset, buf)
    }
}

impl<'buffer, B> Seek for UnsafeReader<'buffer, B>
where
    B: Buffer,
{
    fn seek(&mut self, pos: SeekFrom) -> IOResult<u64> {
        common_buffer_seek(self.buffer, &mut self.offset, pos)
    }
}

impl<'buffer, B> UnsafeReader<'buffer, B>
where
    B: Buffer,
{
    /// Create a new unsafe reader from the [`Buffer`].
    ///
    /// # Safety
    ///
    /// An unsafe reader allows the user to perform any reads in the remote process even while it is
    /// running and without restrictions about the permissions given to the process to manipulate
    /// the memory mapping corresponding to the buffer. This enables the user to perform complex
    /// interactions with the remote process that they know are valid but cannot be expressed with
    /// steroid data integrity model.
    ///
    /// A read performed by an unsafe reader can fail because of many reasons (non-exhaustive):
    /// - the process has already terminated
    /// - the buffer has been freed by the process
    /// - the buffer has been modified by the process making the data read by this reader incorrect
    pub const unsafe fn new(buf: &'buffer B) -> Self {
        UnsafeReader {
            offset: 0,
            buffer: buf,
        }
    }
}

/// Unsafe writer over a steroid [`Buffer`].
///
/// This type enables to write data into the underlying buffer in the remote process using the
/// standard [`Write`] API. The writer borrows the buffer mutably, which means that only one writer
/// can write at the same time and no reader shall read while the writer is existing. This ensures
/// the integrity of the data in the buffer, at least from the steroid-client part.
///
/// # Safety
///
/// [`UnsafeWriter`]s exist to enable complex manipulations of buffers in the remote process that
/// cannot be expressed with safer approaches provided by steroid. Using an unsafe writer, no data
/// integrity can be enforced. The writer can modify the process while it is running and no checks
/// are performed to ensure the process has no write nor read permissions on the buffer. The user
/// should switch to safer alternatives such as an [`AsyncWriter`] whenever possible.
pub struct UnsafeWriter<'buffer, B>
where
    B: Buffer,
{
    offset: usize,
    buffer: &'buffer mut B,
}

impl<'buffer, B> Write for UnsafeWriter<'buffer, B>
where
    B: Buffer,
{
    fn write(&mut self, buf: &[u8]) -> IOResult<usize> {
        common_buffer_write(self.buffer, &mut self.offset, buf)
    }

    /// Writes are immediate, so the flush method does not do anything.
    fn flush(&mut self) -> IOResult<()> {
        Ok(())
    }
}

impl<'buffer, B> Seek for UnsafeWriter<'buffer, B>
where
    B: Buffer,
{
    fn seek(&mut self, pos: SeekFrom) -> IOResult<u64> {
        common_buffer_seek(self.buffer, &mut self.offset, pos)
    }
}

impl<'buffer, B> UnsafeWriter<'buffer, B>
where
    B: Buffer,
{
    /// Create a new unsafe writer for the given buffer.
    ///
    /// # Safety
    ///
    /// An unsafe writer does not give any guaranties in terms of data integrity. The remote process
    /// can be reading, executing or even writing at the location the writer is writing and steroid
    /// will do nothing to prevent that. As such, the creation of an unsafe writer is marked as
    /// unsafe itself. The API of the [`Write`] trait implemented by [`UnsafeWriter`] is safe, the
    /// methods it provides cannot be marked unsafe for this implementation alone, therefore only
    /// this creation function is marked unsafe.
    pub unsafe fn new(buf: &'buffer mut B) -> Self {
        UnsafeWriter {
            offset: 0,
            buffer: buf,
        }
    }
}

/// A reader that can read while the process is running.
///
/// # Safety
///
/// The asynchronous reader is able to read the contents of a buffer in a remote process while it is
/// running. In order to do that, the creation of the reader has prerequisites:
/// - the process must be stopped during the creation of the reader
/// - the process must not be able to write into the buffer
///
/// In order to enforce these prerequisites, the function [`AsyncReader::try_new`] takes a
/// [`TargetController`] as argument - whose existence imposes that the process is stopped - and
/// checks that the permissions of the buffer match. If they do not, the creation fails. It is
/// possible to force the creation of an asynchronous reader by calling [`AsyncReader::new`]. This
/// function does the same things as new, but changes the permissions of the buffer in the remote
/// process to meet the conditions of creation of an asynchronous reader.
pub struct AsyncReader<'buffer, B>
where
    B: Buffer,
{
    offset: usize,
    saved_permissions: Permissions,
    buffer: &'buffer B,
}

impl<'buffer, B> Read for AsyncReader<'buffer, B>
where
    B: Buffer,
{
    fn read(&mut self, buf: &mut [u8]) -> IOResult<usize> {
        common_buffer_read(self.buffer, &mut self.offset, buf)
    }
}

impl<'buffer, B> Seek for AsyncReader<'buffer, B>
where
    B: Buffer,
{
    fn seek(&mut self, pos: SeekFrom) -> IOResult<u64> {
        common_buffer_seek(self.buffer, &mut self.offset, pos)
    }
}

impl<'buffer, B> AsyncReader<'buffer, B>
where
    B: Buffer,
{
    /// Try to create an asynchronous reader using the given controller for the given buffer.
    ///
    /// # Errors
    ///
    /// If the buffer is mapped as writable by the remote process, this function returns a
    /// [`CouldNotCreateAsyncReaderWriter::PermissionsMismatch`] error.
    pub fn try_new<E>(
        ctrl: &mut TargetController<E>,
        buf: &'buffer B,
    ) -> Result<Self, CouldNotCreateAsyncReaderWriter>
    where
        E: Executing,
    {
        let mem = memory_mapping(ctrl.process())?;
        let buf_map = mem
            // Find a mapping that entire contains the buffer to check its permissions.
            // In theory, this function should always succeed since the buffer should always
            // reference a valid memory span.
            .find(|m| m.start <= buf.address() && buf.address() + buf.length() <= m.end)
            .ok_or(CouldNotCreateAsyncReaderWriter::InvalidAddressRange {
                pid: ctrl.process().pid(),
                start: buf.address(),
                end: buf.address() + buf.length(),
            })?;

        let matcher = PermissionMatcher {
            readable: None,
            writable: Some(false),
            executable: None,
            private: None,
        };

        if buf_map.permissions.matches(&matcher) {
            Ok(AsyncReader {
                offset: 0,
                saved_permissions: buf_map.permissions.clone(),
                buffer: buf,
            })
        } else {
            Err(CouldNotCreateAsyncReaderWriter::PermissionsMismatch {
                expected: matcher,
                got: buf_map.permissions.clone(),
            })
        }
    }

    /// Create an asynchronous reader for the given buffer, using the given controller.
    ///
    /// # Errors
    ///
    /// If the buffer is mapped as writable by the remote process, it is remapped as read-only using
    /// [`mprotect(2)`].
    ///
    /// [`mprotect(2)`]: https://man7.org/linux/man-pages/man2/mprotect.2.html
    #[allow(clippy::cast_sign_loss)]
    pub fn new<E>(
        ctrl: &mut TargetController<E>,
        buf: &'buffer B,
    ) -> Result<Self, CouldNotRestorePermissions>
    where
        E: Executing,
    {
        let pid = ctrl.process().pid();
        let mem = memory_mapping(ctrl.process())?;
        let buf_map = mem
            .find(|m| m.start <= buf.address() && buf.address() + buf.length() <= m.end)
            .ok_or(CouldNotRestorePermissions::InvalidAddressRange {
                pid,
                start: buf.address(),
                end: buf.address() + buf.length(),
            })?;

        if buf_map.permissions.writable {
            let perm = buf_map.permissions.to_i32() & !PROT_WRITE;
            let length = buf_map.end - buf_map.start;
            let rax = syscall::mprotect(ctrl, buf_map.start as u64, length as u64, perm as u64)?;

            if rax != 0 {
                let mut permissions = buf_map.permissions.clone();
                permissions.writable = false;

                let mprotect_error = match IOError::from_raw_os_error(rax as i32).kind() {
                    ErrorKind::OutOfMemory => MprotectError::TooManyMappings,
                    ErrorKind::InvalidData => MprotectError::GrowsUpAndDown { perm: permissions },
                    error => unreachable!("unexpected error: {}", error),
                };

                return Err(CouldNotRestorePermissions::MprotectFailed {
                    pid,
                    source: mprotect_error,
                });
            }
        }

        Ok(AsyncReader {
            offset: 0,
            saved_permissions: buf_map.permissions.clone(),
            buffer: buf,
        })
    }

    /// Consume the reader and restore the permissions of the memory mapping that contains the
    /// buffer as they were before the reader was created.
    ///
    /// # Errors
    ///
    /// This function checks that the buffer it is manipulating still exists in the remote
    /// process. So if the address range referenced is not valid anymore, a
    /// [`CouldNotRestorePermissions::InvalidAddressRange`] is returned.
    ///
    /// Moreover, if the call to
    /// [`mprotect(2)`] itself fails, the error code is returned in a
    /// [`CouldNotRestorePermissions::MprotectFailed`] variant.
    ///
    /// Like any function that needs the memory mapping of the remote process, it is possible, while
    /// very unlikely, that steroid cannot parse the [`maps file`] and that the function returns an
    /// error.
    ///
    /// [`maps file`]: ../mapping/index.html
    /// [`mprotect(2)`]: https://man7.org/linux/man-pages/man2/mprotect.2.html
    #[allow(clippy::cast_sign_loss)]
    pub fn restore_permissions<E>(
        self,
        ctrl: &mut TargetController<E>,
    ) -> Result<(), CouldNotRestorePermissions>
    where
        E: Executing,
    {
        let perm = self.saved_permissions.to_i32();
        let buf = self.buffer;
        let pid = ctrl.process().pid();

        let mem = memory_mapping(ctrl.process())?;
        let buf_map = mem
            .find(|m| m.start <= buf.address() && buf.address() + buf.length() <= m.end)
            .ok_or(CouldNotRestorePermissions::InvalidAddressRange {
                pid,
                start: buf.address(),
                end: buf.address() + buf.length(),
            })?;

        let length = buf_map.end - buf_map.start;
        match syscall::mprotect(ctrl, buf_map.start as u64, length as u64, perm as u64)? {
            0 => Ok(()),
            rax => {
                let mut permissions = buf_map.permissions.clone();
                permissions.writable = false;

                let mprotect_error = match IOError::from_raw_os_error(rax as i32).kind() {
                    ErrorKind::OutOfMemory => MprotectError::TooManyMappings,
                    ErrorKind::InvalidData => MprotectError::GrowsUpAndDown { perm: permissions },
                    error => unreachable!("unexpected error: {}", error),
                };

                Err(CouldNotRestorePermissions::MprotectFailed {
                    pid,
                    source: mprotect_error,
                })
            }
        }
    }
}

/// A writer able to write in a buffer in a remote process while it is running.
///
/// # Safety
///
/// In order to ensure that it is safe to write into the buffer even though the process is running,
/// the process must meet some criteria for the user to create an asynchronous writer:
/// - The process must be stopped at the creation of the writer
/// - The buffer must not be readable, writable nor executable by the remote process
pub struct AsyncWriter<'buffer, B>
where
    B: Buffer,
{
    offset: usize,
    buffer: &'buffer mut B,
}

impl<'buffer, B> Write for AsyncWriter<'buffer, B>
where
    B: Buffer,
{
    fn write(&mut self, buf: &[u8]) -> IOResult<usize> {
        common_buffer_write(self.buffer, &mut self.offset, buf)
    }

    fn flush(&mut self) -> IOResult<()> {
        Ok(())
    }
}

impl<'buffer, B> Seek for AsyncWriter<'buffer, B>
where
    B: Buffer,
{
    fn seek(&mut self, pos: SeekFrom) -> IOResult<u64> {
        common_buffer_seek(self.buffer, &mut self.offset, pos)
    }
}

impl<'buffer, B> AsyncWriter<'buffer, B>
where
    B: Buffer,
{
    /// Try to create an asynchronous writer using the given controller for the given buffer.
    ///
    /// # Errors
    ///
    /// If the buffer is mapped as either readable, writable or executable by the remote process,
    /// this function returns a [`CouldNotCreateAsyncReaderWriter::PermissionsMismatch`] error.
    pub fn try_new<E>(
        ctrl: &mut TargetController<E>,
        buf: &'buffer mut B,
    ) -> Result<Self, CouldNotCreateAsyncReaderWriter>
    where
        E: Executing,
    {
        let mem = memory_mapping(ctrl.process())?;
        let buf_map = mem
            .find(|m| m.start <= buf.address() && buf.address() + buf.length() <= m.end)
            .ok_or(CouldNotCreateAsyncReaderWriter::InvalidAddressRange {
                pid: ctrl.process().pid(),
                start: buf.address(),
                end: buf.address() + buf.length(),
            })?;

        let matcher = PermissionMatcher {
            readable: Some(false),
            writable: Some(false),
            executable: Some(false),
            private: None,
        };

        if buf_map.permissions.matches(&matcher) {
            Ok(AsyncWriter {
                offset: 0,
                buffer: buf,
            })
        } else {
            Err(CouldNotCreateAsyncReaderWriter::PermissionsMismatch {
                expected: matcher,
                got: buf_map.permissions.clone(),
            })
        }
    }
}

/// A reader that can read from the buffer in the remote process while it is still stopped.
///
/// The synchronous buffer allows the user to read from the buffer as long as it is not
/// restarted. This is the safest abstraction provided by steroid to read from a buffer. Indeed, the
/// synchronous reader does not need the process to meed any kind of conditions like [`AsyncReader`]
/// since the process is stopped during the reader's lifetime. Only exterior interferences such as
/// the end user killing the process can make the reader fail.
///
/// # Safety
///
/// Since a synchronous reader only exists when the process is stopped, there is no risk of unwanted
/// data corruption of a buffer by the remote process. Therefore, one can consider [`SyncReader`] as
/// the safest type of buffer reader steroid provides. However, such guaranties impose that a
/// [`SyncReader`] is created using a controller and exists only as long as the same controller
/// lives.
///
/// The following snippet of code is valid:
/// ```
/// # use std::io::Read;
/// # use std::path::PathBuf;
/// # use anyhow::Error;
/// # use steroid::process::spawn_process;
/// # use steroid::run::{Executing};
/// # use steroid::buffer::{remote_view, SyncReader};
/// # use steroid::breakpoint::{breakpoint, Breakpoint, Mode};
/// #
/// # let mut SOME_PROCESS = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
/// # SOME_PROCESS.push("resources/test/say_hello_no_pie");
/// # let SOME_ADDRESS: usize = 0x401126;
/// # let mut process = spawn_process(SOME_PROCESS, [""])?;
/// let mut ctrl = process.wait()?.assume_alive()?;
///
/// let buffer = remote_view(ctrl.process(), SOME_ADDRESS, 50).unwrap();
/// let mut reader = SyncReader::new(&mut ctrl, &buffer).unwrap();
///
/// // Read things
/// let mut buf: [u8; 10] = Default::default();
/// reader.read(&mut buf).unwrap();
///
/// ctrl.resume()?;
/// # Ok::<(), Error>(())
/// ```
///
/// While this one cannot compile:
/// ```compile_fail
/// # use std::io::Read;
/// # use std::path::PathBuf;
/// # use steroid::process::{spawn_process, Error};
/// # use steroid::process::Executing;
/// # use steroid::buffer::{remote_view, SyncReader};
/// # use steroid::breakpoint::{breakpoint, Breakpoint, Mode};
/// #
/// # let mut SOME_PROCESS = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
/// # SOME_PROCESS.push("resources/test/say_hello_no_pie");
/// # let SOME_ADDRESS: usize = 0x401126;
/// # let mut process = spawn_process(SOME_PROCESS, [""])?;
/// let mut ctrl = process.wait()?;
///
/// let buffer = remote_view(ctrl.process(), SOME_ADDRESS, 50).unwrap();
/// let mut reader = SyncReader::new(&mut ctrl, &buffer).unwrap();
///
/// // Read things
/// let mut buf: [u8; 10] = Default::default();
/// reader.read(&mut buf).unwrap();
///
/// ctrl.resume()?;
///
/// // Try reading after the process restarted
/// let mut buf: [u8; 10] = Default::default();
/// reader.read(&mut buf).unwrap();
/// # Ok::<(), Error>(())
/// ```
pub struct SyncReader<'buffer, 'ctrl, B, E>
where
    B: Buffer,
    E: Executing,
{
    buffer: &'buffer B,
    ctrl: &'ctrl mut TargetController<E>,
    offset: usize,
}

impl<'buffer, 'ctrl, B, E> Read for SyncReader<'buffer, 'ctrl, B, E>
where
    B: Buffer,
    E: Executing,
{
    fn read(&mut self, buf: &mut [u8]) -> IOResult<usize> {
        common_buffer_read(self.buffer, &mut self.offset, buf)
    }
}

impl<'buffer, 'ctrl, B, E> Seek for SyncReader<'buffer, 'ctrl, B, E>
where
    B: Buffer,
    E: Executing,
{
    fn seek(&mut self, pos: SeekFrom) -> IOResult<u64> {
        common_buffer_seek(self.buffer, &mut self.offset, pos)
    }
}

impl<'buffer, 'ctrl, B, E> SyncReader<'buffer, 'ctrl, B, E>
where
    B: Buffer,
    E: Executing,
{
    /// Create a new synchronous reader for the buffer using the given controller.
    ///
    /// # Errors
    ///
    /// This function checks that the buffer still exists in memory to create the reader. If it is
    /// not the case, an error [`CouldNotCreateSyncReaderWriter::InvalidAddressRange`] is returned.
    pub fn new(
        ctrl: &'ctrl mut TargetController<E>,
        buffer: &'buffer B,
    ) -> Result<Self, CouldNotCreateSyncReaderWriter> {
        let mem = memory_mapping(ctrl.process())?;
        mem.find(|m| m.start <= buffer.address() && buffer.address() + buffer.length() <= m.end)
            .ok_or(CouldNotCreateSyncReaderWriter::InvalidAddressRange {
                pid: ctrl.process().pid(),
                start: buffer.address(),
                end: buffer.address() + buffer.length(),
            })?;

        Ok(SyncReader {
            buffer,
            ctrl,
            offset: 0,
        })
    }

    /// Get a mutable reference to the controller currently borrowed by the reader.
    ///
    /// Since the reader borrows the controller to ensure it does not exist anymore once the process
    /// restart, this getter method allows the user to use the controller while a synchronous reader
    /// exists.
    pub fn controller(&mut self) -> &mut TargetController<E> {
        self.ctrl
    }
}

/// A writer that can read from the buffer in the remote process while it is still stopped.
///
/// The synchronous buffer allows the user to writ from the buffer as long as it is not
/// restarted. This is the safest abstraction provided by steroid to writ from a buffer. Indeed, the
/// synchronous writer does not need the process to meed any kind of conditions like [`AsyncWriter`]
/// since the process is stopped during the writer's lifetime. Only exterior interferences such as
/// the end user killing the process can make the writer fail.
///
/// # Safety
///
/// Since a synchronous writer only exists when the process is stopped, there is no risk of unwanted
/// data corruption of a buffer by the remote process. Therefore, one can consider [`SyncWriter`] as
/// the safest type of buffer writer steroid provides. However, such guaranties impose that a
/// [`SyncWriter`] is created using a controller and exists only as long as the same controller
/// lives.
///
/// [`SyncReader`]'s documentation provides a good example of how synchronous readers/writers work.
pub struct SyncWriter<'buffer, 'ctrl, B, E>
where
    B: Buffer,
    E: Executing,
{
    buffer: &'buffer mut B,
    ctrl: &'ctrl mut TargetController<E>,
    offset: usize,
}

impl<'buffer, 'ctrl, B, E> Write for SyncWriter<'buffer, 'ctrl, B, E>
where
    B: Buffer,
    E: Executing,
{
    fn write(&mut self, buf: &[u8]) -> IOResult<usize> {
        common_buffer_write(self.buffer, &mut self.offset, buf)
    }

    fn flush(&mut self) -> IOResult<()> {
        Ok(())
    }
}

impl<'buffer, 'ctrl, B, E> Seek for SyncWriter<'buffer, 'ctrl, B, E>
where
    B: Buffer,
    E: Executing,
{
    fn seek(&mut self, pos: SeekFrom) -> IOResult<u64> {
        common_buffer_seek(self.buffer, &mut self.offset, pos)
    }
}

impl<'buffer, 'ctrl, B, E> SyncWriter<'buffer, 'ctrl, B, E>
where
    B: Buffer,
    E: Executing,
{
    /// Create a new synchronous writer for the buffer using the given controller.
    ///
    /// # Errors
    ///
    /// This function checks that the buffer still exists in memory to create the writer. If it is
    /// not the case, an error [`CouldNotCreateSyncReaderWriter::InvalidAddressRange`] is returned.
    pub fn new(
        ctrl: &'ctrl mut TargetController<E>,
        buffer: &'buffer mut B,
    ) -> Result<Self, CouldNotCreateSyncReaderWriter> {
        let mem = memory_mapping(ctrl.process())?;
        mem.find(|m| m.start <= buffer.address() && buffer.address() + buffer.length() <= m.end)
            .ok_or(CouldNotCreateSyncReaderWriter::InvalidAddressRange {
                pid: ctrl.process().pid(),
                start: buffer.address(),
                end: buffer.address() + buffer.length(),
            })?;

        Ok(SyncWriter {
            buffer,
            ctrl,
            offset: 0,
        })
    }

    /// Get a mutable reference to the controller currently borrowed by the writer.
    ///
    /// Since the writer borrows the controller to ensure it does not exist anymore once the process
    /// restart, this getter method allows the user to use the controller while a synchronous writer
    /// exists.
    pub fn controller(&mut self) -> &mut TargetController<E> {
        self.ctrl
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use anyhow::Error as AnyError;

    use crate::mapping::Permissions;
    use crate::process::spawn_process;

    use super::*;

    #[test]
    fn unsafe_read_some_code() -> Result<(), AnyError> {
        let mut path_buf = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path_buf.push("resources/test/say_hello_no_pie");
        let process = spawn_process::<_, _, &str>(path_buf, vec![])?;
        let ctrl = process.wait()?.assume_alive()?;

        let buffer = remote_view(ctrl.process(), 0x0040_1126, 30)?;

        unsafe {
            let mut reader = UnsafeReader::new(&buffer);
            let mut buf: [u8; 5] = Default::default();

            let count = reader.read(&mut buf)?;
            assert_eq!(count, 5);
            assert_eq!(buf, [0x55, 0x48, 0x89, 0xe5, 0x48]);
        }

        let process = ctrl.resume()?;

        let state = process.wait()?;
        assert!(state.has_exited(), "{}", state.reason());

        Ok(())
    }

    #[test]
    fn async_read_some_code() -> Result<(), AnyError> {
        let mut path_buf = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        path_buf.push("resources/test/say_hello_no_pie");
        let process = spawn_process::<_, _, &str>(path_buf, vec![])?;
        let mut ctrl = process.wait()?.assume_alive()?;

        let buffer = remote_view(ctrl.process(), 0x0040_1126, 50)?;
        let mut reader = AsyncReader::try_new(&mut ctrl, &buffer)?;
        let mut buf: [u8; 5] = Default::default();
        let count = reader.read(&mut buf)?;
        assert_eq!(count, 5);
        assert_eq!(buf, [0x55, 0x48, 0x89, 0xe5, 0x48]);

        let process = ctrl.resume()?;

        let state = process.wait()?;
        assert!(state.has_exited(), "{}", state.reason());

        Ok(())
    }

    #[test]
    fn buffer_allocation() -> Result<(), AnyError> {
        let process = spawn_process("/bin/ls", ["-l"])?;
        let mut ctrl = process.wait()?.assume_alive()?;

        let buffer = allocate_buffer(&mut ctrl, 1000, PROT_READ)?;
        assert_ne!(buffer.address(), 0);

        let mapping = memory_mapping(ctrl.process()).unwrap();
        let opt = mapping.find(|m| m.start == buffer.address());

        assert!(opt.is_some());

        let m = opt.unwrap();

        assert_eq!(
            m.permissions,
            Permissions {
                readable: true,
                writable: false,
                executable: false,
                private: true
            }
        );
        assert!(m.is_anonymous());

        let process = ctrl.resume()?;

        let state = process.wait()?;
        assert!(state.has_exited(), "{}", state.reason());
        Ok(())
    }

    #[test]
    fn buffer_deallocation() -> Result<(), AnyError> {
        let process = spawn_process("/bin/ls", ["-l"])?;
        let mut ctrl = process.wait()?.assume_alive()?;

        let buffer = allocate_buffer(&mut ctrl, 1000, PROT_READ)?;

        buffer.deallocate(&mut ctrl)?;

        let process = ctrl.resume()?;

        let state = process.wait()?;
        assert!(state.has_exited(), "{}", state.reason());
        Ok(())
    }
}