|
18 | 18 |
|
19 | 19 | #include "new.h"
|
20 | 20 |
|
21 |
| -void * operator new(size_t size) { |
| 21 | +// The C++ spec dicates that allocation failure should cause the |
| 22 | +// (non-nothrow version of the) operator new to throw an exception. |
| 23 | +// Since we expect to have exceptions disabled, it would be more |
| 24 | +// appropriate (and probably standards-compliant) to terminate instead. |
| 25 | +// Historically failure causes null to be returned, but this define |
| 26 | +// allows switching to more robust terminating behaviour (that might |
| 27 | +// become the default at some point in the future). Note that any code |
| 28 | +// that wants null to be returned can (and should) use the nothrow |
| 29 | +// versions of the new statement anyway and is unaffected by this. |
| 30 | +// #define NEW_TERMINATES_ON_FAILURE |
| 31 | + |
| 32 | +namespace std { |
| 33 | + // Defined in abi.cpp |
| 34 | + void terminate(); |
| 35 | +} |
| 36 | + |
| 37 | +static void * new_helper(size_t size) { |
22 | 38 | // Even zero-sized allocations should return a unique pointer, but
|
23 | 39 | // malloc does not guarantee this
|
24 | 40 | if (size == 0)
|
25 | 41 | size = 1;
|
26 | 42 | return malloc(size);
|
27 | 43 | }
|
| 44 | + |
| 45 | +void * operator new(size_t size) { |
| 46 | + void *res = new_helper(size); |
| 47 | +#if defined(NEW_TERMINATES_ON_FAILURE) |
| 48 | + if (!res) |
| 49 | + std::terminate(); |
| 50 | +#endif |
| 51 | + return res; |
| 52 | +} |
28 | 53 | void * operator new[](size_t size) {
|
29 | 54 | return operator new(size);
|
30 | 55 | }
|
31 | 56 |
|
32 | 57 | void * operator new(size_t size, const std::nothrow_t tag) noexcept {
|
| 58 | +#if defined(NEW_TERMINATES_ON_FAILURE) |
| 59 | + // Cannot call throwing operator new as standard suggests, so call |
| 60 | + // new_helper directly then |
| 61 | + return new_helper(size); |
| 62 | +#else |
33 | 63 | return operator new(size);
|
| 64 | +#endif |
34 | 65 | }
|
35 | 66 | void * operator new[](size_t size, const std::nothrow_t& tag) noexcept {
|
| 67 | +#if defined(NEW_TERMINATES_ON_FAILURE) |
| 68 | + // Cannot call throwing operator new[] as standard suggests, so call |
| 69 | + // malloc directly then |
| 70 | + return new_helper(size); |
| 71 | +#else |
36 | 72 | return operator new[](size);
|
| 73 | +#endif |
37 | 74 | }
|
38 | 75 |
|
39 | 76 | void * operator new(size_t size, void *place) noexcept {
|
|
0 commit comments