• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #ifndef PANDA_RUNTIME_MEM_MALLOC_PROXY_ALLOCATOR_H
16 #define PANDA_RUNTIME_MEM_MALLOC_PROXY_ALLOCATOR_H
17 
18 #include <functional>
19 #include <map>
20 #include <memory>
21 #include <unordered_map>
22 #include <type_traits>
23 
24 #include "libpandabase/mem/mem.h"
25 #include "libpandabase/mem/space.h"
26 #include "libpandabase/os/mutex.h"
27 
28 namespace panda::mem {
29 
30 using panda::Alignment;
31 class EmptyMemoryConfig;
32 
33 /**
34  * \brief Class-proxy to the malloc, do some logging.
35  */
36 template <typename AllocConfigT>
37 class MallocProxyAllocator {
38 public:
39     NO_COPY_SEMANTIC(MallocProxyAllocator);
40     NO_MOVE_SEMANTIC(MallocProxyAllocator);
41 
42     explicit MallocProxyAllocator(MemStatsType *mem_stats, SpaceType type_allocation = SpaceType::SPACE_TYPE_INTERNAL)
type_allocation_(type_allocation)43         : type_allocation_(type_allocation), mem_stats_ {mem_stats}
44     {
45     }
46 
47     ~MallocProxyAllocator();
48 
49     [[nodiscard]] void *Alloc(size_t size, Alignment align = DEFAULT_ALIGNMENT);
50 
51     template <class T>
AllocArray(size_t size)52     T *AllocArray(size_t size)
53     {
54         return static_cast<T *>(this->Alloc(sizeof(T) * size));
55     }
56 
57     void Free(void *mem);
58 
59 private:
60     static constexpr bool DUMMY_ALLOC_CONFIG = std::is_same<AllocConfigT, EmptyMemoryConfig>::value;
61     std::unordered_map<void *, size_t> allocated_memory_;
62     SpaceType type_allocation_;
63     MemStatsType *mem_stats_;
64     os::memory::Mutex lock_;
65 };
66 
67 }  // namespace panda::mem
68 
69 #endif  // PANDA_RUNTIME_MEM_MALLOC_PROXY_ALLOCATOR_H
70