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
extern crate memmap;
extern crate byteorder;

pub mod mmap;
pub mod components;
pub mod relocations;
pub mod x64;
pub mod x86;
pub mod aarch64;

pub use crate::mmap::ExecutableBuffer;
use crate::components::{MemoryManager, LabelRegistry, RelocRegistry, ManagedRelocs, PatchLoc};
use crate::relocations::Relocation;

use std::iter::Extend;
use std::sync::{Arc, RwLock, RwLockReadGuard};
use std::io;
use std::error;
use std::fmt;
use std::mem;

/// This macro takes a *const pointer from the source operand, and then casts it to the desired return type.
/// this allows it to be used as an easy shorthand for passing pointers as dynasm immediate arguments.
#[macro_export]
macro_rules! Pointer {
    ($e:expr) => {$e as *const _ as _};
}

/// Preforms the same action as the `Pointer!` macro, but casts to a *mut pointer.
#[macro_export]
macro_rules! MutPointer {
    ($e:expr) => {$e as *mut _ as _};
}


/// A struct representing an offset into the assembling buffer of a `DynasmLabelApi` struct.
/// The wrapped `usize` is the offset from the start of the assembling buffer in bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AssemblyOffset(pub usize);

/// A dynamic label
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DynamicLabel(usize);


impl DynamicLabel {
    /// Get the internal ID of this dynamic label. This is only useful for debugging purposes.
    pub fn get_id(self) -> usize {
        self.0
    }
}


/// A read-only shared reference to the executable buffer inside an Assembler. By
/// locking it the internal `ExecutableBuffer` can be accessed and executed.
#[derive(Debug, Clone)]
pub struct Executor {
    execbuffer: Arc<RwLock<ExecutableBuffer>>
}

/// A read-only lockable reference to the internal `ExecutableBuffer` of an Assembler.
/// To gain access to this buffer, it must be locked.
impl Executor {
    /// Gain read-access to the internal `ExecutableBuffer`. While the returned guard
    /// is alive, it can be used to read and execute from the `ExecutableBuffer`.
    /// Any pointers created to the `Executablebuffer` should no longer be used when
    /// the guard is dropped.
    #[inline]
    pub fn lock(&self) -> RwLockReadGuard<ExecutableBuffer> {
        self.execbuffer.read().unwrap()
    }
}


/// A description of a label. Used for error reporting.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LabelKind {
    Local(&'static str),
    Global(&'static str),
    Dynamic(DynamicLabel)
}

impl fmt::Display for LabelKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Local(s) => write!(f, "label {}", s),
            Self::Global(s) => write!(f, "label ->{}", s),
            Self::Dynamic(id) => write!(f, "label =>{}", id.get_id())
        }
    }
}


/// A description of a relocation target. Used for error reporting.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TargetKind {
    Forward(&'static str),
    Backward(&'static str),
    Global(&'static str),
    Dynamic(DynamicLabel),
    Extern(usize),
    Managed,
}

impl fmt::Display for TargetKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Forward(s) => write!(f, "target >{}", s),
            Self::Backward(s) => write!(f, "target <{}", s),
            Self::Global(s) => write!(f, "target ->{}", s),
            Self::Dynamic(id) => write!(f, "target =>{}", id.get_id()),
            Self::Extern(value) => write!(f, "target extern {}", value),
            Self::Managed => write!(f, "while adjusting managed relocation"),
        }
    }
}


/// The various error types generated by dynasm functions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DynasmError {
    /// A check (like `Modifier::check` or `Modifier::check_exact`) that failed
    CheckFailed,
    /// A duplicate label dynamic/global label was defined
    DuplicateLabel(LabelKind),
    /// An unknown label
    UnknownLabel(LabelKind),
    /// The user tried to declare a relocation too far away from the label it targets
    ImpossibleRelocation(TargetKind),
}

impl fmt::Display for DynasmError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            DynasmError::CheckFailed => write!(f, "An assembly modification check failed"),
            DynasmError::DuplicateLabel(l) => write!(f, "Duplicate label defined: '{}'", l),
            DynasmError::UnknownLabel(l) => write!(f, "Unknown label: '{}'", l),
            DynasmError::ImpossibleRelocation(s) => write!(f, "Impossible relocation: '{}'", s),
        }
    }
}

impl error::Error for DynasmError {
    fn description(&self) -> &str {
        match self {
            DynasmError::CheckFailed => "An assembly modification offset check failed",
            DynasmError::DuplicateLabel(_) => "Duplicate label defined",
            DynasmError::UnknownLabel(_) => "Unknown label",
            DynasmError::ImpossibleRelocation(_) => "Impossible relocation",
        }
    }
}


/// This trait represents the interface that must be implemented to allow
/// the dynasm preprocessor to assemble into a datastructure.
pub trait DynasmApi: Extend<u8> + for<'a> Extend<&'a u8> {
    /// Report the current offset into the assembling target
    fn offset(&self) -> AssemblyOffset;
    /// Push a byte into the assembling target
    fn push(&mut self, byte: u8);
    /// Push filler until the assembling target end is aligned to the given alignment.
    fn align(&mut self, alignment: usize, with: u8);

    #[inline]
    /// Push a signed byte into the assembling target
    fn push_i8(&mut self, value: i8) {
        self.push(value as u8);
    }
    /// Push a signed word into the assembling target
    #[inline]
    fn push_i16(&mut self, value: i16) {
        self.extend(&value.to_le_bytes());
    }
    /// Push a signed doubleword into the assembling target
    #[inline]
    fn push_i32(&mut self, value: i32) {
        self.extend(&value.to_le_bytes());
    }
    /// Push a signed quadword into the assembling target
    #[inline]
    fn push_i64(&mut self, value: i64) {
        self.extend(&value.to_le_bytes());
    }
    /// Push an usigned word into the assembling target
    #[inline]
    fn push_u16(&mut self, value: u16) {
        self.extend(&value.to_le_bytes());
    }
    /// Push an usigned doubleword into the assembling target
    #[inline]
    fn push_u32(&mut self, value: u32) {
        self.extend(&value.to_le_bytes());
    }
    /// Push an usigned quadword into the assembling target
    #[inline]
    fn push_u64(&mut self, value: u64) {
        self.extend(&value.to_le_bytes());
    }
    /// This function is called in when a runtime error has to be generated. It panics.
    #[inline]
    fn runtime_error(&self, msg: &'static str) -> ! {
        panic!(msg);
    }
}

/// This trait extends DynasmApi to not only allow assembling, but also labels and various directives
pub trait DynasmLabelApi : DynasmApi {
    /// The relocation info type this assembler uses. 
    type Relocation: Relocation;

    /// Record the definition of a local label
    fn local_label(  &mut self, name: &'static str);
    /// Record the definition of a global label
    fn global_label( &mut self, name: &'static str);
    /// Record the definition of a dynamic label
    fn dynamic_label(&mut self, id: DynamicLabel);

    /// Record a relocation spot for a forward reference to a local label
    fn forward_reloc( &mut self, name: &'static str, offset: isize, kind: <Self::Relocation as Relocation>::Encoding) {
        self.forward_relocation(name, offset, Self::Relocation::from_encoding(kind))
    }
    /// Record a relocation spot for a backward reference to a local label
    fn backward_reloc(&mut self, name: &'static str, offset: isize, kind: <Self::Relocation as Relocation>::Encoding) {
        self.backward_relocation(name, offset, Self::Relocation::from_encoding(kind))
    }
    /// Record a relocation spot for a reference to a global label
    fn global_reloc(  &mut self, name: &'static str, offset: isize, kind: <Self::Relocation as Relocation>::Encoding) {
        self.global_relocation(name, offset, Self::Relocation::from_encoding(kind))
    }
    /// Record a relocation spot for a reference to a dynamic label
    fn dynamic_reloc( &mut self, id: DynamicLabel,   offset: isize, kind: <Self::Relocation as Relocation>::Encoding) {
        self.dynamic_relocation(id, offset, Self::Relocation::from_encoding(kind))
    }
    /// Record a relocation spot to an arbitrary target.
    fn bare_reloc(&mut self, target: usize, kind: <Self::Relocation as Relocation>::Encoding) {
        self.bare_relocation(target, Self::Relocation::from_encoding(kind))
    }

    /// Equivalents of the previous functions but taking non-encoded relocations
    fn forward_relocation( &mut self, name: &'static str, offset: isize, kind: Self::Relocation);
    fn backward_relocation(&mut self, name: &'static str, offset: isize, kind: Self::Relocation);
    fn global_relocation(  &mut self, name: &'static str, offset: isize, kind: Self::Relocation);
    fn dynamic_relocation( &mut self, id: DynamicLabel,   offset: isize, kind: Self::Relocation);
    fn bare_relocation(&mut self, target: usize, kind: Self::Relocation);
}


/// An assembler that is purely a `Vec<u8>`. It doesn't support labels, but can be used to easily inspect generated code.
pub struct VecAssembler(Vec<u8>);

impl Extend<u8> for VecAssembler {
    fn extend<T>(&mut self, iter: T) where T: IntoIterator<Item=u8> {
        self.0.extend(iter)
    }
}

impl<'a> Extend<&'a u8> for VecAssembler {
    fn extend<T>(&mut self, iter: T) where T: IntoIterator<Item=&'a u8> {
        self.0.extend(iter)
    }
}

impl DynasmApi for VecAssembler {
    fn offset(&self) -> AssemblyOffset {
        AssemblyOffset(self.0.len())
    }
    fn push(&mut self, byte: u8) {
        self.0.push(byte);
    }
    fn align(&mut self, alignment: usize, with: u8) {
        let offset = self.offset().0 % alignment;
        if offset != 0 {
            for _ in offset .. alignment {
                self.push(with);
            }
        }
    }
}

/// A full assembler implementation. Supports labels, all types of relocations,
/// incremental compilation and multithreaded execution with simultaneous compiltion.
/// Its implementation guarantees no memory is executable and writable at the same time.
#[derive(Debug)]
pub struct Assembler<R: Relocation> {
    ops: Vec<u8>,
    memory: MemoryManager,
    labels: LabelRegistry,
    relocs: RelocRegistry<R>,
    managed: ManagedRelocs<R>,
    error: Option<DynasmError>,
}

impl<R: Relocation> Assembler<R> {
    /// Create a new, empty assembler, with initial allocation size `page_size`.
    pub fn new() -> io::Result<Self> {
        Ok(Self {
            ops: Vec::new(),
            memory: MemoryManager::new(R::page_size())?,
            labels: LabelRegistry::new(),
            relocs: RelocRegistry::new(),
            managed: ManagedRelocs::new(),
            error: None
        })
    }

    /// Create a new dynamic label ID
    pub fn new_dynamic_label(&mut self) -> DynamicLabel {
        self.labels.new_dynamic_label()
    }

    /// Use an `UncommittedModifier` to alter uncommitted code.
    /// This does not allow the user to change labels/relocations.
    pub fn alter_uncommitted(&mut self) -> UncommittedModifier {
        let offset = self.memory.committed();
        UncommittedModifier::new(&mut self.ops, AssemblyOffset(offset))
    }

    /// Use a `Modifier` to alter committed code directly. While this is happening
    /// no code can be executed as the relevant pages are remapped as writable.
    /// This API supports defining new labels/relocations, and overwriting previously defined relocations.
    pub fn alter<F, O>(&mut self, f: F) -> Result<O, DynasmError>
    where F: FnOnce(&mut Modifier<R>) -> O {
        self.commit()?;

        // swap out a buffer from base
        let mut lock = self.memory.write();
        let buffer = mem::replace(&mut *lock, ExecutableBuffer::default());
        let mut buffer = buffer.make_mut().expect("Could not swap buffer protection modes");

        // construct the modifier
        let mut modifier = Modifier {
            asmoffset: 0,
            previous_asmoffset: 0,
            buffer: &mut *buffer,

            labels: &mut self.labels,
            relocs: &mut self.relocs,
            old_managed: &mut self.managed,
            new_managed: ManagedRelocs::new(),

            error: None
        };

        // execute the user code
        let output = f(&mut modifier);

        // flush any changes made by the user code to the buffer
        modifier.encode_relocs()?;

        // repack the buffer
        let buffer = buffer.make_exec().expect("Could not swap buffer protection modes");
        mem::replace(&mut *lock, buffer);

        // call it a day
        Ok(output)
    }

    /// Commit code, flushing the temporary internal assembling buffer to the mapped executable memory.
    /// This makes assembled code available for execution.
    pub fn commit(&mut self) -> Result<(), DynasmError> {
        self.encode_relocs()?;

        let managed = &self.managed;
        let error = &mut self.error;

        self.memory.commit(&mut self.ops, |buffer, old_addr, new_addr| {
            let change = new_addr.wrapping_sub(old_addr) as isize;

            for reloc in managed.iter() {
                if let Err(_) = reloc.adjust(0, buffer, change) {
                    *error = Some(DynasmError::ImpossibleRelocation(TargetKind::Managed))
                }
            }
        });

        if let Some(e) = self.error.take() {
            return Err(e);
        }
        Ok(())
    }

    /// Finalize this assembler, returning the internal executablebuffer if no Executor instances exist.
    /// This panics if any uncommitted changes caused errors near the end. To handle these, call `commit()` explicitly beforehand.
    pub fn finalize(mut self) -> Result<ExecutableBuffer, Self> {
        self.commit().expect("Errors were encountered when committing before finalization");
        match self.memory.finalize() {
            Ok(execbuffer) => Ok(execbuffer),
            Err(memory) => Err(Self {
                memory,
                ..self
            })
        }
    }

    /// Create an executor which can be used to execute code while still assembling code
    pub fn reader(&self) -> Executor {
        Executor {
            execbuffer: self.memory.reader()
        }
    }

    /// Provides access to the assemblers internal labels registry
    pub fn labels(&self) -> &LabelRegistry {
        &self.labels
    }

    /// Provides mutable access to the assemblers internal labels registry
    pub fn labels_mut(&mut self) -> &mut LabelRegistry {
        &mut self.labels
    }

    // encode uncommited relocations
    fn encode_relocs(&mut self) -> Result<(), DynasmError> {
        let buf_offset = self.memory.committed();
        let buf_addr = self.memory.execbuffer_addr();
        let buf = &mut self.ops;

        // If we accrued any errors while assembling before, emit them now.
        if let Some(e) = self.error.take() {
            return Err(e);
        }

        // Resolve globals
        for (loc, name) in self.relocs.take_globals() {
            let target = self.labels.resolve_global(name)?;
            if let Err(_) = loc.patch(buf_offset, buf_addr, buf, target.0) {
                return Err(DynasmError::ImpossibleRelocation(TargetKind::Global(name)));
            }
            if loc.needs_adjustment() {
                self.managed.add(loc)
            }
        }

        // Resolve dynamics
        for (loc, id) in self.relocs.take_dynamics() {
            let target = self.labels.resolve_dynamic(id)?;
            if let Err(_) = loc.patch(buf_offset, buf_addr, buf, target.0) {
                return Err(DynasmError::ImpossibleRelocation(TargetKind::Dynamic(id)));
            }
            if loc.needs_adjustment() {
                self.managed.add(loc)
            }
        }

        // Check that there are no unknown local labels
        for (_, name) in self.relocs.take_locals() {
            return Err(DynasmError::UnknownLabel(LabelKind::Local(name)));
        }

        Ok(())
    }
}

impl<R: Relocation> Extend<u8> for Assembler<R> {
    fn extend<T>(&mut self, iter: T) where T: IntoIterator<Item=u8> {
        self.ops.extend(iter)
    }
}

impl<'a, R: Relocation> Extend<&'a u8> for Assembler<R> {
    fn extend<T>(&mut self, iter: T) where T: IntoIterator<Item=&'a u8> {
        self.ops.extend(iter)
    }
}

impl<R: Relocation> DynasmApi for Assembler<R> {
    fn offset(&self) -> AssemblyOffset {
        AssemblyOffset(self.memory.committed() + self.ops.len())
    }

    fn push(&mut self, value: u8) {
        self.ops.push(value);
    }

    fn align(&mut self, alignment: usize, with: u8) {
        let misalign = self.offset().0 % alignment;
        if misalign != 0 {
            for _ in misalign .. alignment {
                self.push(with);
            }
        }
    }
}

impl<R: Relocation> DynasmLabelApi for Assembler<R> {
    type Relocation = R;

    fn local_label(&mut self, name: &'static str) {
        let offset = self.offset();
        for loc in self.relocs.take_locals_named(name) {
            if let Err(_) = loc.patch(self.memory.committed(), self.memory.execbuffer_addr(), &mut self.ops, offset.0) {
                self.error = Some(DynasmError::ImpossibleRelocation(TargetKind::Forward(name)))
            } else if loc.needs_adjustment() {
                self.managed.add(loc)
            }
        }
        self.labels.define_local(name, offset);
    }
    fn global_label( &mut self, name: &'static str) {
        let offset = self.offset();
        if let Err(e) = self.labels.define_global(name, offset) {
            self.error = Some(e)
        }
    }
    fn dynamic_label(&mut self, id: DynamicLabel) {
        let offset = self.offset();
        if let Err(e) = self.labels.define_dynamic(id, offset) {
            self.error = Some(e)
        }
    }
    fn global_relocation(&mut self, name: &'static str, offset: isize, kind: R) {
        let location = self.offset();
        self.relocs.add_global(name, PatchLoc::new(location, offset, kind));
    }
    fn dynamic_relocation(&mut self, id: DynamicLabel, offset: isize, kind: R) {
        let location = self.offset();
        self.relocs.add_dynamic(id, PatchLoc::new(location, offset, kind));
    }
    fn forward_relocation(&mut self, name: &'static str, offset: isize, kind: R) {
        let location = self.offset();
        self.relocs.add_local(name, PatchLoc::new(location, offset, kind));
    }
    fn backward_relocation(&mut self, name: &'static str, offset: isize, kind: R) {
        let target = match self.labels.resolve_local(name) {
            Ok(target) => target.0,
            Err(e) => {
                self.error = Some(e);
                return;
            }
        };
        let location = self.offset();
        let loc = PatchLoc::new(location, offset, kind);
        if let Err(_) = loc.patch(self.memory.committed(), self.memory.execbuffer_addr(), &mut self.ops, target) {
            self.error = Some(DynasmError::ImpossibleRelocation(TargetKind::Backward(name)))
        } else if loc.needs_adjustment() {
            self.managed.add(loc)
        }
    }
    fn bare_relocation(&mut self, target: usize, kind: R) {
        let location = self.offset();
        let loc = PatchLoc::new(location, 0, kind);
        if let Err(_) = loc.patch(self.memory.committed(), self.memory.execbuffer_addr(), &mut self.ops, target) {
            self.error = Some(DynasmError::ImpossibleRelocation(TargetKind::Extern(target)))
        } else if loc.needs_adjustment() {
            self.managed.add(loc)
        }
    }
}


/// Allows modification of already committed assembly code. Contains an internal cursor
/// into the emitted assembly, initialized to the start, that can be moved around either with the
/// `goto` function, or just by assembling new code into this `Modifier`.
#[derive(Debug)]
pub struct Modifier<'a, R: Relocation> {
    asmoffset: usize,
    previous_asmoffset: usize,
    buffer: &'a mut [u8],

    labels: &'a mut LabelRegistry,
    relocs: &'a mut RelocRegistry<R>,
    old_managed: &'a mut ManagedRelocs<R>,
    new_managed: ManagedRelocs<R>,

    error: Option<DynasmError>
}

impl<'a, R: Relocation> Modifier<'a, R> {
    /// Move the modifier cursor to the selected location.
    pub fn goto(&mut self, offset: AssemblyOffset) {
        self.old_managed.remove_between(self.previous_asmoffset, self.asmoffset);
        self.asmoffset = offset.0;
        self.previous_asmoffset = offset.0;
    }

    /// Check that the modifier cursor has not moved past the specified location.
    pub fn check(&self, offset: AssemblyOffset) -> Result<(), DynasmError> {
        if self.asmoffset > offset.0 {
            Err(DynasmError::CheckFailed)
        } else {
            Ok(())
        }
    }

    /// Check that the modifier cursor is exactly at the specified location.
    pub fn check_exact(&self, offset: AssemblyOffset) -> Result<(), DynasmError> {
        if self.asmoffset != offset.0 {
            Err(DynasmError::CheckFailed)
        } else {
            Ok(())
        }
    }

    // encode uncommited relocations
    fn encode_relocs(&mut self) -> Result<(), DynasmError> {
        let buf_addr = self.buffer.as_ptr() as usize;

        // If we accrued any errors while assembling before, emit them now.
        if let Some(e) = self.error.take() {
            return Err(e);
        }

        // Resolve globals
        for (loc, name) in self.relocs.take_globals() {
            let target = self.labels.resolve_global(name)?;
            if let Err(_) = loc.patch(0, buf_addr, self.buffer, target.0) {
                return Err(DynasmError::ImpossibleRelocation(TargetKind::Global(name)));
            }
            if loc.needs_adjustment() {
                self.new_managed.add(loc);
            }
        }

        // Resolve dynamics
        for (loc, id) in self.relocs.take_dynamics() {
            let target = self.labels.resolve_dynamic(id)?;
            if let Err(_) = loc.patch(0, buf_addr, self.buffer, target.0) {
                return Err(DynasmError::ImpossibleRelocation(TargetKind::Dynamic(id)));
            }
            if loc.needs_adjustment() {
                self.new_managed.add(loc);
            }
        }

        // Check for unknown locals
        for (_, name) in self.relocs.take_locals() {
            return Err(DynasmError::UnknownLabel(LabelKind::Local(name)));
        }

        self.old_managed.remove_between(self.previous_asmoffset, self.asmoffset);
        self.previous_asmoffset = self.asmoffset;

        self.old_managed.append(&mut self.new_managed);

        Ok(())
    }
}

impl<'a, R: Relocation> Extend<u8> for Modifier<'a,R> {
    fn extend<T>(&mut self, iter: T) where T: IntoIterator<Item=u8> {
        for (src, dst) in iter.into_iter().zip(self.buffer[self.asmoffset ..].iter_mut()) {
            *dst = src;
        }
    }
}

impl<'a, 'b, R: Relocation> Extend<&'b u8> for Modifier<'a, R> {
    fn extend<T>(&mut self, iter: T) where T: IntoIterator<Item=&'b u8> {
        for (src, dst) in iter.into_iter().zip(self.buffer[self.asmoffset ..].iter_mut()) {
            *dst = *src;
        }
    }
}

impl<'a, R: Relocation> DynasmApi for Modifier<'a, R> {
    fn offset(&self) -> AssemblyOffset {
        AssemblyOffset(self.asmoffset)
    }

    fn push(&mut self, value: u8) {
        self.buffer[self.asmoffset] = value;
        self.asmoffset += 1
    }

    fn align(&mut self, alignment: usize, with: u8) {
        let mismatch = self.asmoffset % alignment;
        if mismatch != 0 {
            for _ in mismatch .. alignment {
                self.push(with)
            }
        }
    }
}

impl<'a, R: Relocation> DynasmLabelApi for Modifier<'a, R> {
    type Relocation = R;

    fn local_label(&mut self, name: &'static str) {
        let offset = self.offset();
        for loc in self.relocs.take_locals_named(name) {
            if let Err(_) = loc.patch(0, self.buffer.as_ptr() as usize, self.buffer, offset.0)  {
                self.error = Some(DynasmError::ImpossibleRelocation(TargetKind::Forward(name)));
            } else if loc.needs_adjustment() {
                self.new_managed.add(loc);
            }
        }
        self.labels.define_local(name, offset);
    }
    fn global_label( &mut self, name: &'static str) {
        let offset = self.offset();
        if let Err(e) = self.labels.define_global(name, offset) {
            self.error = Some(e);
        }
    }
    fn dynamic_label(&mut self, id: DynamicLabel) {
        let offset = self.offset();
        if let Err(e) = self.labels.define_dynamic(id, offset) {
            self.error = Some(e);
        }
    }
    fn global_relocation(&mut self, name: &'static str, offset: isize, kind: R) {
        let location = self.offset();
        self.relocs.add_global(name, PatchLoc::new(location, offset, kind));
    }
    fn dynamic_relocation(&mut self, id: DynamicLabel, offset: isize, kind: R) {
        let location = self.offset();
        self.relocs.add_dynamic(id, PatchLoc::new(location, offset, kind));
    }
    fn forward_relocation(&mut self, name: &'static str, offset: isize, kind: R) {
        let location = self.offset();
        self.relocs.add_local(name, PatchLoc::new(location, offset, kind));
    }
    fn backward_relocation(&mut self, name: &'static str, offset: isize, kind: R) {
        let target = match self.labels.resolve_local(name) {
            Ok(target) => target.0,
            Err(e) => {
                self.error = Some(e);
                return;
            }
        };
        let location = self.offset();
        let loc = PatchLoc::new(location, offset, kind);
        if let Err(_) = loc.patch(0, self.buffer.as_ptr() as usize, self.buffer, target) {
            self.error = Some(DynasmError::ImpossibleRelocation(TargetKind::Backward(name)));
        } else if loc.needs_adjustment() {
            self.new_managed.add(loc)
        }
    }
    fn bare_relocation(&mut self, target: usize, kind: R) {
        let location = self.offset();
        let loc = PatchLoc::new(location, 0, kind);
        if let Err(_) = loc.patch(0, self.buffer.as_ptr() as usize, self.buffer, target) {
            self.error = Some(DynasmError::ImpossibleRelocation(TargetKind::Extern(target)));
        } else if loc.needs_adjustment() {
            self.new_managed.add(loc)
        }
    }
}


/// This struct is a wrapper around an `Assembler` normally created using the
/// `Assembler.alter_uncommitted` method. It allows the user to edit parts
/// of the assembling buffer that cannot be determined easily or efficiently
/// in advance. Due to limitations of the label resolution algorithms, this
/// assembler does not allow labels to be used.
#[derive(Debug)]
pub struct UncommittedModifier<'a> {
    buffer: &'a mut Vec<u8>,
    base_offset: usize,
    offset: usize
}

impl<'a> UncommittedModifier<'a> {
    /// create a new uncommittedmodifier
    pub fn new(buffer: &mut Vec<u8>, base_offset: AssemblyOffset) -> UncommittedModifier {
        UncommittedModifier {
            buffer,
            base_offset: base_offset.0,
            offset: base_offset.0
        }
    }

    /// Sets the current modification offset to the given value
    pub fn goto(&mut self, offset: AssemblyOffset) {
        self.offset = offset.0;
    }

    /// Checks that the current modification offset is not larger than the specified offset.
    pub fn check(&mut self, offset: AssemblyOffset) -> Result<(), DynasmError> {
        if self.offset > offset.0 {
            Err(DynasmError::CheckFailed)
        } else {
            Ok(())
        }
    }

    /// Checks that the current modification offset is exactly the specified offset.
    pub fn check_exact(&mut self, offset: AssemblyOffset) -> Result<(), DynasmError> {
        if self.offset != offset.0 {
            Err(DynasmError::CheckFailed)
        } else {
            Ok(())
        }
    }
}

impl<'a> DynasmApi for UncommittedModifier<'a> {
    fn offset(&self) -> AssemblyOffset {
        AssemblyOffset(self.offset)
    }

    fn push(&mut self, value: u8) {
        self.buffer[self.offset - self.base_offset] = value;
        self.offset += 1;
    }

    fn align(&mut self, alignment: usize, with: u8) {
        let mismatch = self.offset % alignment;
        if mismatch != 0 {
            for _ in mismatch .. alignment {
                self.push(with)
            }
        }
    }
}

impl<'a> Extend<u8> for UncommittedModifier<'a> {
    fn extend<T>(&mut self, iter: T) where T: IntoIterator<Item=u8> {
        for i in iter {
            self.push(i)
        }
    }
}

impl<'a, 'b> Extend<&'b u8> for UncommittedModifier<'a> {
    fn extend<T>(&mut self, iter: T) where T: IntoIterator<Item=&'b u8> {
        self.extend(iter.into_iter().cloned())
    }
}