Google Cloud C++ Client  1.32.1
C++ Client Library for Google Cloud Platform
terminate_handler.cc
Go to the documentation of this file.
1 // Copyright 2018 Google LLC
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 #include "google/cloud/terminate_handler.h"
16 #include <iostream>
17 #include <mutex>
18 
19 namespace google {
20 namespace cloud {
21 inline namespace GOOGLE_CLOUD_CPP_NS {
22 namespace {
23 
24 class TerminateFunction {
25  public:
26  explicit TerminateFunction(TerminateHandler f) : f_(std::move(f)) {}
27 
28  TerminateHandler Get() {
29  std::lock_guard<std::mutex> l(m_);
30  return f_;
31  }
32 
33  TerminateHandler Set(TerminateHandler f) {
34  std::lock_guard<std::mutex> l(m_);
35  f.swap(f_);
36  return f;
37  }
38 
39  private:
40  std::mutex m_;
41  TerminateHandler f_;
42 };
43 
44 TerminateFunction& GetTerminateHolder() {
45  static TerminateFunction f([](char const* msg) {
46  std::cerr << "Aborting because exceptions are disabled: " << msg << "\n";
47  std::abort();
48  });
49  return f;
50 }
51 
52 } // anonymous namespace
53 
54 TerminateHandler SetTerminateHandler(TerminateHandler f) {
55  return GetTerminateHolder().Set(std::move(f));
56 }
57 
58 TerminateHandler GetTerminateHandler() { return GetTerminateHolder().Get(); }
59 
60 [[noreturn]] void Terminate(char const* msg) {
61  GetTerminateHolder().Get()(msg);
62  std::cerr << "Aborting because the installed terminate handler returned. "
63  "Error details: "
64  << msg << "\n";
65  std::abort();
66 }
67 
68 } // namespace GOOGLE_CLOUD_CPP_NS
69 } // namespace cloud
70 } // namespace google