Introduce preloadThread for launcher (#451)
[platform/core/dotnet/launcher.git] / NativeLauncher / launcher / lib / injection.cc
1 /*
2  * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
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 "log.h"
18
19 #include <cstdlib>
20 #include <cstring>
21
22 #include <dlfcn.h>
23
24 #define HT_PATH "/home/owner/share/tmp/sdk_tools/heaptrack/"
25 #define HT_LIB_PATH HT_PATH "libprofiler.so"
26 #define HT_INJECTION_LIB_PATH HT_PATH "libheaptrack_inject.so"
27
28 static int injectLibrary(const char path[])
29 {
30         typedef int inject_func();
31
32         int res = -1;
33         void *lib = nullptr;
34         inject_func *inject = nullptr;
35         const char *inject_sym = "dotnet_launcher_inject";
36
37         _INFO("Inject %s library", path);
38
39         // Current implementation of heaptrack CLR profiler requires RTLD_GLOBAL
40         lib = dlopen(path, RTLD_NOW | RTLD_GLOBAL);
41         if (lib == nullptr) {
42                 _ERR("%s", dlerror());
43                 return res;
44         }
45
46         inject = reinterpret_cast<inject_func*>(dlsym(lib, inject_sym));
47         if (inject == nullptr) {
48                 _ERR("%s is not found in the %s", inject_sym, path);
49                 return res;
50         }
51
52         res = inject();
53         return res;
54 }
55
56 int checkInjection()
57 {
58         char *env = nullptr;
59
60         env = getenv("CORECLR_PROFILER_PATH");
61         if (env == nullptr) {
62                 return 0;
63         }
64
65         // At the moment, this mechanism is used only when the Memory Profiler is started.
66         if (strcmp(env, HT_LIB_PATH) != 0) {
67                 return 0;
68         }
69
70         _INFO("##### Perform injection #########");
71
72         if (injectLibrary(HT_INJECTION_LIB_PATH) != 0) {
73                 _INFO("##### Injection failed #########");
74                 return -1;
75         }
76
77         _INFO("##### Injection finished #########");
78         return 0;
79 }