scoped_clear_last_error.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. #include "build/build_config.h"
  9. namespace base {
  10. // ScopedClearLastError stores and resets the value of thread local error codes
  11. // (errno, GetLastError()), and restores them in the destructor. This is useful
  12. // to avoid side effects on these values in instrumentation functions that
  13. // interact with the OS.
  14. // Common implementation of ScopedClearLastError for all platforms. Use
  15. // ScopedClearLastError instead.
  16. class BASE_EXPORT ScopedClearLastErrorBase {
  17. public:
  18. ScopedClearLastErrorBase() : last_errno_(errno) { errno = 0; }
  19. ScopedClearLastErrorBase(const ScopedClearLastErrorBase&) = delete;
  20. ScopedClearLastErrorBase& operator=(const ScopedClearLastErrorBase&) = delete;
  21. ~ScopedClearLastErrorBase() { errno = last_errno_; }
  22. private:
  23. const int last_errno_;
  24. };
  25. #if BUILDFLAG(IS_WIN)
  26. // Windows specific implementation of ScopedClearLastError.
  27. class BASE_EXPORT ScopedClearLastError : public ScopedClearLastErrorBase {
  28. public:
  29. ScopedClearLastError();
  30. ScopedClearLastError(const ScopedClearLastError&) = delete;
  31. ScopedClearLastError& operator=(const ScopedClearLastError&) = delete;
  32. ~ScopedClearLastError();
  33. private:
  34. const unsigned long last_system_error_;
  35. };
  36. #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
  37. using ScopedClearLastError = ScopedClearLastErrorBase;
  38. #endif // BUILDFLAG(IS_WIN)
  39. } // namespace base
  40. #endif // BASE_SCOPED_CLEAR_LAST_ERROR_H_