1/*
2 * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved.
3 *
4 * NVIDIA CORPORATION and its licensors retain all intellectual property
5 * and proprietary rights in and to this software, related documentation
6 * and any modifications thereto. Any use, reproduction, disclosure or
7 * distribution of this software and related documentation without an express
8 * license agreement from NVIDIA CORPORATION is strictly prohibited.
9 */
10// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
11// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
12
13
14#ifndef PX_DEFAULT_ALLOCATOR_H
15#define PX_DEFAULT_ALLOCATOR_H
16/** \addtogroup extensions
17 @{
18*/
19
20#include "foundation/PxAllocatorCallback.h"
21#include "common/PxPhysXCommonConfig.h"
22#include "foundation/PxAssert.h"
23#include <stdlib.h>
24
25#if defined(PX_WINDOWS) || defined(PX_LINUX) || defined(PX_ANDROID)
26#include <malloc.h>
27#endif
28
29#ifndef PX_DOXYGEN
30namespace physx
31{
32#endif
33
34#if defined(PX_WINDOWS) || defined(PX_WINMODERN)
35// on win32 we only have 8-byte alignment guaranteed, but the CRT provides special aligned allocation fns
36PX_FORCE_INLINE void* platformAlignedAlloc(size_t size)
37{
38 return _aligned_malloc(size, 16);
39}
40
41PX_FORCE_INLINE void platformAlignedFree(void* ptr)
42{
43 _aligned_free(ptr);
44}
45#elif defined(PX_LINUX) || defined(PX_ANDROID)
46PX_FORCE_INLINE void* platformAlignedAlloc(size_t size)
47{
48 return ::memalign(16, size);
49}
50
51PX_FORCE_INLINE void platformAlignedFree(void* ptr)
52{
53 ::free(ptr);
54}
55#elif defined(PX_WIIU)
56PX_FORCE_INLINE void* platformAlignedAlloc(size_t size)
57{
58 size_t pad = 15 + sizeof(size_t); // store offset for delete.
59 PxU8* base = (PxU8*)::malloc(size+pad);
60 if(!base)
61 return NULL;
62
63 PxU8* ptr = (PxU8*)(size_t(base + pad) & ~(15)); // aligned pointer
64 ((size_t*)ptr)[-1] = ptr - base; // store offset
65
66 return ptr;
67}
68
69PX_FORCE_INLINE void platformAlignedFree(void* ptr)
70{
71 if(ptr == NULL)
72 return;
73
74 PxU8* base = ((PxU8*)ptr) - ((size_t*)ptr)[-1];
75 ::free(base);
76}
77#else
78// on all other platforms we get 16-byte alignment by default
79PX_FORCE_INLINE void* platformAlignedAlloc(size_t size)
80{
81 return ::malloc(size);
82}
83
84PX_FORCE_INLINE void platformAlignedFree(void* ptr)
85{
86 ::free(ptr);
87}
88#endif
89
90/**
91\brief default implementation of the allocator interface required by the SDK
92*/
93class PxDefaultAllocator : public PxAllocatorCallback
94{
95public:
96 void* allocate(size_t size, const char*, const char*, int)
97 {
98 void* ptr = platformAlignedAlloc(size);
99 PX_ASSERT((reinterpret_cast<size_t>(ptr) & 15)==0);
100 return ptr;
101 }
102
103 void deallocate(void* ptr)
104 {
105 platformAlignedFree(ptr);
106 }
107};
108
109#ifndef PX_DOXYGEN
110} // namespace physx
111#endif
112
113/** @} */
114#endif
115