• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #else
34 #error "unsupported arch"
35 #endif
36 
37 static int g_isAsan = false;
38 
dl_iterate_phdr_callback(struct dl_phdr_info * info,size_t size,void * args)39 static int dl_iterate_phdr_callback(struct dl_phdr_info *info, size_t size, void *args)
40 {
41     return info && info->dlpi_name && (strcmp(info->dlpi_name, ASAN_LINKER) == 0);
42 }
43 
init(void)44 static void __attribute__((constructor)) init(void)
45 {
46     g_isAsan = dl_iterate_phdr(dl_iterate_phdr_callback, NULL);
47 }
48 
49 typedef void* (*dlopen_fn_t)(const char *file, int mode);
50 static void *trap_dlopen(const char *file, int mode);
51 static dlopen_fn_t real_dlopen = trap_dlopen;
trap_dlopen(const char * file,int mode)52 static void *trap_dlopen(const char *file, int mode)
53 {
54     dlopen_fn_t fn = dlsym(RTLD_NEXT, "dlopen");
55     if (fn) {
56         real_dlopen = fn;
57         return fn(file, mode);
58     }
59     abort();
60 }
61 
dlopen(const char * file,int mode)62 void *dlopen(const char *file, int mode)
63 {
64     while (g_isAsan && file != NULL) {
65         char *p = strstr(file, LIB);
66         if (p == NULL) {
67             break;
68         }
69 
70         char *f = NULL;
71         asprintf(&f, "%.*s/asan%s", (int)(p - file), file, p);
72         if (f == NULL) {
73             break;
74         }
75 
76         void *ret = real_dlopen(f, mode);
77         free(f);
78         f = NULL;
79         if (ret != NULL) {
80             return ret;
81         }
82         break;
83     }
84     return real_dlopen(file, mode);
85 }
86