TAC support for memory optimization
[platform/core/dotnet/launcher.git] / NativeLauncher / launcher / 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 static int injectLibrary(const char path[])
25 {
26         typedef int inject_func();
27
28         int res = -1;
29         void *lib = nullptr;
30         inject_func *inject = nullptr;
31         const char *inject_sym = "dotnet_launcher_inject";
32
33         _INFO("Inject %s library", path);
34
35         // Current implementation of heaptrack CLR profiler requires RTLD_GLOBAL
36         lib = dlopen(path, RTLD_NOW | RTLD_GLOBAL);
37         if (lib == nullptr) {
38                 _ERR("%s", dlerror());
39                 return res;
40         }
41
42         inject = reinterpret_cast<inject_func*>(dlsym(lib, inject_sym));
43         if (inject == nullptr) {
44                 _ERR("%s is not found in the %s", inject_sym, path);
45                 return res;
46         }
47
48         res = inject();
49         return res;
50 }
51
52 int checkInjection()
53 {
54         int res = -1;
55         char *env = nullptr;
56         char* injectableLibs = nullptr;
57         const char *delim = ", ";
58         char *lib = nullptr;
59         char *saveptr = nullptr;
60
61         env = getenv("DOTNET_LAUNCHER_INJECT");
62         if (env == nullptr) {
63                 res = 0;
64                 return res;
65         }
66
67         _INFO("##### Perform injection #########");
68
69         injectableLibs = strdup(env);
70         if (injectableLibs == nullptr) {
71                 _ERR("Fail to allocate memory for injectable library paths\n");
72                 return res;
73         }
74
75         res = 0;
76         lib = strtok_r(injectableLibs, delim, &saveptr);
77         for(; lib != nullptr; lib = strtok_r(nullptr, delim, &saveptr)) {
78                 if (injectLibrary(lib) != 0) {
79                         res = -1;
80                         break;
81                 }
82         }
83
84         if (res == 0) {
85                 _INFO("##### Injection finished #########");
86         } else {
87                 _INFO("##### Injection failed #########");
88         }
89
90         free(injectableLibs);
91         return res;
92 }