Google Cloud C++ Client  0.4.0
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  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([](const char* msg) {
46  std::cerr << "Aborting because exceptions are disabled: " << msg
47  << std::endl;
48  std::abort();
49  });
50  return f;
51 }
52 
53 } // anonymous namespace
54 
55 TerminateHandler SetTerminateHandler(TerminateHandler f) {
56  return GetTerminateHolder().Set(std::move(f));
57 }
58 
59 TerminateHandler GetTerminateHandler() { return GetTerminateHolder().Get(); }
60 
61 [[noreturn]] void Terminate(const char* msg) {
62  GetTerminateHolder().Get()(msg);
63  std::cerr << "Aborting because the installed terminate handler returned. "
64  "Error details: "
65  << msg << std::endl;
66  std::abort();
67 }
68 
69 } // namespace GOOGLE_CLOUD_CPP_NS
70 } // namespace cloud
71 } // namespace google
#define GOOGLE_CLOUD_CPP_NS
Definition: version.h:24
Contains all the Google Cloud C++ Library APIs.
Definition: iam_bindings.cc:21
TerminateHandler SetTerminateHandler(TerminateHandler f)
Install terminate handler and get the old one atomically.
void Terminate(const char *msg)
Invoke the currently installed handler.
TerminateHandler GetTerminateHandler()
Get the currently installed handler.