summaryrefslogtreecommitdiff
path: root/src/jit/hostallocator.h
blob: 447fc67eb14df8d64eefb7d78fd31acef190e692 (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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#pragma once

class HostAllocator final
{
private:
    HostAllocator()
    {
    }

public:
    template <typename T>
    T* allocate(size_t count)
    {
        ClrSafeInt<size_t> safeElemSize(sizeof(T));
        ClrSafeInt<size_t> safeCount(count);
        ClrSafeInt<size_t> size = safeElemSize * safeCount;
        if (size.IsOverflow())
        {
            return nullptr;
        }

        return static_cast<T*>(allocateHostMemory(size.Value()));
    }

    void deallocate(void* p)
    {
        freeHostMemory(p);
    }

    static HostAllocator getHostAllocator()
    {
        return HostAllocator();
    }

private:
    void* allocateHostMemory(size_t size);
    void freeHostMemory(void* p);
};

// Global operator new overloads that work with HostAllocator

inline void* __cdecl operator new(size_t n, HostAllocator alloc)
{
    return alloc.allocate<char>(n);
}

inline void* __cdecl operator new[](size_t n, HostAllocator alloc)
{
    return alloc.allocate<char>(n);
}