scoped_temp_dir_win.cc 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2015 The Crashpad Authors. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "test/scoped_temp_dir.h"
  15. #include <windows.h>
  16. #include "base/logging.h"
  17. #include "base/strings/string16.h"
  18. #include "base/strings/stringprintf.h"
  19. #include "base/strings/utf_string_conversions.h"
  20. #include "util/misc/random_string.h"
  21. #include "gtest/gtest.h"
  22. namespace crashpad {
  23. namespace test {
  24. namespace {
  25. base::FilePath GenerateCandidateName() {
  26. wchar_t temp_path[MAX_PATH + 1];
  27. DWORD path_len = GetTempPath(MAX_PATH, temp_path);
  28. PCHECK(path_len != 0) << "GetTempPath";
  29. base::FilePath system_temp_dir(temp_path);
  30. base::string16 new_dir_name = base::UTF8ToUTF16(base::StringPrintf(
  31. "crashpad.test.%lu.%s", GetCurrentProcessId(), RandomString().c_str()));
  32. return system_temp_dir.Append(new_dir_name);
  33. }
  34. constexpr int kRetries = 50;
  35. } // namespace
  36. void ScopedTempDir::Rename() {
  37. for (int count = 0; count < kRetries; ++count) {
  38. // Try to move to a new temporary directory with a randomly generated name.
  39. // If the one we try exists, retry with a new name until we reach some
  40. // limit.
  41. base::FilePath target_path = GenerateCandidateName();
  42. if (MoveFileEx(path_.value().c_str(), target_path.value().c_str(), 0)) {
  43. path_ = target_path;
  44. return;
  45. }
  46. }
  47. CHECK(false) << "Couldn't move to a new unique temp dir";
  48. }
  49. // static
  50. base::FilePath ScopedTempDir::CreateTemporaryDirectory() {
  51. for (int count = 0; count < kRetries; ++count) {
  52. // Try to create a new temporary directory with random generated name. If
  53. // the one we generate exists, keep trying another path name until we reach
  54. // some limit.
  55. base::FilePath path_to_create = GenerateCandidateName();
  56. if (CreateDirectory(path_to_create.value().c_str(), NULL))
  57. return path_to_create;
  58. }
  59. CHECK(false) << "Couldn't create a new unique temp dir";
  60. return base::FilePath();
  61. }
  62. } // namespace test
  63. } // namespace crashpad