2 * Copyright (C) 2016 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "private/CFIShadow.h"
21 __attribute__((__weak__, visibility("default"))) extern "C" void __loader_cfi_fail(
22 uint64_t CallSiteTypeId, void* Ptr, void* DiagData, void* CallerPc);
24 // Base address of the CFI shadow. Passed down from the linker in __cfi_init()
25 // and does not change after that. The contents of the shadow change in
29 char padding[PAGE_SIZE - sizeof(v)];
30 } shadow_base_storage alignas(PAGE_SIZE);
32 // __cfi_init is called by the loader as soon as the shadow is mapped. This may happen very early
33 // during startup, before libdl.so global constructors, and, on i386, even before __libc_sysinfo is
34 // initialized. This function should not do any system calls.
35 extern "C" uintptr_t* __cfi_init(uintptr_t shadow_base) {
36 shadow_base_storage.v = shadow_base;
37 static_assert(sizeof(shadow_base_storage) == PAGE_SIZE, "");
38 return &shadow_base_storage.v;
41 static uint16_t shadow_load(void* p) {
42 uintptr_t addr = reinterpret_cast<uintptr_t>(p);
43 uintptr_t ofs = CFIShadow::MemToShadowOffset(addr);
44 if (ofs > CFIShadow::kShadowSize) return CFIShadow::kInvalidShadow;
45 return *reinterpret_cast<uint16_t*>(shadow_base_storage.v + ofs);
48 static uintptr_t cfi_check_addr(uint16_t v, void* Ptr) {
49 uintptr_t addr = reinterpret_cast<uintptr_t>(Ptr);
50 uintptr_t aligned_addr = align_up(addr, CFIShadow::kShadowAlign);
51 uintptr_t p = aligned_addr - (static_cast<uintptr_t>(v - CFIShadow::kRegularShadowMin)
52 << CFIShadow::kCfiCheckGranularity);
54 // Assume Thumb encoding. FIXME: force thumb at compile time?
60 static inline void cfi_slowpath_common(uint64_t CallSiteTypeId, void* Ptr, void* DiagData) {
61 uint16_t v = shadow_load(Ptr);
63 case CFIShadow::kInvalidShadow:
64 __loader_cfi_fail(CallSiteTypeId, Ptr, DiagData, __builtin_return_address(0));
66 case CFIShadow::kUncheckedShadow:
69 reinterpret_cast<CFIShadow::CFICheckFn>(cfi_check_addr(v, Ptr))(CallSiteTypeId, Ptr, DiagData);
73 extern "C" void __cfi_slowpath(uint64_t CallSiteTypeId, void* Ptr) {
74 cfi_slowpath_common(CallSiteTypeId, Ptr, nullptr);
77 extern "C" void __cfi_slowpath_diag(uint64_t CallSiteTypeId, void* Ptr, void* DiagData) {
78 cfi_slowpath_common(CallSiteTypeId, Ptr, DiagData);