unilink  0.4.3
A simple C++ library for unified async communication
memory_validator.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2025 Jinwoo Sung
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 #pragma once
18 
19 #include <cstdint>
20 #include <cstring>
21 #include <memory>
22 #include <stdexcept>
23 #include <vector>
24 
26 
27 namespace unilink {
28 namespace memory {
29 
33 namespace memory_validator {
34 
41 bool is_memory_accessible(const void* ptr, size_t size);
42 
49 bool is_memory_aligned(const void* ptr, size_t alignment);
50 
58 bool check_buffer_bounds(const void* ptr, size_t size, size_t canary_size = 8);
59 
66 void initialize_canary_bytes(void* ptr, size_t size, size_t canary_size = 8);
67 
75 bool validate_canary_bytes(const void* ptr, size_t size, size_t canary_size = 8);
76 
84 void safe_memcpy_validated(void* dest, const void* src, size_t size);
85 
93 void safe_memmove_validated(void* dest, const void* src, size_t size);
94 
102 void safe_memset_validated(void* ptr, int value, size_t size);
103 
109 bool is_double_free(void* ptr);
110 
116 bool is_use_after_free(const void* ptr);
117 
118 } // namespace memory_validator
119 
124  public:
125  explicit MemoryValidator(void* ptr, size_t size, size_t canary_size = 8);
127 
128  // Non-copyable, non-movable
133 
134  // Validation methods
135  bool validate() const;
136  void check_bounds() const;
137 
138  // Access methods
139  void* data() const { return ptr_; }
140  size_t size() const { return size_; }
141 
142  private:
143  void* ptr_;
144  size_t size_;
145  size_t canary_size_;
146  std::vector<uint8_t> original_canaries_;
147  bool canaries_initialized_;
148 
149  void initialize_canaries();
150  bool validate_canaries() const;
151 };
152 
157  public:
158  static std::vector<uint8_t> generate_pattern(size_t size, uint8_t seed = 0xAA);
159  static std::vector<uint8_t> generate_random_pattern(size_t size);
160  static bool validate_pattern(const void* ptr, size_t size, uint8_t expected_seed = 0xAA);
161 };
162 
163 } // namespace memory
164 } // namespace unilink
#define UNILINK_API
Definition: visibility.hpp:37