github.com/google/syzkaller@v0.0.0-20240517125934-c0f1611a36d6/executor/_include/flatbuffers/allocator.h (about) 1 /* 2 * Copyright 2021 Google Inc. 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 FLATBUFFERS_ALLOCATOR_H_ 18 #define FLATBUFFERS_ALLOCATOR_H_ 19 20 #include "flatbuffers/base.h" 21 22 namespace flatbuffers { 23 24 // Allocator interface. This is flatbuffers-specific and meant only for 25 // `vector_downward` usage. 26 class Allocator { 27 public: 28 virtual ~Allocator() {} 29 30 // Allocate `size` bytes of memory. 31 virtual uint8_t *allocate(size_t size) = 0; 32 33 // Deallocate `size` bytes of memory at `p` allocated by this allocator. 34 virtual void deallocate(uint8_t *p, size_t size) = 0; 35 36 // Reallocate `new_size` bytes of memory, replacing the old region of size 37 // `old_size` at `p`. In contrast to a normal realloc, this grows downwards, 38 // and is intended specifcally for `vector_downward` use. 39 // `in_use_back` and `in_use_front` indicate how much of `old_size` is 40 // actually in use at each end, and needs to be copied. 41 virtual uint8_t *reallocate_downward(uint8_t *old_p, size_t old_size, 42 size_t new_size, size_t in_use_back, 43 size_t in_use_front) { 44 FLATBUFFERS_ASSERT(new_size > old_size); // vector_downward only grows 45 uint8_t *new_p = allocate(new_size); 46 memcpy_downward(old_p, old_size, new_p, new_size, in_use_back, 47 in_use_front); 48 deallocate(old_p, old_size); 49 return new_p; 50 } 51 52 protected: 53 // Called by `reallocate_downward` to copy memory from `old_p` of `old_size` 54 // to `new_p` of `new_size`. Only memory of size `in_use_front` and 55 // `in_use_back` will be copied from the front and back of the old memory 56 // allocation. 57 void memcpy_downward(uint8_t *old_p, size_t old_size, uint8_t *new_p, 58 size_t new_size, size_t in_use_back, 59 size_t in_use_front) { 60 memcpy(new_p + new_size - in_use_back, old_p + old_size - in_use_back, 61 in_use_back); 62 memcpy(new_p, old_p, in_use_front); 63 } 64 }; 65 66 } // namespace flatbuffers 67 68 #endif // FLATBUFFERS_ALLOCATOR_H_