1//===-------------------------- cxa_vector.cpp ---------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is dual licensed under the MIT and the University of Illinois Open
6// Source Licenses. See LICENSE.TXT for details.
7//
8//
9//  This file implements the "Array Construction and Destruction APIs"
10//  http://mentorembedded.github.io/cxx-abi/abi.html#array-ctor
11//
12//===----------------------------------------------------------------------===//
13
14#include "cxxabi.h"
15
16#include <exception>        // for std::terminate
17
18namespace __cxxabiv1 {
19
20#if 0
21#pragma mark --Helper routines and classes --
22#endif
23
24namespace {
25    inline static size_t __get_element_count ( void *p ) {
26        return static_cast <size_t *> (p)[-1];
27        }
28
29    inline static void __set_element_count ( void *p, size_t element_count ) {
30        static_cast <size_t *> (p)[-1] = element_count;
31        }
32
33
34//  A pair of classes to simplify exception handling and control flow.
35//  They get passed a block of memory in the constructor, and unless the
36//  'release' method is called, they deallocate the memory in the destructor.
37//  Preferred usage is to allocate some memory, attach it to one of these objects,
38//  and then, when all the operations to set up the memory block have succeeded,
39//  call 'release'. If any of the setup operations fail, or an exception is
40//  thrown, then the block is automatically deallocated.
41//
42//  The only difference between these two classes is the signature for the
43//  deallocation function (to match new2/new3 and delete2/delete3.
44    class st_heap_block2 {
45    public:
46        typedef void (*dealloc_f)(void *);
47
48        st_heap_block2 ( dealloc_f dealloc, void *ptr )
49            : dealloc_ ( dealloc ), ptr_ ( ptr ), enabled_ ( true ) {}
50        ~st_heap_block2 () { if ( enabled_ ) dealloc_ ( ptr_ ) ; }
51        void release () { enabled_ = false; }
52
53    private:
54        dealloc_f dealloc_;
55        void *ptr_;
56        bool enabled_;
57    };
58
59    class st_heap_block3 {
60    public:
61        typedef void (*dealloc_f)(void *, size_t);
62
63        st_heap_block3 ( dealloc_f dealloc, void *ptr, size_t size )
64            : dealloc_ ( dealloc ), ptr_ ( ptr ), size_ ( size ), enabled_ ( true ) {}
65        ~st_heap_block3 () { if ( enabled_ ) dealloc_ ( ptr_, size_ ) ; }
66        void release () { enabled_ = false; }
67
68    private:
69        dealloc_f dealloc_;
70        void *ptr_;
71        size_t size_;
72        bool enabled_;
73    };
74
75    class st_cxa_cleanup {
76    public:
77        typedef void (*destruct_f)(void *);
78
79        st_cxa_cleanup ( void *ptr, size_t &idx, size_t element_size, destruct_f destructor )
80            : ptr_ ( ptr ), idx_ ( idx ), element_size_ ( element_size ),
81                destructor_ ( destructor ), enabled_ ( true ) {}
82        ~st_cxa_cleanup () {
83            if ( enabled_ )
84                __cxa_vec_cleanup ( ptr_, idx_, element_size_, destructor_ );
85            }
86
87        void release () { enabled_ = false; }
88
89    private:
90        void *ptr_;
91        size_t &idx_;
92        size_t element_size_;
93        destruct_f destructor_;
94        bool enabled_;
95    };
96
97    class st_terminate {
98    public:
99        st_terminate ( bool enabled = true ) : enabled_ ( enabled ) {}
100        ~st_terminate () { if ( enabled_ ) std::terminate (); }
101        void release () { enabled_ = false; }
102    private:
103        bool enabled_ ;
104    };
105}
106
107#if 0
108#pragma mark --Externally visible routines--
109#endif
110
111extern "C" {
112
113// Equivalent to
114//
115//   __cxa_vec_new2(element_count, element_size, padding_size, constructor,
116//                  destructor, &::operator new[], &::operator delete[])
117_LIBCXXABI_FUNC_VIS void *
118__cxa_vec_new(size_t element_count, size_t element_size, size_t padding_size,
119              void (*constructor)(void *), void (*destructor)(void *)) {
120    return __cxa_vec_new2 ( element_count, element_size, padding_size,
121        constructor, destructor, &::operator new [], &::operator delete [] );
122}
123
124
125
126// Given the number and size of elements for an array and the non-negative
127// size of prefix padding for a cookie, allocate space (using alloc) for
128// the array preceded by the specified padding, initialize the cookie if
129// the padding is non-zero, and call the given constructor on each element.
130// Return the address of the array proper, after the padding.
131//
132// If alloc throws an exception, rethrow the exception. If alloc returns
133// NULL, return NULL. If the constructor throws an exception, call
134// destructor for any already constructed elements, and rethrow the
135// exception. If the destructor throws an exception, call std::terminate.
136//
137// The constructor may be NULL, in which case it must not be called. If the
138// padding_size is zero, the destructor may be NULL; in that case it must
139// not be called.
140//
141// Neither alloc nor dealloc may be NULL.
142_LIBCXXABI_FUNC_VIS void *
143__cxa_vec_new2(size_t element_count, size_t element_size, size_t padding_size,
144               void (*constructor)(void *), void (*destructor)(void *),
145               void *(*alloc)(size_t), void (*dealloc)(void *)) {
146    const size_t heap_size = element_count * element_size + padding_size;
147    char * const heap_block = static_cast<char *> ( alloc ( heap_size ));
148    char *vec_base = heap_block;
149
150    if ( NULL != vec_base ) {
151        st_heap_block2 heap ( dealloc, heap_block );
152
153    //  put the padding before the array elements
154        if ( 0 != padding_size ) {
155            vec_base += padding_size;
156            __set_element_count ( vec_base, element_count );
157        }
158
159    //  Construct the elements
160        __cxa_vec_ctor ( vec_base, element_count, element_size, constructor, destructor );
161        heap.release ();    // We're good!
162    }
163
164    return vec_base;
165}
166
167
168// Same as __cxa_vec_new2 except that the deallocation function takes both
169// the object address and its size.
170_LIBCXXABI_FUNC_VIS void *
171__cxa_vec_new3(size_t element_count, size_t element_size, size_t padding_size,
172               void (*constructor)(void *), void (*destructor)(void *),
173               void *(*alloc)(size_t), void (*dealloc)(void *, size_t)) {
174    const size_t heap_size = element_count * element_size + padding_size;
175    char * const heap_block = static_cast<char *> ( alloc ( heap_size ));
176    char *vec_base = heap_block;
177
178    if ( NULL != vec_base ) {
179        st_heap_block3 heap ( dealloc, heap_block, heap_size );
180
181    //  put the padding before the array elements
182        if ( 0 != padding_size ) {
183            vec_base += padding_size;
184            __set_element_count ( vec_base, element_count );
185        }
186
187    //  Construct the elements
188        __cxa_vec_ctor ( vec_base, element_count, element_size, constructor, destructor );
189        heap.release ();    // We're good!
190    }
191
192    return vec_base;
193}
194
195
196// Given the (data) addresses of a destination and a source array, an
197// element count and an element size, call the given copy constructor to
198// copy each element from the source array to the destination array. The
199// copy constructor's arguments are the destination address and source
200// address, respectively. If an exception occurs, call the given destructor
201// (if non-NULL) on each copied element and rethrow. If the destructor
202// throws an exception, call terminate(). The constructor and or destructor
203// pointers may be NULL. If either is NULL, no action is taken when it
204// would have been called.
205
206_LIBCXXABI_FUNC_VIS void __cxa_vec_cctor(void *dest_array, void *src_array,
207                                         size_t element_count,
208                                         size_t element_size,
209                                         void (*constructor)(void *, void *),
210                                         void (*destructor)(void *)) {
211    if ( NULL != constructor ) {
212        size_t idx = 0;
213        char *src_ptr  = static_cast<char *>(src_array);
214        char *dest_ptr = static_cast<char *>(dest_array);
215        st_cxa_cleanup cleanup ( dest_array, idx, element_size, destructor );
216
217        for ( idx = 0; idx < element_count;
218                    ++idx, src_ptr += element_size, dest_ptr += element_size )
219            constructor ( dest_ptr, src_ptr );
220        cleanup.release ();     // We're good!
221    }
222}
223
224
225// Given the (data) address of an array, not including any cookie padding,
226// and the number and size of its elements, call the given constructor on
227// each element. If the constructor throws an exception, call the given
228// destructor for any already-constructed elements, and rethrow the
229// exception. If the destructor throws an exception, call terminate(). The
230// constructor and/or destructor pointers may be NULL. If either is NULL,
231// no action is taken when it would have been called.
232_LIBCXXABI_FUNC_VIS void
233__cxa_vec_ctor(void *array_address, size_t element_count, size_t element_size,
234               void (*constructor)(void *), void (*destructor)(void *)) {
235    if ( NULL != constructor ) {
236        size_t idx;
237        char *ptr = static_cast <char *> ( array_address );
238        st_cxa_cleanup cleanup ( array_address, idx, element_size, destructor );
239
240    //  Construct the elements
241        for ( idx = 0; idx < element_count; ++idx, ptr += element_size )
242            constructor ( ptr );
243        cleanup.release ();     // We're good!
244    }
245}
246
247// Given the (data) address of an array, the number of elements, and the
248// size of its elements, call the given destructor on each element. If the
249// destructor throws an exception, rethrow after destroying the remaining
250// elements if possible. If the destructor throws a second exception, call
251// terminate(). The destructor pointer may be NULL, in which case this
252// routine does nothing.
253_LIBCXXABI_FUNC_VIS void __cxa_vec_dtor(void *array_address,
254                                        size_t element_count,
255                                        size_t element_size,
256                                        void (*destructor)(void *)) {
257    if ( NULL != destructor ) {
258        char *ptr = static_cast <char *> (array_address);
259        size_t idx = element_count;
260        st_cxa_cleanup cleanup ( array_address, idx, element_size, destructor );
261        {
262            st_terminate exception_guard (__cxa_uncaught_exception ());
263            ptr +=  element_count * element_size;   // one past the last element
264
265            while ( idx-- > 0 ) {
266                ptr -= element_size;
267                destructor ( ptr );
268            }
269            exception_guard.release (); //  We're good !
270        }
271        cleanup.release ();     // We're still good!
272    }
273}
274
275// Given the (data) address of an array, the number of elements, and the
276// size of its elements, call the given destructor on each element. If the
277// destructor throws an exception, call terminate(). The destructor pointer
278// may be NULL, in which case this routine does nothing.
279_LIBCXXABI_FUNC_VIS void __cxa_vec_cleanup(void *array_address,
280                                           size_t element_count,
281                                           size_t element_size,
282                                           void (*destructor)(void *)) {
283    if ( NULL != destructor ) {
284        char *ptr = static_cast <char *> (array_address);
285        size_t idx = element_count;
286        st_terminate exception_guard;
287
288        ptr += element_count * element_size;    // one past the last element
289        while ( idx-- > 0 ) {
290            ptr -= element_size;
291            destructor ( ptr );
292            }
293        exception_guard.release ();     // We're done!
294    }
295}
296
297
298// If the array_address is NULL, return immediately. Otherwise, given the
299// (data) address of an array, the non-negative size of prefix padding for
300// the cookie, and the size of its elements, call the given destructor on
301// each element, using the cookie to determine the number of elements, and
302// then delete the space by calling ::operator delete[](void *). If the
303// destructor throws an exception, rethrow after (a) destroying the
304// remaining elements, and (b) deallocating the storage. If the destructor
305// throws a second exception, call terminate(). If padding_size is 0, the
306// destructor pointer must be NULL. If the destructor pointer is NULL, no
307// destructor call is to be made.
308//
309// The intent of this function is to permit an implementation to call this
310// function when confronted with an expression of the form delete[] p in
311// the source code, provided that the default deallocation function can be
312// used. Therefore, the semantics of this function are consistent with
313// those required by the standard. The requirement that the deallocation
314// function be called even if the destructor throws an exception derives
315// from the resolution to DR 353 to the C++ standard, which was adopted in
316// April, 2003.
317_LIBCXXABI_FUNC_VIS void __cxa_vec_delete(void *array_address,
318                                          size_t element_size,
319                                          size_t padding_size,
320                                          void (*destructor)(void *)) {
321    __cxa_vec_delete2 ( array_address, element_size, padding_size,
322               destructor, &::operator delete [] );
323}
324
325// Same as __cxa_vec_delete, except that the given function is used for
326// deallocation instead of the default delete function. If dealloc throws
327// an exception, the result is undefined. The dealloc pointer may not be
328// NULL.
329_LIBCXXABI_FUNC_VIS void
330__cxa_vec_delete2(void *array_address, size_t element_size, size_t padding_size,
331                  void (*destructor)(void *), void (*dealloc)(void *)) {
332    if ( NULL != array_address ) {
333        char *vec_base   = static_cast <char *> (array_address);
334        char *heap_block = vec_base - padding_size;
335        st_heap_block2 heap ( dealloc, heap_block );
336
337        if ( 0 != padding_size && NULL != destructor ) // call the destructors
338            __cxa_vec_dtor ( array_address, __get_element_count ( vec_base ),
339                                    element_size, destructor );
340    }
341}
342
343
344// Same as __cxa_vec_delete, except that the given function is used for
345// deallocation instead of the default delete function. The deallocation
346// function takes both the object address and its size. If dealloc throws
347// an exception, the result is undefined. The dealloc pointer may not be
348// NULL.
349_LIBCXXABI_FUNC_VIS void
350__cxa_vec_delete3(void *array_address, size_t element_size, size_t padding_size,
351                  void (*destructor)(void *), void (*dealloc)(void *, size_t)) {
352    if ( NULL != array_address ) {
353        char *vec_base   = static_cast <char *> (array_address);
354        char *heap_block = vec_base - padding_size;
355        const size_t element_count = padding_size ? __get_element_count ( vec_base ) : 0;
356        const size_t heap_block_size = element_size * element_count + padding_size;
357        st_heap_block3 heap ( dealloc, heap_block, heap_block_size );
358
359        if ( 0 != padding_size && NULL != destructor ) // call the destructors
360            __cxa_vec_dtor ( array_address, element_count, element_size, destructor );
361    }
362}
363
364
365}  // extern "C"
366
367}  // abi
368