scoped_clear_last_error.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2018 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_SCOPED_CLEAR_LAST_ERROR_H_
  5. #define BASE_SCOPED_CLEAR_LAST_ERROR_H_
  6. #include <errno.h>
  7. #include "base/base_export.h"
  8. // TODO(crbug.com/1010217) Remove once no #includers are getting base/macros.h
  9. // by including this header.
  10. #include "base/macros.h"
  11. #include "build/build_config.h"
  12. namespace base {
  13. // ScopedClearLastError stores and resets the value of thread local error codes
  14. // (errno, GetLastError()), and restores them in the destructor. This is useful
  15. // to avoid side effects on these values in instrumentation functions that
  16. // interact with the OS.
  17. // Common implementation of ScopedClearLastError for all platforms. Use
  18. // ScopedClearLastError instead.
  19. class BASE_EXPORT ScopedClearLastErrorBase {
  20. public:
  21. ScopedClearLastErrorBase() : last_errno_(errno) { errno = 0; }
  22. ScopedClearLastErrorBase(const ScopedClearLastErrorBase&) = delete;
  23. ScopedClearLastErrorBase& operator=(const ScopedClearLastErrorBase&) = delete;
  24. ~ScopedClearLastErrorBase() { errno = last_errno_; }
  25. private:
  26. const int last_errno_;
  27. };
  28. #if defined(OS_WIN)
  29. // Windows specific implementation of ScopedClearLastError.
  30. class BASE_EXPORT ScopedClearLastError : public ScopedClearLastErrorBase {
  31. public:
  32. ScopedClearLastError();
  33. ScopedClearLastError(const ScopedClearLastError&) = delete;
  34. ScopedClearLastError& operator=(const ScopedClearLastError&) = delete;
  35. ~ScopedClearLastError();
  36. private:
  37. const unsigned long last_system_error_;
  38. };
  39. #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
  40. using ScopedClearLastError = ScopedClearLastErrorBase;
  41. #endif // defined(OS_WIN)
  42. } // namespace base
  43. #endif // BASE_SCOPED_CLEAR_LAST_ERROR_H_