1 /* 2 Copyright (c) 2005-2021 Intel Corporation 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 //! \file test_malloc_new_handler.cpp 18 //! \brief Test for [memory_allocation] functionality 19 20 #define __TBB_NO_IMPLICIT_LINKAGE 1 21 22 #include "common/test.h" 23 #include "common/utils.h" 24 25 #include "common/allocator_overload.h" 26 27 // Under ASAN current approach is not viable as it breaks the ASAN itself as well 28 #if !HARNESS_SKIP_TEST && TBB_USE_EXCEPTIONS && !__TBB_USE_ADDRESS_SANITIZER 29 30 #if _MSC_VER 31 #pragma warning (push) 32 // Forcing value to bool 'true' or 'false' (occurred inside tls.h) 33 #pragma warning (disable: 4800) 34 #endif //#if _MSC_VER 35 36 thread_local bool new_handler_called = false; 37 void customNewHandler() { 38 new_handler_called = true; 39 throw std::bad_alloc(); 40 } 41 42 // Return true if operator new threw exception 43 bool allocateWithException(size_t big_mem) { 44 bool exception_caught = false; 45 try { 46 // Allocate big array (should throw exception) 47 char* volatile big_array = new char[big_mem]; 48 // If succeeded, double the size (unless it overflows) and recursively retry 49 if (big_mem * 2 > big_mem) { 50 exception_caught = allocateWithException(big_mem * 2); 51 } 52 delete[] big_array; 53 } catch (const std::bad_alloc&) { 54 bool is_called = new_handler_called; 55 REQUIRE_MESSAGE(is_called, "User provided new_handler was not called."); 56 exception_caught = true; 57 } 58 return exception_caught; 59 } 60 61 class AllocLoopBody : utils::NoAssign { 62 public: 63 void operator()(int) const { 64 size_t BIG_MEM = 100 * 1024 * 1024; 65 new_handler_called = false; 66 REQUIRE_MESSAGE(allocateWithException(BIG_MEM), "Operator new did not throw bad_alloc."); 67 } 68 }; 69 70 //! \brief \ref error_guessing 71 TEST_CASE("New handler callback") { 72 #if __TBB_CPP11_GET_NEW_HANDLER_PRESENT 73 std::new_handler default_handler = std::get_new_handler(); 74 REQUIRE_MESSAGE(default_handler == nullptr, "No handler should be set at this point."); 75 #endif 76 // Define the handler for new operations 77 std::set_new_handler(customNewHandler); 78 // Run the test 79 utils::NativeParallelFor(8, AllocLoopBody()); 80 // Undo custom handler 81 std::set_new_handler(nullptr); 82 } 83 84 #if _MSC_VER 85 #pragma warning (pop) 86 #endif 87 88 #endif // !HARNESS_SKIP_TEST && TBB_USE_EXCEPTIONS 89