xref: /aosp_15_r20/external/webrtc/modules/desktop_capture/linux/x11/x_error_trap.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include "modules/desktop_capture/linux/x11/x_error_trap.h"
12 
13 #include <atomic>
14 
15 #include <stddef.h>
16 
17 #include "rtc_base/checks.h"
18 
19 namespace webrtc {
20 
21 namespace {
22 
23 static int g_last_xserver_error_code = 0;
24 static std::atomic<Display*> g_display_for_error_handler = nullptr;
25 
AcquireMutex()26 Mutex* AcquireMutex() {
27   static Mutex* mutex = new Mutex();
28   return mutex;
29 }
30 
XServerErrorHandler(Display * display,XErrorEvent * error_event)31 int XServerErrorHandler(Display* display, XErrorEvent* error_event) {
32   RTC_DCHECK_EQ(display, g_display_for_error_handler.load());
33   g_last_xserver_error_code = error_event->error_code;
34   return 0;
35 }
36 
37 }  // namespace
38 
XErrorTrap(Display * display)39 XErrorTrap::XErrorTrap(Display* display) : mutex_lock_(AcquireMutex()) {
40   // We don't expect this class to be used in a nested fashion so therefore
41   // g_display_for_error_handler should never be valid here.
42   RTC_DCHECK(!g_display_for_error_handler.load());
43   RTC_DCHECK(display);
44   g_display_for_error_handler.store(display);
45   g_last_xserver_error_code = 0;
46   original_error_handler_ = XSetErrorHandler(&XServerErrorHandler);
47 }
48 
GetLastErrorAndDisable()49 int XErrorTrap::GetLastErrorAndDisable() {
50   g_display_for_error_handler.store(nullptr);
51   XSetErrorHandler(original_error_handler_);
52   return g_last_xserver_error_code;
53 }
54 
~XErrorTrap()55 XErrorTrap::~XErrorTrap() {
56   if (g_display_for_error_handler.load() != nullptr)
57     GetLastErrorAndDisable();
58 }
59 
60 }  // namespace webrtc
61