summaryrefslogtreecommitdiffstats
path: root/LibOVR/Src/Kernel/OVR_Allocator.h
blob: dcf097dcb2f971d43d864a1bf158dde9b7128645 (plain)
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/************************************************************************************

PublicHeader:   OVR_Kernel.h
Filename    :   OVR_Allocator.h
Content     :   Installable memory allocator
Created     :   September 19, 2012
Notes       : 

Copyright   :   Copyright 2014 Oculus VR, LLC All Rights reserved.

Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); 
you may not use the Oculus VR Rift SDK except in compliance with the License, 
which is provided at the time of installation or download, or which 
otherwise accompanies this software in either electronic or hard copy form.

You may obtain a copy of the License at

http://www.oculusvr.com/licenses/LICENSE-3.2 

Unless required by applicable law or agreed to in writing, the Oculus VR SDK 
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.

************************************************************************************/

#ifndef OVR_Allocator_h
#define OVR_Allocator_h

#include "OVR_Types.h"

//-----------------------------------------------------------------------------------

// ***** Disable template-unfriendly MS VC++ warnings
#if defined(OVR_CC_MSVC)
// Pragma to prevent long name warnings in in VC++
#pragma warning(disable : 4503)
#pragma warning(disable : 4786)
// In MSVC 7.1, warning about placement new POD default initializer
#pragma warning(disable : 4345)
#endif

// Un-define new so that placement constructors work
#undef new


//-----------------------------------------------------------------------------------
// ***** Placement new overrides

// Calls constructor on own memory created with "new(ptr) type"
#ifndef __PLACEMENT_NEW_INLINE
#define __PLACEMENT_NEW_INLINE

#   if defined(OVR_CC_MWERKS) || defined(OVR_CC_BORLAND) || defined(OVR_CC_GNU)
#      include <new>
#   else
    // Useful on MSVC
    OVR_FORCE_INLINE void* operator new     (size_t n, void *ptr) { OVR_UNUSED(n); return ptr; }
    OVR_FORCE_INLINE void  operator delete  (void *, void *)     { }
#   endif

#endif // __PLACEMENT_NEW_INLINE



//------------------------------------------------------------------------
// ***** Macros to redefine class new/delete operators

// Types specifically declared to allow disambiguation of address in
// class member operator new.

#define OVR_MEMORY_REDEFINE_NEW_IMPL(class_name, check_delete)                          \
    void*   operator new(size_t sz)                                                      \
    { void *p = OVR_ALLOC_DEBUG(sz, __FILE__, __LINE__); return p; }                                              \
    void*   operator new(size_t sz, const char* file, int line)                          \
    { void* p = OVR_ALLOC_DEBUG(sz, file, line); OVR_UNUSED2(file, line); return p; }   \
    void    operator delete(void *p)                                                    \
    { check_delete(class_name, p); OVR_FREE(p); }                                       \
    void    operator delete(void *p, const char*, int)                                  \
    { check_delete(class_name, p); OVR_FREE(p); }                          

#define OVR_MEMORY_DEFINE_PLACEMENT_NEW                                                 \
    void*   operator new        (size_t n, void *ptr)    { OVR_UNUSED(n); return ptr; }  \
    void    operator delete     (void *ptr, void *ptr2) { OVR_UNUSED2(ptr,ptr2); }


#define OVR_MEMORY_CHECK_DELETE_NONE(class_name, p)

// Redefined all delete/new operators in a class without custom memory initialization
#define OVR_MEMORY_REDEFINE_NEW(class_name) \
    OVR_MEMORY_REDEFINE_NEW_IMPL(class_name, OVR_MEMORY_CHECK_DELETE_NONE)


namespace OVR {

//-----------------------------------------------------------------------------------
// ***** Construct / Destruct

// Construct/Destruct functions are useful when new is redefined, as they can
// be called instead of placement new constructors.


template <class T>
OVR_FORCE_INLINE T*  Construct(void *p)
{
    return ::new(p) T();
}

template <class T>
OVR_FORCE_INLINE T*  Construct(void *p, const T& source)
{
    return ::new(p) T(source);
}

// Same as above, but allows for a different type of constructor.
template <class T, class S>
OVR_FORCE_INLINE T*  ConstructAlt(void *p, const S& source)
{
    return ::new(p) T(source);
}

template <class T, class S1, class S2>
OVR_FORCE_INLINE T*  ConstructAlt(void *p, const S1& src1, const S2& src2)
{
    return ::new(p) T(src1, src2);
}

template <class T>
OVR_FORCE_INLINE void ConstructArray(void *p, size_t count)
{
    uint8_t *pdata = (uint8_t*)p;
    for (size_t i=0; i< count; ++i, pdata += sizeof(T))
    {
        Construct<T>(pdata);
    }
}

template <class T>
OVR_FORCE_INLINE void ConstructArray(void *p, size_t count, const T& source)
{
    uint8_t *pdata = (uint8_t*)p;
    for (size_t i=0; i< count; ++i, pdata += sizeof(T))
    {
        Construct<T>(pdata, source);
    }
}

template <class T>
OVR_FORCE_INLINE void Destruct(T *pobj)
{
    pobj->~T();
    OVR_UNUSED1(pobj); // Fix incorrect 'unused variable' MSVC warning.
}

template <class T>
OVR_FORCE_INLINE void DestructArray(T *pobj, size_t count)
{   
    for (size_t i=0; i<count; ++i, ++pobj)
        pobj->~T();
}


//-----------------------------------------------------------------------------------
// ***** Allocator

// Allocator defines a memory allocation interface that developers can override
// to to provide memory for OVR; an instance of this class is typically created on
// application startup and passed into System or OVR::System constructor.
// 
//
// Users implementing this interface must provide three functions: Alloc, Free,
// and Realloc. Implementations of these functions must honor the requested alignment.
// Although arbitrary alignment requests are possible, requested alignment will
// typically be small, such as 16 bytes or less.

class Allocator
{
    friend class System;
public:
    virtual ~Allocator(){}

    // *** Standard Alignment Alloc/Free

    // Allocate memory of specified size with default alignment.
    // Alloc of size==0 will allocate a tiny block & return a valid pointer;
    // this makes it suitable for new operator.
    virtual void*   Alloc(size_t size) = 0;
    // Same as Alloc, but provides an option of passing debug data.
    virtual void*   AllocDebug(size_t size, const char* file, unsigned line)
    { OVR_UNUSED2(file, line); return Alloc(size); }

    // Reallocate memory block to a new size, copying data if necessary. Returns the pointer to
    // new memory block, which may be the same as original pointer. Will return 0 if reallocation
    // failed, in which case previous memory is still valid.
    // Realloc to decrease size will never fail.
    // Realloc of pointer == 0 is equivalent to Alloc
    // Realloc to size == 0, shrinks to the minimal size, pointer remains valid and requires Free().
    virtual void*   Realloc(void* p, size_t newSize) = 0;

    // Frees memory allocated by Alloc/Realloc.
    // Free of null pointer is valid and will do nothing.
    virtual void    Free(void *p) = 0;


    // *** Standard Alignment Alloc/Free

    // Allocate memory of specified alignment.
    // Memory allocated with AllocAligned MUST be freed with FreeAligned.
    // Default implementation will delegate to Alloc/Free after doing rounding.
    virtual void*   AllocAligned(size_t size, size_t align);    
    // Frees memory allocated with AllocAligned.
    virtual void    FreeAligned(void* p);
    
    // Returns the pointer to the current globally installed Allocator instance.
    // This pointer is used for most of the memory allocations.
    static Allocator* GetInstance() { return pInstance; }


protected:
    // onSystemShutdown is called on the allocator during System::Shutdown.
    // At this point, all allocations should've been freed.
    virtual void    onSystemShutdown() { }

public:
    static  void    setInstance(Allocator* palloc)    
    {
        OVR_ASSERT((pInstance == 0) || (palloc == 0));
        pInstance = palloc;
    }

private:

    static Allocator* pInstance;
};



//------------------------------------------------------------------------
// ***** Allocator_SingletonSupport

// Allocator_SingletonSupport is a Allocator wrapper class that implements
// the InitSystemSingleton static function, used to create a global singleton
// used for the OVR::System default argument initialization.
//
// End users implementing custom Allocator interface don't need to make use of this base
// class; they can just create an instance of their own class on stack and pass it to System.

template<class D>
class Allocator_SingletonSupport : public Allocator
{
    struct AllocContainer
    {        
        size_t Data[(sizeof(D) + sizeof(size_t)-1) / sizeof(size_t)];
        bool  Initialized;
        AllocContainer() : Initialized(0) { }
    };

    AllocContainer* pContainer;

public:
    Allocator_SingletonSupport() : pContainer(0) { }

    // Creates a singleton instance of this Allocator class used
    // on OVR_DEFAULT_ALLOCATOR during System initialization.
    static  D*  InitSystemSingleton()
    {
        static AllocContainer Container;
        OVR_ASSERT(Container.Initialized == false);

        Allocator_SingletonSupport<D> *presult = Construct<D>((void*)Container.Data);
        presult->pContainer   = &Container;
        Container.Initialized = true;
        return (D*)presult;
    }

protected:
    virtual void onSystemShutdown()
    {
        Allocator::onSystemShutdown();
        if (pContainer)
        {
            pContainer->Initialized = false;
            Destruct((D*)this);
            pContainer = 0;
        }
    }
};

//------------------------------------------------------------------------
// ***** Default Allocator

// This allocator is created and used if no other allocator is installed.
// Default allocator delegates to system malloc.

class DefaultAllocator : public Allocator_SingletonSupport<DefaultAllocator>
{
public:
    virtual void*   Alloc(size_t size);
    virtual void*   AllocDebug(size_t size, const char* file, unsigned line);
    virtual void*   Realloc(void* p, size_t newSize);
    virtual void    Free(void *p);
};


//------------------------------------------------------------------------
// ***** Memory Allocation Macros

// These macros should be used for global allocation. In the future, these
// macros will allows allocation to be extended with debug file/line information
// if necessary.

#define OVR_REALLOC(p,s)        OVR::Allocator::GetInstance()->Realloc((p),(s))
#define OVR_FREE(p)             OVR::Allocator::GetInstance()->Free((p))
#define OVR_ALLOC_ALIGNED(s,a)  OVR::Allocator::GetInstance()->AllocAligned((s),(a))
#define OVR_FREE_ALIGNED(p)     OVR::Allocator::GetInstance()->FreeAligned((p))

#ifdef OVR_BUILD_DEBUG
#define OVR_ALLOC(s)            OVR::Allocator::GetInstance()->AllocDebug((s), __FILE__, __LINE__)
#define OVR_ALLOC_DEBUG(s,f,l)  OVR::Allocator::GetInstance()->AllocDebug((s), f, l)
#else
#define OVR_ALLOC(s)            OVR::Allocator::GetInstance()->Alloc((s))
#define OVR_ALLOC_DEBUG(s,f,l)  OVR::Allocator::GetInstance()->Alloc((s))
#endif

//------------------------------------------------------------------------

// Base class that overrides the new and delete operators.
// Deriving from this class, even as a multiple base, incurs no space overhead.
class NewOverrideBase
{
public:

    // Redefine all new & delete operators.
    OVR_MEMORY_REDEFINE_NEW(NewOverrideBase)
};


//------------------------------------------------------------------------
// ***** Mapped memory allocation
//
// Equates to VirtualAlloc/VirtualFree on Windows, mmap/munmap on Unix.
// These are useful for when you need system-supplied memory pages. 
// These are also useful for when you need to allocate memory in a way 
// that doesn't affect the application heap.

void* MMapAlloc(size_t size);
void  MMapFree(void* memory, size_t size);


} // OVR


// Redefine operator 'new' if necessary.
#if defined(OVR_DEFINE_NEW)
#define new OVR_DEFINE_NEW
#endif


#endif // OVR_Memory