memory.cc revision 227825
1/**
2 * memory.cc - Contains stub definition of C++ new/delete operators.
3 *
4 * These definitions are intended to be used for testing and are weak symbols
5 * to allow them to be replaced by definitions from a STL implementation.
6 * These versions simply wrap malloc() and free(), they do not provide a
7 * C++-specific allocator.
8 */
9
10#include <stddef.h>
11#include <stdlib.h>
12#include "stdexcept.h"
13
14namespace std
15{
16	struct nothrow_t {};
17}
18
19
20/// The type of the function called when allocation fails.
21typedef void (*new_handler)();
22/**
23 * The function to call when allocation fails.  By default, there is no
24 * handler and a bad allocation exception is thrown if an allocation fails.
25 */
26static new_handler new_handl;
27
28namespace std
29{
30	/**
31	 * Sets a function to be called when there is a failure in new.
32	 */
33	__attribute__((weak))
34	new_handler set_new_handler(new_handler handler)
35	{
36		return __sync_lock_test_and_set(&new_handl, handler);
37	}
38}
39
40
41__attribute__((weak))
42void* operator new(size_t size)
43{
44	void * mem = malloc(size);
45	while (0 == mem)
46	{
47		if (0 != new_handl)
48		{
49			new_handl();
50		}
51		else
52		{
53			throw std::bad_alloc();
54		}
55		mem = malloc(size);
56	}
57
58	return mem;
59}
60
61__attribute__((weak))
62void* operator new(size_t size, const std::nothrow_t &) throw()
63{
64	void *mem = malloc(size);
65	while (0 == mem)
66	{
67		if (0 != new_handl)
68		{
69			try
70			{
71				new_handl();
72			}
73			catch (...)
74			{
75				// nothrow operator new should return NULL in case of
76				// std::bad_alloc exception in new handler
77				return NULL;
78			}
79		}
80		else
81		{
82			return NULL;
83		}
84		mem = malloc(size);
85	}
86
87	return mem;
88}
89
90
91__attribute__((weak))
92void operator delete(void * ptr)
93{
94	free(ptr);
95}
96
97
98__attribute__((weak))
99void * operator new[](size_t size)
100{
101	return ::operator new(size);
102}
103
104
105__attribute__((weak))
106void operator delete[](void * ptr)
107{
108	::operator delete(ptr);
109}
110
111
112