• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 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 
16 #ifndef PANDA_LIBPANDABASE_MEM_CODE_ALLOCATOR_H_
17 #define PANDA_LIBPANDABASE_MEM_CODE_ALLOCATOR_H_
18 
19 #include "utils/arena_containers.h"
20 #include "os/mem.h"
21 #include "os/mutex.h"
22 
23 namespace panda {
24 
25 class BaseMemStats;
26 
27 class CodeAllocator {
28 public:
29     explicit CodeAllocator(BaseMemStats *mem_stats);
30     ~CodeAllocator();
31     NO_COPY_SEMANTIC(CodeAllocator);
32     NO_MOVE_SEMANTIC(CodeAllocator);
33 
34     /**
35      * \brief Allocates \param size bytes, copies \param codeBuff to allocated memory and makes this memory executable
36      * @param size
37      * @param codeBuff
38      * @return
39      */
40     [[nodiscard]] void *AllocateCode(size_t size, const void *code_buff);
41 
42     /**
43      * \brief Allocates \param size bytes of non-protected memory
44      * @param size to be allocated
45      * @return MapRange of the allocated code
46      */
47     [[nodiscard]] os::mem::MapRange<std::byte> AllocateCodeUnprotected(size_t size);
48 
49     /**
50      * Make memory \mem_range executable
51      * @param mem_range
52      */
53     static void ProtectCode(os::mem::MapRange<std::byte> mem_range);
54 
55     /**
56      * Fast checks if the given program counter belongs to JIT code
57      */
58     bool InAllocatedCodeRange(const void *pc);
59 
60 private:
61     void CodeRangeUpdate(void *ptr, size_t size);
62 
63 private:
64     static const Alignment PAGE_LOG_ALIGN;
65 
66     ArenaAllocator arenaAllocator_;
67     BaseMemStats *memStats_;
68     os::memory::RWLock code_range_lock_;
69     void *codeRangeStart_;
70     void *codeRangeEnd_;
71 };
72 
73 }  // namespace panda
74 
75 #endif  // PANDA_LIBPANDABASE_MEM_CODE_ALLOCATOR_H_
76