Florian Mayer | c10d064 | 2023-03-22 16:12:49 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2023 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #include <dlfcn.h> |
| 18 | #include <stdlib.h> |
| 19 | |
| 20 | #include <gtest/gtest.h> |
| 21 | |
| 22 | #include <android-base/silent_death_test.h> |
| 23 | #include <android-base/test_utils.h> |
| 24 | |
| 25 | using HwasanDeathTest = SilentDeathTest; |
| 26 | |
| 27 | TEST_F(HwasanDeathTest, UseAfterFree) { |
| 28 | EXPECT_DEATH( |
| 29 | { |
| 30 | void* m = malloc(1); |
| 31 | volatile char* x = const_cast<volatile char*>(reinterpret_cast<char*>(m)); |
| 32 | *x = 1; |
| 33 | free(m); |
| 34 | *x = 2; |
| 35 | }, |
| 36 | "use-after-free"); |
| 37 | } |
| 38 | |
| 39 | TEST_F(HwasanDeathTest, OutOfBounds) { |
| 40 | EXPECT_DEATH( |
| 41 | { |
| 42 | void* m = malloc(1); |
| 43 | volatile char* x = const_cast<volatile char*>(reinterpret_cast<char*>(m)); |
| 44 | x[1] = 1; |
| 45 | }, |
| 46 | "buffer-overflow"); |
| 47 | } |
| 48 | |
| 49 | // Check whether dlopen of /foo/bar.so checks /foo/hwasan/bar.so first. |
| 50 | TEST(HwasanTest, DlopenAbsolutePath) { |
| 51 | std::string path = android::base::GetExecutableDirectory() + "/libtest_simple_hwasan.so"; |
| 52 | ASSERT_EQ(0, access(path.c_str(), F_OK)); // Verify test setup. |
| 53 | std::string hwasan_path = |
| 54 | android::base::GetExecutableDirectory() + "/hwasan/libtest_simple_hwasan.so"; |
| 55 | ASSERT_EQ(0, access(hwasan_path.c_str(), F_OK)); // Verify test setup. |
| 56 | |
| 57 | void* handle = dlopen(path.c_str(), RTLD_NOW); |
| 58 | ASSERT_TRUE(handle != nullptr); |
| 59 | uint32_t* compiled_with_hwasan = |
| 60 | reinterpret_cast<uint32_t*>(dlsym(handle, "dlopen_testlib_compiled_with_hwasan")); |
| 61 | EXPECT_TRUE(*compiled_with_hwasan); |
| 62 | dlclose(handle); |
| 63 | } |
| 64 | |
| 65 | TEST(HwasanTest, IsRunningWithHWasan) { |
| 66 | EXPECT_TRUE(running_with_hwasan()); |
| 67 | } |