1 /*
2  * Copyright (c) 2024 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 #ifndef _MUSL_SOCKET_PREINIT_COMMON_H
17 #define _MUSL_SOCKET_PREINIT_COMMON_H
18 
19 #include <stdio.h>
20 #include "musl_socket_dispatch.h"
21 #include "common_def.h"
22 
23 extern struct SocketDispatchType __musl_libc_socket_dispatch;
24 extern struct SocketDispatchType __libc_socket_default_dispatch;
25 
26 enum SocketFuncEnum {
27 	INITIALIZE_FUNC,
28 	FINALIZE_FUNC,
29 	GET_HOOK_FLAG_FUNC,
30 	SET_HOOK_FLAG_FUNC,
31 	LAST_FUNC,
32 };
33 
34 #ifdef OHOS_SOCKET_HOOK_ENABLE
35 extern long long __current_dispatch;
36 extern bool __socket_hook_begin_flag;
37 extern long long __ohos_socket_hook_shared_library;
38 extern void* shared_lib_func[LAST_FUNC];
39 #endif
40 
41 #ifdef __cplusplus
42 extern "C" {
43 #endif
44 
45 __attribute__((always_inline))
__get_socket_hook_begin_flag()46 inline bool __get_socket_hook_begin_flag()
47 {
48 #ifdef OHOS_SOCKET_HOOK_ENABLE
49 	return __socket_hook_begin_flag;
50 #else
51 	return false;
52 #endif
53 }
54 
55 __attribute__((always_inline))
__get_socket_hook_flag()56 inline bool __get_socket_hook_flag()
57 {
58 #ifdef OHOS_SOCKET_HOOK_ENABLE
59 	void* handle = (void *)__ohos_socket_hook_shared_library;
60 	if (handle == NULL) {
61 		return false;
62 	} else if (handle == (void *)-1) {
63 		return true;
64 	} else {
65 		SocketGetHookFlagType get_hook_func_ptr = (SocketGetHookFlagType)(shared_lib_func[GET_HOOK_FLAG_FUNC]);
66 		bool flag = get_hook_func_ptr();
67 		return flag;
68 	}
69 #else
70 	return false;
71 #endif
72 }
73 
74 __attribute__((always_inline))
get_socket_dispatch()75 inline volatile const struct SocketDispatchType* get_socket_dispatch()
76 {
77 #ifdef OHOS_SOCKET_HOOK_ENABLE
78 	volatile const struct SocketDispatchType* ret = (struct SocketDispatchType *)__current_dispatch;
79 	if (ret != NULL) {
80 		if (!__get_socket_hook_begin_flag()) {
81 			ret = NULL;
82 		} else if (!__get_socket_hook_flag()) {
83 			ret = NULL;
84 		} else {
85 			return ret;
86 		}
87 	}
88 	return ret;
89 #else
90 	return NULL;
91 #endif
92 }
93 
94 #ifdef __cplusplus
95 }
96 #endif
97 
98 #endif
99