dll-syringe 0.18.2

A windows dll injection library written in rust.
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
use std::{
    fmt::{self, Display},
    io,
};

use num_enum::{IntoPrimitive, TryFromPrimitive, TryFromPrimitiveError};
use thiserror::Error;
use windows_sys::Win32::Foundation::{
    EXCEPTION_ACCESS_VIOLATION, EXCEPTION_ARRAY_BOUNDS_EXCEEDED, EXCEPTION_BREAKPOINT,
    EXCEPTION_DATATYPE_MISALIGNMENT, EXCEPTION_FLT_DENORMAL_OPERAND, EXCEPTION_FLT_DIVIDE_BY_ZERO,
    EXCEPTION_FLT_INEXACT_RESULT, EXCEPTION_FLT_INVALID_OPERATION, EXCEPTION_FLT_OVERFLOW,
    EXCEPTION_FLT_STACK_CHECK, EXCEPTION_FLT_UNDERFLOW, EXCEPTION_GUARD_PAGE,
    EXCEPTION_ILLEGAL_INSTRUCTION, EXCEPTION_IN_PAGE_ERROR, EXCEPTION_INT_DIVIDE_BY_ZERO,
    EXCEPTION_INT_OVERFLOW, EXCEPTION_INVALID_DISPOSITION, EXCEPTION_INVALID_HANDLE,
    EXCEPTION_NONCONTINUABLE_EXCEPTION, EXCEPTION_PRIV_INSTRUCTION, EXCEPTION_SINGLE_STEP,
    EXCEPTION_STACK_OVERFLOW, STATUS_UNWIND_CONSOLIDATE,
};

#[cfg(feature = "syringe")]
use windows_sys::Win32::Foundation::ERROR_PARTIAL_COPY;

#[derive(Debug, Error)]
/// Error enum representing either a windows api error or a nul error from an invalid interior nul.
pub enum IoOrNulError {
    /// Variant representing an illegal interior nul value.
    #[error("interior nul found")]
    Nul(#[from] widestring::error::ContainsNul<u16>),
    /// Variant representing an windows api error.
    #[error("io error: {}", _0)]
    Io(#[from] io::Error),
}

/// Error enum for errors during a call to [`ProcessModule::get_local_procedure_address`].
///
/// [`ProcessModule::get_local_procedure_address`]: crate::process::ProcessModule::get_local_procedure_address
#[derive(Debug, Error)]
pub enum GetLocalProcedureAddressError {
    /// Variant representing an illegal interior nul value.
    #[error("interior nul found")]
    Nul(#[from] std::ffi::NulError),
    /// Variant representing an windows api error.
    #[error("io error: {}", _0)]
    Io(#[from] io::Error),
    /// Variant representing an unsupported target process.
    #[error("unsupported remote target process")]
    UnsupportedRemoteTarget,
}

#[derive(
    Debug, TryFromPrimitive, IntoPrimitive, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash,
)]
#[repr(i32)]
/// Codes for unhandled windows exceptions from [msdn](https://docs.microsoft.com/en-us/windows/win32/debug/getexceptioncode).
pub enum ExceptionCode {
    /// The thread attempts to read from or write to a virtual address for which it does not have access.
    AccessViolation = EXCEPTION_ACCESS_VIOLATION,
    /// The thread attempts to access an array element that is out of bounds, and the underlying hardware supports bounds checking.
    ArrayBoundsExceeded = EXCEPTION_ARRAY_BOUNDS_EXCEEDED,
    /// A breakpoint is encountered.
    Breakpoint = EXCEPTION_BREAKPOINT,
    /// The thread attempts to read or write data that is misaligned on hardware that does not provide alignment.
    /// For example, 16-bit values must be aligned on 2-byte boundaries, 32-bit values on 4-byte boundaries, and so on.
    DatatypeMisalignment = EXCEPTION_DATATYPE_MISALIGNMENT,
    /// One of the operands in a floating point operation is denormal.
    /// A denormal value is one that is too small to represent as a standard floating point value.
    FltDenormalOperand = EXCEPTION_FLT_DENORMAL_OPERAND,
    /// The thread attempts to divide a floating point value by a floating point divisor of 0 (zero).
    FltDivideByZero = EXCEPTION_FLT_DIVIDE_BY_ZERO,
    /// The result of a floating point operation cannot be represented exactly as a decimal fraction.
    FltInexactResult = EXCEPTION_FLT_INEXACT_RESULT,
    /// A floating point exception that is not included in this list.
    FltInvalidOperation = EXCEPTION_FLT_INVALID_OPERATION,
    /// The exponent of a floating point operation is greater than the magnitude allowed by the corresponding type.
    FltOverflow = EXCEPTION_FLT_OVERFLOW,
    /// The stack has overflowed or underflowed, because of a floating point operation.
    FltStackCheck = EXCEPTION_FLT_STACK_CHECK,
    /// The exponent of a floating point operation is less than the magnitude allowed by the corresponding type.
    FltUnderflow = EXCEPTION_FLT_UNDERFLOW,
    /// The thread accessed memory allocated with the `PAGE_GUARD` modifier.
    GuardPage = EXCEPTION_GUARD_PAGE,
    /// The thread tries to execute an invalid instruction.
    IllegalInstruction = EXCEPTION_ILLEGAL_INSTRUCTION,
    /// The thread tries to access a page that is not present, and the system is unable to load the page.
    /// For example, this exception might occur if a network connection is lost while running a program over a network.
    InPageError = EXCEPTION_IN_PAGE_ERROR,
    /// The thread attempts to divide an integer value by an integer divisor of 0 (zero).
    IntegerDivideByZero = EXCEPTION_INT_DIVIDE_BY_ZERO,
    /// The result of an integer operation creates a value that is too large to be held by the destination register.
    /// In some cases, this will result in a carry out of the most significant bit of the result.
    /// Some operations do not set the carry flag.
    IntegerOverflow = EXCEPTION_INT_OVERFLOW,
    /// An exception handler returns an invalid disposition to the exception dispatcher.
    /// Programmers using a high-level language such as C should never encounter this exception.
    InvalidDisposition = EXCEPTION_INVALID_DISPOSITION,
    /// The thread used a handle to a kernel object that was invalid (probably because it had been closed.)
    InvalidHandle = EXCEPTION_INVALID_HANDLE,
    /// The thread attempts to continue execution after a non-continuable exception occurs.
    NoncontinuableException = EXCEPTION_NONCONTINUABLE_EXCEPTION,
    /// The thread attempts to execute an instruction with an operation that is not allowed in the current computer mode.
    PrivilegedInstruction = EXCEPTION_PRIV_INSTRUCTION,
    /// A trace trap or other single instruction mechanism signals that one instruction is executed.
    SingleStep = EXCEPTION_SINGLE_STEP,
    /// The thread uses up its stack.
    StackOverflow = EXCEPTION_STACK_OVERFLOW,
    /// A frame consolidation has been executed.
    UnwindConsolidate = STATUS_UNWIND_CONSOLIDATE,
}

impl ExceptionCode {
    /// Try to interpret the given code as a windows exception code.
    pub fn try_from_code(code: i32) -> Result<Self, TryFromPrimitiveError<Self>> {
        Self::try_from_primitive(code)
    }
    /// Returns the underlying windows exception code.
    #[must_use]
    pub fn code(self) -> i32 {
        self.into()
    }
}

impl Display for ExceptionCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // These error messages were collected using https://stackoverflow.com/a/43961146/6304917 and https://stackoverflow.com/a/7915329/6304917
        // They are hardcoded as they are unlikely appear very often and would require a lot of extra code
        // Additionally, the messages returned from the methods above are sometimes unusable and inconsitently formatted.

        match *self {
            Self::AccessViolation => write!(f, "Invalid access to memory location."),
            Self::ArrayBoundsExceeded => write!(f, "Array bounds exceeded."),
            Self::Breakpoint => write!(f, "A breakpoint has been reached."),
            Self::DatatypeMisalignment => write!(
                f,
                "A datatype misalignment was detected in a load or store instruction."
            ),
            Self::FltDenormalOperand => write!(f, "Floating-point denormal operand."),
            Self::FltDivideByZero => write!(f, "Floating-point division by zero."),
            Self::FltInexactResult => write!(f, "Floating-point inexact result."),
            Self::FltInvalidOperation => write!(f, "Floating-point invalid operation."),
            Self::FltOverflow => write!(f, "Floating-point overflow."),
            Self::FltStackCheck => write!(f, "Floating-point stack check."),
            Self::FltUnderflow => write!(f, "Floating-point underflow."),
            Self::GuardPage => write!(
                f,
                "A page of memory that marks the end of a data structure, such as a stack or an array, has been accessed."
            ),
            Self::IllegalInstruction => {
                write!(f, "An attempt was made to execute an illegal instruction.")
            }
            Self::InPageError => write!(f, "Error performing inpage operation."),
            Self::IntegerDivideByZero => write!(f, "Integer division by zero."),
            Self::IntegerOverflow => write!(f, "Integer overflow."),
            Self::InvalidDisposition => write!(
                f,
                "An invalid exception disposition was returned by an exception handler."
            ),
            Self::InvalidHandle => write!(f, "The handle is invalid."),
            Self::NoncontinuableException => {
                write!(f, "Windows cannot continue from this exception.")
            }
            Self::PrivilegedInstruction => write!(f, "Privileged instruction."),
            Self::SingleStep => write!(
                f,
                "A single step or trace operation has just been completed."
            ),
            Self::StackOverflow => write!(f, "Recursion too deep; the stack overflowed."),
            Self::UnwindConsolidate => write!(f, "A frame consolidation has been executed."),
        }
    }
}

#[derive(Debug, Error)]
/// An error representing either an unhandled exception or an io error.
pub enum ExceptionOrIoError {
    /// Variant representing an io error.
    #[error("remote io error: {}", _0)]
    Io(io::Error),
    /// Variant representing an unhandled exception.
    #[error("remote exception: {}", _0)]
    Exception(ExceptionCode),
}

/// Error enum for errors during [`Syringe::load_inject_help_data_for_process`](crate::Syringe::load_inject_help_data_for_process).
#[derive(Debug, Error)]
#[cfg(feature = "syringe")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "syringe")))]
pub(crate) enum LoadInjectHelpDataError {
    /// Variant representing an io error.
    #[error("io error: {}", _0)]
    Io(io::Error),
    /// Variant representing an unsupported target process.
    #[error("unsupported target process")]
    UnsupportedTarget,
    /// Variant representing an inaccessible target process.
    /// This can occur if it crashed or was terminated.
    #[error("inaccessible target process")]
    ProcessInaccessible,
    /// Variant representing an error while loading an pe file.
    #[cfg(target_arch = "x86_64")]
    #[cfg(feature = "into-x86-from-x64")]
    #[error("failed to load pe file: {}", _0)]
    Goblin(#[from] goblin::error::Error),
}

#[cfg(feature = "syringe")]
impl From<io::Error> for LoadInjectHelpDataError {
    fn from(err: io::Error) -> Self {
        if err.raw_os_error() == Some(ERROR_PARTIAL_COPY.cast_signed())
            || err.kind() == io::ErrorKind::PermissionDenied
        {
            Self::ProcessInaccessible
        } else {
            Self::Io(err)
        }
    }
}

/// Error enum for errors during [`Syringe::inject`](crate::Syringe::inject).
#[derive(Debug, Error)]
#[cfg(feature = "syringe")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "syringe")))]
pub enum InjectError {
    /// Variant representing an illegal interior nul value in the module path.
    #[error("module path contains illegal interior nul")]
    IllegalPath(#[from] widestring::error::ContainsNul<u16>),
    /// Variant representing an io error.
    #[error("io error: {}", _0)]
    Io(io::Error),
    /// Variant representing an unsupported target process.
    #[error("unsupported target process")]
    UnsupportedTarget,
    /// Variant representing an io error inside the target process.
    #[error("remote io error: {}", _0)]
    RemoteIo(io::Error),
    /// Variant representing an unhandled exception inside the target process.
    #[error("remote exception: {}", _0)]
    RemoteException(ExceptionCode),
    /// Variant representing an inaccessible target process.
    /// This can occur if it crashed or was terminated.
    #[error("inaccessible target process")]
    ProcessInaccessible,
    /// Variant representing an incompatible payload module compiled for a different target than the target process.
    #[error("mismatch between target and payload architecture")]
    ArchitectureMismatch,
    /// Variant representing an error while loading an pe file.
    #[cfg(target_arch = "x86_64")]
    #[cfg(feature = "into-x86-from-x64")]
    #[error("failed to load pe file: {}", _0)]
    Goblin(#[from] goblin::error::Error),
}

#[cfg(feature = "syringe")]
impl From<io::Error> for InjectError {
    fn from(err: io::Error) -> Self {
        if err.raw_os_error() == Some(ERROR_PARTIAL_COPY.cast_signed())
            || err.kind() == io::ErrorKind::PermissionDenied
        {
            Self::ProcessInaccessible
        } else {
            Self::Io(err)
        }
    }
}

#[cfg(feature = "syringe")]
impl From<ExceptionCode> for InjectError {
    fn from(err: ExceptionCode) -> Self {
        Self::RemoteException(err)
    }
}

#[cfg(feature = "syringe")]
impl From<IoOrNulError> for InjectError {
    fn from(err: IoOrNulError) -> Self {
        match err {
            IoOrNulError::Nul(e) => e.into(),
            IoOrNulError::Io(e) => e.into(),
        }
    }
}

#[cfg(feature = "syringe")]
impl From<ExceptionOrIoError> for InjectError {
    fn from(err: ExceptionOrIoError) -> Self {
        match err {
            ExceptionOrIoError::Io(e) => Self::RemoteIo(e),
            ExceptionOrIoError::Exception(e) => Self::RemoteException(e),
        }
    }
}

#[cfg(feature = "syringe")]
impl From<LoadInjectHelpDataError> for InjectError {
    fn from(err: LoadInjectHelpDataError) -> Self {
        match err {
            LoadInjectHelpDataError::Io(e) => Self::Io(e),
            LoadInjectHelpDataError::UnsupportedTarget => Self::UnsupportedTarget,
            LoadInjectHelpDataError::ProcessInaccessible => Self::ProcessInaccessible,
            #[cfg(target_arch = "x86_64")]
            #[cfg(feature = "into-x86-from-x64")]
            LoadInjectHelpDataError::Goblin(e) => Self::Goblin(e),
        }
    }
}

/// Error enum for errors during [`Syringe::eject`](crate::Syringe::eject).
#[derive(Debug, Error)]
#[cfg(feature = "syringe")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "syringe")))]
pub enum EjectError {
    /// Variant representing an io error.
    #[error("io error: {}", _0)]
    Io(io::Error),
    /// Variant representing an unsupported target process.
    #[error("unsupported target process")]
    UnsupportedTarget,
    /// Variant representing an io error inside the target process.
    #[error("remote io error: {}", _0)]
    RemoteIo(io::Error),
    /// Variant representing an unhandled exception inside the target process.
    #[error("remote exception: {}", _0)]
    RemoteException(ExceptionCode),
    /// Variant representing an inaccessible target process.
    /// This can occur if it crashed or was terminated.
    #[error("inaccessible target process")]
    ProcessInaccessible,
    /// Variant representing an inaccessible target module.
    /// This can occur if the target module was ejected or unloaded.
    #[error("inaccessible target module")]
    ModuleInaccessible,
    /// Variant representing an error while loading an pe file.
    #[cfg(target_arch = "x86_64")]
    #[cfg(feature = "into-x86-from-x64")]
    #[error("failed to load pe file: {}", _0)]
    Goblin(#[from] goblin::error::Error),
}

#[cfg(feature = "syringe")]
impl From<LoadInjectHelpDataError> for EjectError {
    fn from(err: LoadInjectHelpDataError) -> Self {
        match err {
            LoadInjectHelpDataError::Io(e) => Self::Io(e),
            LoadInjectHelpDataError::UnsupportedTarget => Self::UnsupportedTarget,
            LoadInjectHelpDataError::ProcessInaccessible => Self::ProcessInaccessible,
            #[cfg(target_arch = "x86_64")]
            #[cfg(feature = "into-x86-from-x64")]
            LoadInjectHelpDataError::Goblin(e) => Self::Goblin(e),
        }
    }
}

#[cfg(feature = "syringe")]
impl From<io::Error> for EjectError {
    fn from(err: io::Error) -> Self {
        if err.raw_os_error() == Some(ERROR_PARTIAL_COPY.cast_signed())
            || err.kind() == io::ErrorKind::PermissionDenied
        {
            Self::ProcessInaccessible
        } else {
            Self::Io(err)
        }
    }
}

#[cfg(feature = "syringe")]
impl From<ExceptionCode> for EjectError {
    fn from(err: ExceptionCode) -> Self {
        Self::RemoteException(err)
    }
}

#[cfg(feature = "syringe")]
impl From<ExceptionOrIoError> for EjectError {
    fn from(err: ExceptionOrIoError) -> Self {
        match err {
            ExceptionOrIoError::Io(e) => Self::RemoteIo(e),
            ExceptionOrIoError::Exception(e) => Self::RemoteException(e),
        }
    }
}

/// Error enum for errors during procedure loading.
#[derive(Debug, Error)]
#[cfg(feature = "syringe")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "syringe")))]
pub enum LoadProcedureError {
    /// Variant representing an io error.
    #[error("io error: {}", _0)]
    Io(io::Error),
    /// Variant representing an unsupported target process.
    #[error("unsupported target process")]
    UnsupportedTarget,
    /// Variant representing an io error inside the target process.
    #[error("remote io error: {}", _0)]
    RemoteIo(io::Error),
    /// Variant representing an unhandled exception inside the target process.
    #[error("remote exception: {}", _0)]
    RemoteException(ExceptionCode),
    /// Variant representing an inaccessible target process.
    /// This can occur if it crashed or was terminated.
    #[error("inaccessible target process")]
    ProcessInaccessible,
    /// Variant representing an inaccessible target module.
    /// This can occur if the target module was ejected or unloaded.
    #[error("inaccessible target module")]
    ModuleInaccessible,
    /// Variant representing an error while loading an pe file.
    #[cfg(target_arch = "x86_64")]
    #[cfg(feature = "into-x86-from-x64")]
    #[error("failed to load pe file: {}", _0)]
    Goblin(#[from] goblin::error::Error),
}

#[cfg(feature = "syringe")]
impl From<LoadInjectHelpDataError> for LoadProcedureError {
    fn from(err: LoadInjectHelpDataError) -> Self {
        match err {
            LoadInjectHelpDataError::Io(e) => Self::Io(e),
            LoadInjectHelpDataError::UnsupportedTarget => Self::UnsupportedTarget,
            LoadInjectHelpDataError::ProcessInaccessible => Self::ProcessInaccessible,
            #[cfg(target_arch = "x86_64")]
            #[cfg(feature = "into-x86-from-x64")]
            LoadInjectHelpDataError::Goblin(e) => Self::Goblin(e),
        }
    }
}

#[cfg(feature = "syringe")]
impl From<io::Error> for LoadProcedureError {
    fn from(err: io::Error) -> Self {
        if err.raw_os_error() == Some(ERROR_PARTIAL_COPY.cast_signed())
            || err.kind() == io::ErrorKind::PermissionDenied
        {
            Self::ProcessInaccessible
        } else {
            Self::Io(err)
        }
    }
}

#[cfg(feature = "syringe")]
impl From<ExceptionCode> for LoadProcedureError {
    fn from(err: ExceptionCode) -> Self {
        Self::RemoteException(err)
    }
}

#[cfg(feature = "syringe")]
impl From<ExceptionOrIoError> for LoadProcedureError {
    fn from(err: ExceptionOrIoError) -> Self {
        match err {
            ExceptionOrIoError::Io(e) => Self::RemoteIo(e),
            ExceptionOrIoError::Exception(e) => Self::RemoteException(e),
        }
    }
}

/// Error enum encompassing all errors during [`Syringe`](crate::Syringe) operations.
#[derive(Debug, Error)]
#[cfg(feature = "syringe")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "syringe")))]
pub enum SyringeError {
    /// Variant representing an illegal interior nul value in the module path.
    #[error("module path contains illegal interior nul")]
    IllegalPath(#[from] widestring::error::ContainsNul<u16>),
    /// Variant representing an io error.
    #[error("io error: {}", _0)]
    Io(io::Error),
    /// Variant representing an unsupported target process.
    #[error("unsupported target process")]
    UnsupportedTarget,
    /// Variant representing an io error inside the target process.
    #[error("remote io error: {}", _0)]
    RemoteIo(io::Error),
    /// Variant representing an unhandled exception inside the target process.
    #[error("remote exception: {}", _0)]
    RemoteException(ExceptionCode),
    /// Variant representing an inaccessible target process.
    /// This can occur if it crashed or was terminated.
    #[error("inaccessible target process")]
    ProcessInaccessible,
    /// Variant representing an incompatible payload module compiled for a different target than the target process.
    #[error("mismatch between target and payload architecture")]
    ArchitectureMismatch,
    /// Variant representing an inaccessible target module.
    /// This can occur if the target module was ejected or unloaded.
    #[error("inaccessible target module")]
    ModuleInaccessible,
    /// Variant representing an error while serializing or deserializing.
    #[cfg(feature = "rpc-payload")]
    #[error("serde error: {}", _0)]
    Serde(crate::rpc::SerdeError),
    /// Variant representing an error or panic inside a remote payload procedure.
    #[cfg(feature = "rpc-payload")]
    #[error("remote payload error: {}", _0)]
    RemotePayloadProcedure(String),
    /// Variant representing an error while loading an pe file.
    #[cfg(target_arch = "x86_64")]
    #[cfg(feature = "into-x86-from-x64")]
    #[error("failed to load pe file: {}", _0)]
    Goblin(#[from] goblin::error::Error),
}

#[cfg(feature = "syringe")]
impl From<io::Error> for SyringeError {
    fn from(err: io::Error) -> Self {
        if err.raw_os_error() == Some(ERROR_PARTIAL_COPY.cast_signed())
            || err.kind() == io::ErrorKind::PermissionDenied
        {
            Self::ProcessInaccessible
        } else {
            Self::Io(err)
        }
    }
}

#[cfg(feature = "syringe")]
impl From<ExceptionCode> for SyringeError {
    fn from(err: ExceptionCode) -> Self {
        Self::RemoteException(err)
    }
}

#[cfg(feature = "syringe")]
impl From<IoOrNulError> for SyringeError {
    fn from(err: IoOrNulError) -> Self {
        match err {
            IoOrNulError::Nul(e) => e.into(),
            IoOrNulError::Io(e) => e.into(),
        }
    }
}

#[cfg(feature = "syringe")]
impl From<ExceptionOrIoError> for SyringeError {
    fn from(err: ExceptionOrIoError) -> Self {
        match err {
            ExceptionOrIoError::Io(e) => Self::RemoteIo(e),
            ExceptionOrIoError::Exception(e) => Self::RemoteException(e),
        }
    }
}

#[cfg(feature = "syringe")]
impl From<InjectError> for SyringeError {
    fn from(err: InjectError) -> Self {
        match err {
            InjectError::IllegalPath(e) => Self::IllegalPath(e),
            InjectError::Io(e) => Self::Io(e),
            InjectError::UnsupportedTarget => Self::UnsupportedTarget,
            InjectError::RemoteIo(e) => Self::RemoteIo(e),
            InjectError::RemoteException(e) => Self::RemoteException(e),
            InjectError::ProcessInaccessible => Self::ProcessInaccessible,
            InjectError::ArchitectureMismatch => Self::ArchitectureMismatch,
            #[cfg(target_arch = "x86_64")]
            #[cfg(feature = "into-x86-from-x64")]
            InjectError::Goblin(e) => Self::Goblin(e),
        }
    }
}

#[cfg(feature = "syringe")]
impl From<EjectError> for SyringeError {
    fn from(err: EjectError) -> Self {
        match err {
            EjectError::Io(e) => Self::Io(e),
            EjectError::UnsupportedTarget => Self::UnsupportedTarget,
            EjectError::RemoteIo(e) => Self::RemoteIo(e),
            EjectError::RemoteException(e) => Self::RemoteException(e),
            EjectError::ProcessInaccessible => Self::ProcessInaccessible,
            EjectError::ModuleInaccessible => Self::ModuleInaccessible,
            #[cfg(target_arch = "x86_64")]
            #[cfg(feature = "into-x86-from-x64")]
            EjectError::Goblin(e) => Self::Goblin(e),
        }
    }
}

#[cfg(feature = "rpc-core")]
impl From<LoadProcedureError> for SyringeError {
    fn from(err: LoadProcedureError) -> Self {
        match err {
            LoadProcedureError::Io(e) => Self::Io(e),
            LoadProcedureError::UnsupportedTarget => Self::UnsupportedTarget,
            LoadProcedureError::RemoteIo(e) => Self::RemoteIo(e),
            LoadProcedureError::RemoteException(e) => Self::RemoteException(e),
            LoadProcedureError::ProcessInaccessible => Self::ProcessInaccessible,
            LoadProcedureError::ModuleInaccessible => Self::ModuleInaccessible,
            #[cfg(target_arch = "x86_64")]
            #[cfg(feature = "into-x86-from-x64")]
            LoadProcedureError::Goblin(e) => Self::Goblin(e),
        }
    }
}

#[cfg(feature = "rpc-core")]
#[cfg_attr(all(feature = "rpc-core", not(feature = "rpc-raw")), doc(hidden))]
impl From<crate::rpc::RawRpcError> for SyringeError {
    fn from(err: crate::rpc::RawRpcError) -> Self {
        match err {
            crate::rpc::RawRpcError::Io(err) => Self::Io(err),
            crate::rpc::RawRpcError::RemoteException(code) => Self::RemoteException(code),
            crate::rpc::RawRpcError::ProcessInaccessible => Self::ProcessInaccessible,
            crate::rpc::RawRpcError::ModuleInaccessible => Self::ModuleInaccessible,
        }
    }
}

#[cfg(feature = "rpc-payload")]
#[cfg_attr(all(feature = "rpc-core", not(feature = "rpc-raw")), doc(hidden))]
impl From<crate::rpc::PayloadRpcError> for SyringeError {
    fn from(err: crate::rpc::PayloadRpcError) -> Self {
        match err {
            crate::rpc::PayloadRpcError::Io(e) => Self::Io(e),
            crate::rpc::PayloadRpcError::RemoteException(e) => Self::RemoteException(e),
            crate::rpc::PayloadRpcError::ProcessInaccessible => Self::ProcessInaccessible,
            crate::rpc::PayloadRpcError::ModuleInaccessible => Self::ModuleInaccessible,
            crate::rpc::PayloadRpcError::RemoteProcedure(e) => Self::RemotePayloadProcedure(e),
            crate::rpc::PayloadRpcError::Serde(e) => Self::Serde(e),
        }
    }
}

/// Error enum encompassing all errors during syringe operations in a nested format.
#[derive(Debug, Error)]
#[cfg(feature = "syringe")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "syringe")))]
pub enum SyringeOperationError {
    /// Variant representing an error while injecting a module.
    #[error("inject error: {}", _0)]
    Inject(#[from] InjectError),
    /// Variant representing an error while ejecting a module.
    #[error("eject error: {}", _0)]
    Eject(#[from] EjectError),
    /// Variant representing an error while using payload rpc.
    #[cfg(feature = "rpc-payload")]
    #[error("payload rpc error: {}", _0)]
    PayloadProcedureCall(#[from] crate::rpc::PayloadRpcError),
    /// Variant representing an error while using raw rpc.
    #[cfg(feature = "rpc-raw")]
    #[error("raw rpc error: {}", _0)]
    RawProcedureCall(#[from] crate::rpc::RawRpcError),
    /// Variant representing an error while using rpc.
    #[cfg(feature = "rpc-core")]
    #[error("procedure load error: {}", _0)]
    ProcedureLoad(#[from] LoadProcedureError),
}