blob: 1268b2f4e9078d8941e6c379d0ea9174b3657029 [file] [log] [blame]
Joshua Perazab427af262020-04-13 21:54:421// Copyright 2018 The Chromium Authors. All rights reserved.
Etienne Pierre-Dorayd120ebf2018-09-14 23:38:212// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef BASE_SCOPED_CLEAR_LAST_ERROR_H_
6#define BASE_SCOPED_CLEAR_LAST_ERROR_H_
7
8#include <errno.h>
9
10#include "base/base_export.h"
David Bienvenu5f4d4f02020-09-27 16:55:0311// TODO(crbug.com/1010217) Remove once no #includers are getting base/macros.h
12// by including this header.
Etienne Pierre-Dorayd120ebf2018-09-14 23:38:2113#include "base/macros.h"
14#include "build/build_config.h"
15
16namespace base {
Etienne Pierre-Dorayd120ebf2018-09-14 23:38:2117
18// ScopedClearLastError stores and resets the value of thread local error codes
19// (errno, GetLastError()), and restores them in the destructor. This is useful
20// to avoid side effects on these values in instrumentation functions that
21// interact with the OS.
22
23// Common implementation of ScopedClearLastError for all platforms. Use
24// ScopedClearLastError instead.
25class BASE_EXPORT ScopedClearLastErrorBase {
26 public:
27 ScopedClearLastErrorBase() : last_errno_(errno) { errno = 0; }
David Bienvenu5f4d4f02020-09-27 16:55:0328 ScopedClearLastErrorBase(const ScopedClearLastErrorBase&) = delete;
29 ScopedClearLastErrorBase& operator=(const ScopedClearLastErrorBase&) = delete;
Etienne Pierre-Dorayd120ebf2018-09-14 23:38:2130 ~ScopedClearLastErrorBase() { errno = last_errno_; }
31
32 private:
33 const int last_errno_;
Etienne Pierre-Dorayd120ebf2018-09-14 23:38:2134};
35
36#if defined(OS_WIN)
37
38// Windows specific implementation of ScopedClearLastError.
39class BASE_EXPORT ScopedClearLastError : public ScopedClearLastErrorBase {
40 public:
41 ScopedClearLastError();
David Bienvenu5f4d4f02020-09-27 16:55:0342 ScopedClearLastError(const ScopedClearLastError&) = delete;
43 ScopedClearLastError& operator=(const ScopedClearLastError&) = delete;
Etienne Pierre-Dorayd120ebf2018-09-14 23:38:2144 ~ScopedClearLastError();
45
46 private:
Joshua Perazab427af262020-04-13 21:54:4247 const unsigned long last_system_error_;
Etienne Pierre-Dorayd120ebf2018-09-14 23:38:2148};
49
50#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
51
52using ScopedClearLastError = ScopedClearLastErrorBase;
53
54#endif // defined(OS_WIN)
55
Etienne Pierre-Dorayd120ebf2018-09-14 23:38:2156} // namespace base
57
58#endif // BASE_SCOPED_CLEAR_LAST_ERROR_H_