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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License..

//! # align box crate for Rust SGX SDK
//!

use core::ptr::{Unique, NonNull};
use core::ops::{DerefMut, Deref};
use core::mem;
use core::ptr;
use core::fmt;
use core::borrow;
use core::alloc::Layout;
use alloc::alloc::handle_alloc_error;
use super::alignalloc::AlignAlloc;
pub use super::alignalloc::AlignReq;

pub struct AlignBox<T> {
    ptr: Unique<T>,
    align_layout: Layout,
    origin_layout: Layout,
}

impl<T> AlignBox<T> {
    /// Gets a raw pointer to the start of the allocation. Note that this is
    /// Unique::empty() if `cap = 0` or T is zero-sized. In the former case, you must
    /// be careful.
    pub fn as_ptr(&self) -> *mut T {
        self.ptr.as_ptr()
    }
}

impl<T> Deref for AlignBox<T> {
    type Target = T;

    fn deref(&self) -> &T {
        unsafe{self.ptr.as_ref()}
    }
}

impl<T> DerefMut for AlignBox<T> {
    fn deref_mut(&mut self) -> &mut T {
       unsafe{self.ptr.as_mut()}
    }
}

impl<T> AsRef<T> for AlignBox<T> {
    fn as_ref(&self) -> &T {
        &**self
    }
}

impl<T> AsMut<T> for AlignBox<T> {
    fn as_mut(&mut self) -> &mut T {
        &mut **self
    }
}

impl<T> borrow::Borrow<T> for AlignBox<T> {
    fn borrow(&self) -> &T {
        &**self
    }
}

impl<T> borrow::BorrowMut<T> for AlignBox<T> {
    fn borrow_mut(&mut self) -> &mut T {
        &mut **self
    }
}

impl<T: fmt::Display> fmt::Display for AlignBox<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

impl<T: fmt::Debug> fmt::Debug for AlignBox<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AlignBox")
            .field("align_layout", &self.align_layout)
            .field("data", &**self)
            .finish()
    }
}

impl<T: Clone> Clone for AlignBox<T> {
    #[rustfmt::skip]
    #[inline]
    fn clone(&self) -> AlignBox<T> {
        let ptr = match unsafe{AlignAlloc.alloc_with_pad_align_zeroed(self.origin_layout, self.align_layout)} {
            Ok(p) => p,
            Err(_) => handle_alloc_error(self.align_layout),
        };
        unsafe {
            ptr::copy_nonoverlapping(&(**self).clone() as *const _ as *const u8,
                                     ptr.as_ptr(), 
                                     self.origin_layout.size());
        }
        AlignBox {
            ptr: ptr.cast().into(),
            align_layout: self.align_layout,
            origin_layout: self.origin_layout,
        }
    }

    #[inline]
    fn clone_from(&mut self, source: &AlignBox<T>) {
        if source.align_layout.size() != self.align_layout.size() {
            let ptr = match unsafe {
                AlignAlloc.alloc_with_pad_align_zeroed(source.origin_layout, source.align_layout) 
            } {
                Ok(p) => p,
                Err(_) => handle_alloc_error(source.align_layout),
            };
            unsafe {
                ptr::copy_nonoverlapping(&(**source).clone() as *const _ as *const u8,
                                         ptr.as_ptr(),
                                         source.origin_layout.size());
                self.dealloc_buffer();
            }
            self.ptr = ptr.cast().into();
        } else {
            (**self).clone_from(&(**source));
        }
        self.align_layout = source.align_layout;
        self.origin_layout = source.origin_layout;
    }
}

impl<T> AlignBox<T> {
    unsafe fn dealloc_buffer(&mut self) {
        let elem_size = mem::size_of::<T>();
        if elem_size != 0 {
            AlignAlloc.dealloc(NonNull::from(self.ptr).cast(), self.origin_layout)
        }
    }
}

unsafe impl<#[may_dangle] T> Drop for AlignBox<T> {
    fn drop(&mut self) {
        unsafe {
            self.dealloc_buffer();
        }
    }
}

impl<T> AlignBox<T> {
    fn new_with_req_in(align: usize, align_req: &[AlignReq]) -> Option<AlignBox<T>> {
        if align_req.len() == 0 {
            AlignBox::new_in()
        } else {
            AlignBox::allocate_in(true, align, align_req)
        }
    }

    fn new_with_align_in(align: usize) -> Option<AlignBox<T>> {
        let v: [AlignReq; 1] = [AlignReq{ offset:0, len:mem::size_of::<T>() }];
        AlignBox::allocate_in(true, align, &v)
    }

    fn new_in() -> Option<AlignBox<T>> {
        let v: [AlignReq; 1] = [AlignReq{ offset: 0, len:mem::size_of::<T>() }];
        AlignBox::allocate_in(true, mem::align_of::<T>(), &v)
    }

    fn allocate_in(zeroed: bool, align: usize, align_req: &[AlignReq]) -> Option<AlignBox<T>> {
        if mem::size_of::<T>() == 0 {
            return None;
        }

        let layout = match Layout::from_size_align(mem::size_of::<T>(), align) {
            Ok(n) => n,
            Err(_) => return None,
        };
    
        let align_layout = match AlignAlloc.pad_align_to(layout, align_req) {
            Ok(n) => n,
            Err(_) => return None,
        };
       
        // handles ZSTs and `cap = 0` alike
        let result = if zeroed {
            unsafe{ AlignAlloc.alloc_with_req_zeroed(layout, align_req) }
        } else {
            unsafe{ AlignAlloc.alloc_with_req(layout, align_req) }
        };
        let ptr = match result {
            Ok(r) => r.cast(),
            Err(_) => handle_alloc_error(align_layout),
        };

        Some(AlignBox{
            ptr: ptr.into(),
            align_layout: align_layout,
            origin_layout: layout,
        })
    }
}

impl<T> AlignBox<T> {
    pub fn new() -> Option<AlignBox<T>> {
        Self::new_in()
    }
     pub fn new_with_align(align: usize) -> Option<AlignBox<T>> {
        Self::new_with_align_in(align)
    }
    pub fn new_with_req(align: usize, align_req: &[AlignReq]) -> Option<AlignBox<T>> {
        Self::new_with_req_in(align, align_req)
    }
}

impl<T> AlignBox<T> {
    pub fn heap_init<F>(initialize: F) -> Option<AlignBox<T>>
    where
        F: Fn(&mut T),
    {
        unsafe {
            let mut t = Self::new_in();
            match t {
                Some(ref mut b) => initialize(b.ptr.as_mut()),
                None => (),
            }
            t
        }
    }
    pub fn heap_init_with_align<F>(initialize: F, align: usize) -> Option<AlignBox<T>>
    where
        F: Fn(&mut T),
    {
        unsafe {
            let mut t = Self::new_with_align(align);
            match t {
                Some(ref mut b) => initialize(b.ptr.as_mut()),
                None => (),
            }
            t
        }
    }
    pub fn heap_init_with_req<F>(initialize: F, align: usize, data: &[AlignReq]) -> Option<AlignBox<T>>
    where
        F: Fn(&mut T),
    {
      unsafe {
            let mut t = Self::new_with_req(align, data);
            match t {
                Some(ref mut b) => initialize(b.ptr.as_mut()),
                None => (),
            }
            t
        }
    }
}