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#ifdef OHOS_FDTRACK_HOOK_ENABLE
17#include <stdlib.h>
18#include <dlfcn.h>
19#include <errno.h>
20#include <stdio.h>
21#include "musl_log.h"
22#include "musl_fdtrack_hook.h"
23
24static char *__fdtrack_hook_shared_lib = "libfdleak_tracker.so";
25
26int FDTRACK_START_HOOK(int fd_value)
27{
28	int fd = fd_value;
29	if (fd != -1 && __predict_false(__fdtrack_enabled) && __predict_false(__fdtrack_hook)) {
30		struct fdtrack_event event;
31		event.type = FDTRACK_EVENT_TYPE_CREATE;
32		event.fd = fd;
33		atomic_load(&__fdtrack_hook)(&event);
34	}
35	return fd;
36}
37
38__attribute__((constructor())) static void __musl_fdtrack_initialize()
39{
40	if (!check_beta_develop_before()) {
41		return;
42	}
43	void* shared_library_handle = NULL;
44	shared_library_handle = dlopen(__fdtrack_hook_shared_lib, RTLD_NOW | RTLD_LOCAL);
45	if (shared_library_handle == NULL) {
46		MUSL_LOGI("FdTrack, Unable to open shared library %s: %s.\n", __fdtrack_hook_shared_lib, dlerror());
47		return;
48	}
49}
50
51#endif
52