1 /*
2  * Copyright (C) 2017 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 <stdint.h>
18 #include <stdlib.h>
19 
20 #include "CHECK.h"
21 
22 // This library is built for all targets, including host tests, so __cfi_slowpath may not be
23 // present. But it is only used in the bionic loader tests.
24 extern "C" __attribute__((weak)) void __cfi_slowpath(uint64_t, void*);
25 
26 static int g_count;
27 
28 // Mock a CFI-enabled library without relying on the compiler.
29 extern "C" __attribute__((no_sanitize("hwaddress")))  __attribute__((aligned(4096)))
__cfi_check(uint64_t,void *,void *)30 void __cfi_check(uint64_t /*CallSiteTypeId*/, void* /*TargetAddr*/, void* /*Diag*/) {
31   ++g_count;
32 }
33 
34 // This code runs before hwasan is initialized.
35 __attribute__((no_sanitize("hwaddress")))
preinit_ctor()36 void preinit_ctor() {
37   CHECK(g_count == 0);
38   __cfi_slowpath(42, reinterpret_cast<void*>(&preinit_ctor));
39   CHECK(g_count == 1);
40 }
41 
42 __attribute__((section(".preinit_array"), used)) void (*preinit_ctor_p)(void) = preinit_ctor;
43 
ctor()44 __attribute__((constructor, used)) void ctor() {
45   CHECK(g_count == 1);
46   __cfi_slowpath(42, reinterpret_cast<void*>(&ctor));
47   CHECK(g_count == 2);
48 }
49 
main(void)50 int main(void) {
51   CHECK(g_count == 2);
52   __cfi_slowpath(42, reinterpret_cast<void*>(&main));
53   CHECK(g_count == 3);
54   return 0;
55 }
56