89797ad50d6336d2712f0a0566b6592569d1caee
[platform/core/ml/nnfw.git] / runtime / contrib / heap_trace / src / memory_pool_for_symbol_searcher_internals.h
1 /*
2  * Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *    http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef MEMORY_POOL_FOR_SYMBOL_SEARCHER_INTERNALS_H
18 #define MEMORY_POOL_FOR_SYMBOL_SEARCHER_INTERNALS_H
19
20 #include <cstddef>
21 #include <cstdint>
22
23 // TODO this class possibly should be thread safe (or all symbols should be resolved at the start of
24 // application as alternative)
25 class MemoryPoolForSymbolSearcherInternals
26 {
27   static constexpr size_t MAX_SIZE = 65536;
28
29 public:
30   bool containsMemorySpaceStartedFromPointer(void *ptr) noexcept
31   {
32     return ptr >= _buffer && ptr < _buffer + MAX_SIZE;
33   }
34
35   // TODO this function should return alighned ptr to avoid potential problems
36   void *allocate(size_t size) noexcept
37   {
38     if (isSpaceOfRequiredSizeNotAvailable(size))
39     {
40       // TODO need to signalize about error
41     }
42
43     uint8_t *ptr_to_memory_space_begin = _ptr_to_free_space_start;
44     _ptr_to_free_space_start += size;
45     _size_of_last_allocated_space = size;
46     return ptr_to_memory_space_begin;
47   }
48
49   void deallocate(void *p) noexcept
50   {
51     if (p == _ptr_to_free_space_start - _size_of_last_allocated_space)
52     {
53       _ptr_to_free_space_start -= _size_of_last_allocated_space;
54       _size_of_last_allocated_space = 0;
55     }
56   }
57
58 private:
59   bool isSpaceOfRequiredSizeNotAvailable(size_t size)
60   {
61     uint8_t *ptr_to_the_free_space_after_allocation = _ptr_to_free_space_start + size;
62     size_t size_of_reserved_space_after_allocation =
63         ptr_to_the_free_space_after_allocation - _buffer;
64     if (size_of_reserved_space_after_allocation >= MAX_SIZE)
65     {
66       return false;
67     }
68
69     return true;
70   }
71
72 private:
73   static uint8_t _buffer[MAX_SIZE];
74   static uint8_t *volatile _ptr_to_free_space_start;
75   static volatile size_t _size_of_last_allocated_space;
76 };
77
78 #endif // ! MEMORY_POOL_FOR_SYMBOL_SEARCHER_INTERNALS_H