xref: /aosp_15_r20/external/grpc-grpc/test/core/util/socket_use_after_close_detector.h (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 //
2 //
3 // Copyright 2017 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18 
19 #ifndef GRPC_TEST_CORE_UTIL_SOCKET_USE_AFTER_CLOSE_DETECTOR_H
20 #define GRPC_TEST_CORE_UTIL_SOCKET_USE_AFTER_CLOSE_DETECTOR_H
21 
22 #include <memory>
23 #include <thread>
24 
25 #include <grpc/support/port_platform.h>
26 #include <grpc/support/sync_generic.h>
27 
28 namespace grpc_core {
29 namespace testing {
30 
31 // This class is meant to detect file descriptor use-after-close
32 // bugs occuring somewhere in the program while the object is in live.
33 // The implementation currently uses a background thread to open
34 // and close sockets in a loop, catching socket use-after-close bugs
35 // by watching them manifest as unexpected socket operation failures.
36 //
37 // Note: this will not give false positives but may give false negatives.
38 // That said this seems to be fairly reliable at finding use-after-close
39 // bugs, at least on linux, because of fd handles being quickly reused.
40 // For example this was able to catch the use-after-close bug from
41 // https://github.com/grpc/grpc/pull/33871 "almost every time".
42 class SocketUseAfterCloseDetector {
43  public:
44   SocketUseAfterCloseDetector();
45   ~SocketUseAfterCloseDetector();
46 
47  private:
48   std::unique_ptr<std::thread> thread_;
49   gpr_event done_ev_;
50 };
51 
52 }  // namespace testing
53 }  // namespace grpc_core
54 
55 #endif  // GRPC_TEST_CORE_UTIL_SOCKET_USE_AFTER_CLOSE_DETECTOR_H
56