error_codes.cc 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2015 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. #include "chromecast/base/error_codes.h"
  5. #include <errno.h>
  6. #include <fcntl.h>
  7. #include <string>
  8. #include "base/files/file_util.h"
  9. #include "base/logging.h"
  10. #include "base/strings/string_number_conversions.h"
  11. #include "chromecast/base/path_utils.h"
  12. namespace chromecast {
  13. namespace {
  14. const char kInitialErrorFile[] = "initial_error";
  15. base::FilePath GetInitialErrorFilePath() {
  16. return GetHomePathASCII(kInitialErrorFile);
  17. }
  18. } // namespace
  19. ErrorCode GetInitialErrorCode() {
  20. std::string initial_error_code_str;
  21. if (!base::ReadFileToString(GetInitialErrorFilePath(),
  22. &initial_error_code_str)) {
  23. return NO_ERROR;
  24. }
  25. int initial_error_code = 0;
  26. if (base::StringToInt(initial_error_code_str, &initial_error_code) &&
  27. initial_error_code >= NO_ERROR && initial_error_code <= ERROR_UNKNOWN) {
  28. DVLOG(1) << "Initial error from " << GetInitialErrorFilePath().value()
  29. << ": " << initial_error_code;
  30. return static_cast<ErrorCode>(initial_error_code);
  31. }
  32. LOG(ERROR) << "Unknown initial error code: " << initial_error_code_str;
  33. return NO_ERROR;
  34. }
  35. bool SetInitialErrorCode(ErrorCode initial_error_code) {
  36. // Note: Do not use Chromium IO methods in this function. When cast_shell
  37. // crashes, this function can be called by any thread.
  38. const std::string error_file_path = GetInitialErrorFilePath().value();
  39. if (initial_error_code > NO_ERROR && initial_error_code <= ERROR_UNKNOWN) {
  40. const std::string initial_error_code_str(
  41. base::NumberToString(initial_error_code));
  42. int fd = creat(error_file_path.c_str(), 0640);
  43. if (fd < 0) {
  44. PLOG(ERROR) << "Could not open error code file";
  45. return false;
  46. }
  47. int written =
  48. write(fd, initial_error_code_str.data(), initial_error_code_str.size());
  49. if (written != static_cast<int>(initial_error_code_str.size())) {
  50. PLOG(ERROR) << "Could not write error code to file: written=" << written
  51. << ", expected=" << initial_error_code_str.size();
  52. close(fd);
  53. return false;
  54. }
  55. close(fd);
  56. return true;
  57. }
  58. // Remove initial error file if no error.
  59. if (unlink(error_file_path.c_str()) == 0 || errno == ENOENT)
  60. return true;
  61. PLOG(ERROR) << "Failed to remove error file";
  62. return false;
  63. }
  64. } // namespace chromecast