1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
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 */
15
16 #include <stdio.h>
17 #include <dlfcn.h>
18 #include <stdbool.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <sys/prctl.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <unistd.h>
25 #include <link.h>
26
27 #if defined (__arm__)
28 #define ASAN_LINKER "/lib/ld-musl-arm-asan.so.1"
29 #define LIB "/lib/"
30 #elif defined (__aarch64__)
31 #define ASAN_LINKER "/lib/ld-musl-aarch64-asan.so.1"
32 #define LIB "/lib64/"
33 #elif defined (__riscv) && __riscv_xlen == 64
34 #define ASAN_LINKER "/lib/ld-musl-riscv64-asan.so.1"
35 #define LIB "/lib64/"
36 #else
37 #error "unsupported arch"
38 #endif
39
40 static int g_isAsan = false;
41
dl_iterate_phdr_callback(struct dl_phdr_info * info,size_t size,void * args)42 static int dl_iterate_phdr_callback(struct dl_phdr_info *info, size_t size, void *args)
43 {
44 return info && info->dlpi_name && (strcmp(info->dlpi_name, ASAN_LINKER) == 0);
45 }
46
init(void)47 static void __attribute__((constructor)) init(void)
48 {
49 g_isAsan = dl_iterate_phdr(dl_iterate_phdr_callback, NULL);
50 }
51
52 typedef void* (*dlopen_fn_t)(const char *file, int mode);
53 static void *trap_dlopen(const char *file, int mode);
54 static dlopen_fn_t real_dlopen = trap_dlopen;
trap_dlopen(const char * file,int mode)55 static void *trap_dlopen(const char *file, int mode)
56 {
57 dlopen_fn_t fn = dlsym(RTLD_NEXT, "dlopen");
58 if (fn) {
59 real_dlopen = fn;
60 return fn(file, mode);
61 }
62 abort();
63 }
64
dlopen(const char * file,int mode)65 void *dlopen(const char *file, int mode)
66 {
67 while (g_isAsan && file != NULL) {
68 char *p = strstr(file, LIB);
69 if (p == NULL) {
70 break;
71 }
72
73 char *f = NULL;
74 asprintf(&f, "%.*s/asan%s", (int)(p - file), file, p);
75 if (f == NULL) {
76 break;
77 }
78
79 void *ret = real_dlopen(f, mode);
80 free(f);
81 f = NULL;
82 if (ret != NULL) {
83 return ret;
84 }
85 break;
86 }
87 return real_dlopen(file, mode);
88 }
89