initialization_state_test.cc 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2014 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 "util/misc/initialization_state.h"
  15. #include <stdlib.h>
  16. #include <memory>
  17. #include "base/memory/free_deleter.h"
  18. #include "gtest/gtest.h"
  19. namespace crashpad {
  20. namespace test {
  21. namespace {
  22. TEST(InitializationState, InitializationState) {
  23. // Use placement new so that the buffer used to host the object remains live
  24. // even after the object is destroyed.
  25. std::unique_ptr<InitializationState, base::FreeDeleter>
  26. initialization_state_buffer(
  27. static_cast<InitializationState*>(malloc(sizeof(InitializationState))));
  28. InitializationState* initialization_state =
  29. new (initialization_state_buffer.get()) InitializationState();
  30. EXPECT_TRUE(initialization_state->is_uninitialized());
  31. EXPECT_FALSE(initialization_state->is_valid());
  32. initialization_state->set_invalid();
  33. EXPECT_FALSE(initialization_state->is_uninitialized());
  34. EXPECT_FALSE(initialization_state->is_valid());
  35. initialization_state->set_valid();
  36. EXPECT_FALSE(initialization_state->is_uninitialized());
  37. EXPECT_TRUE(initialization_state->is_valid());
  38. initialization_state->~InitializationState();
  39. // initialization_state points to something that no longer exists. This
  40. // portion of the test is intended to check that after an InitializationState
  41. // object is destroyed, it will not be considered valid on a use-after-free,
  42. // assuming that nothing else was written to its former home in memory.
  43. //
  44. // Because initialization_state was constructed via placement new into a
  45. // buffer that’s still valid and its destructor was called directly, this
  46. // approximates use-after-free without risking that the memory formerly used
  47. // for the InitializationState object has been repurposed.
  48. EXPECT_FALSE(initialization_state->is_uninitialized());
  49. EXPECT_FALSE(initialization_state->is_valid());
  50. }
  51. } // namespace
  52. } // namespace test
  53. } // namespace crashpad