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