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 #if !HARNESS_SKIP_TEST && TBB_USE_EXCEPTIONS
28 
29 #include "../../src/tbb/tls.h"
30 
31 tbb::detail::r1::tls<bool> new_handler_called;
32 void customNewHandler() {
33     new_handler_called = true;
34     throw std::bad_alloc();
35 }
36 
37 // Return true if operator new threw exception
38 bool allocateWithException(size_t big_mem) {
39     bool exception_caught = false;
40     try {
41         // Allocate big array (should throw exception)
42         char* volatile big_array = new char[big_mem];
43         // If succeeded, double the size (unless it overflows) and recursively retry
44         if (big_mem * 2 > big_mem) {
45             exception_caught = allocateWithException(big_mem * 2);
46         }
47         delete[] big_array;
48     } catch (const std::bad_alloc&) {
49         bool is_called = new_handler_called;
50         REQUIRE_MESSAGE(is_called, "User provided new_handler was not called.");
51         exception_caught = true;
52     }
53     return exception_caught;
54 }
55 
56 class AllocLoopBody : utils::NoAssign {
57 public:
58     void operator()(int) const {
59         size_t BIG_MEM = 100 * 1024 * 1024;
60         new_handler_called = false;
61         REQUIRE_MESSAGE(allocateWithException(BIG_MEM), "Operator new did not throw bad_alloc.");
62     }
63 };
64 
65 //! \brief \ref error_guessing
66 TEST_CASE("New handler callback") {
67 #if __TBB_CPP11_GET_NEW_HANDLER_PRESENT
68     std::new_handler default_handler = std::get_new_handler();
69     REQUIRE_MESSAGE(default_handler == nullptr, "No handler should be set at this point.");
70 #endif
71     // Define the handler for new operations
72     std::set_new_handler(customNewHandler);
73     // Run the test
74     utils::NativeParallelFor(8, AllocLoopBody());
75     // Undo custom handler
76     std::set_new_handler(0);
77 }
78 #endif // !HARNESS_SKIP_TEST && TBB_USE_EXCEPTIONS
79