gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/test/util/errno_safe_allocator.cc (about) 1 // Copyright 2024 The gVisor Authors. 2 // 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 // new and delete that preserves errno in case of success. 16 17 #include <errno.h> 18 #include <stdlib.h> 19 20 namespace { 21 void* errno_safe_malloc(size_t size) { 22 int original_errno = errno; 23 void* result = malloc(size); 24 if (result != nullptr) { 25 errno = original_errno; 26 } 27 return result; 28 } 29 30 void errno_safe_free(void* p) { 31 int original_errno = errno; 32 free(p); 33 errno = original_errno; 34 } 35 } // namespace 36 37 void* operator new(size_t size) { return errno_safe_malloc(size); } 38 void* operator new[](size_t size) { return errno_safe_malloc(size); } 39 void operator delete(void* p) { errno_safe_free(p); } 40 void operator delete[](void* p) { errno_safe_free(p); }