support multiple dll path for plugin
[platform/core/dotnet/launcher.git] / NativeLauncher / launcher / dotnet / dotnet_launcher.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
18 #include <dlfcn.h>
19
20 #include <string>
21 #include <fstream>
22 #include <vector>
23
24 #include <fcntl.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <sys/wait.h>
28 #include <unistd.h>
29
30 #include "utils.h"
31 #include "log.h"
32 #include "launcher.h"
33 #include "dotnet_launcher.h"
34
35 #define PLUGIN_PATH "/usr/share/dotnet.tizen/lib/libdotnet_plugin.so"
36
37 namespace tizen {
38 namespace runtime {
39 namespace dotnetcore {
40
41 #if defined (__aarch64__)
42 #define ARCHITECTURE_IDENTIFIER "arm64"
43 const static std::vector<std::string> RID_FALLBACK_GRAPH =
44         {"linux-arm64", "linux", "unix-arm64", "unix", "any", "base"};
45
46 #elif defined (__arm__)
47 #define ARCHITECTURE_IDENTIFIER "arm"
48 const static std::vector<std::string> RID_FALLBACK_GRAPH =
49         {"tizen.4.0.0-armel", "tizen.4.0.0", "tizen-armel", "tizen", "linux-armel", "linux", "unix-armel", "unix", "any", "base"};
50
51 #elif defined (__x86_64__)
52 #define ARCHITECTURE_IDENTIFIER "x64"
53 const static std::vector<std::string> RID_FALLBACK_GRAPH =
54         {"linux-x64", "linux", "unix-x64", "unix", "any", "base"};
55
56 #elif defined (__i386__)
57 #define ARCHITECTURE_IDENTIFIER "x86"
58 const static std::vector<std::string> RID_FALLBACK_GRAPH =
59         {"linux-x86", "linux", "unix-x86", "unix", "any", "base"};
60
61 #else
62 #error "Unknown target"
63 #endif
64
65 static std::string getExtraNativeLibDirs(const std::string& appRoot)
66 {
67         std::string candidate;
68         for (int i = 0; i < RID_FALLBACK_GRAPH.size(); i++) {
69                 if(!candidate.empty()) {
70                         candidate += ":";
71                 }
72                 candidate += concatPath(appRoot, "bin/runtimes/" + RID_FALLBACK_GRAPH[i] + "/native");
73         }
74
75         candidate = candidate + ":" + concatPath(appRoot, "lib/" ARCHITECTURE_IDENTIFIER);
76         if (!strncmp(ARCHITECTURE_IDENTIFIER, "arm64", 5)) {
77                 candidate = candidate + ":" + concatPath(appRoot, "lib/aarch64");
78         }
79
80         return candidate;
81 }
82
83 CoreRuntime::CoreRuntime() :
84         initializeClr(nullptr),
85         executeAssembly(nullptr),
86         shutdown(nullptr),
87         createDelegate(nullptr),
88         __coreclrLib(nullptr),
89         __hostHandle(nullptr),
90         __domainId(-1),
91         preparedFunction(nullptr),
92         launchFunction(nullptr),
93         __pluginLib(nullptr),
94         pluginInitialize(nullptr),
95         pluginPreload(nullptr),
96         pluginSetAppInfo(nullptr),
97         pluginSetCoreclrInfo(nullptr),
98         pluginGetDllPath(nullptr),
99         pluginBeforeExecute(nullptr),
100         pluginFinalize(nullptr),
101         fd(0)
102 {
103 #define __XSTR(x) #x
104 #define __STR(x) __XSTR(x)
105
106 #ifdef DEVICE_API_DIR
107         __deviceAPIDirectory = __STR(DEVICE_API_DIR);
108 #endif
109 #ifdef RUNTIME_DIR
110         __runtimeDirectory = __STR(RUNTIME_DIR);
111 #endif
112 #ifdef NATIVE_LIB_DIR
113         __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
114 #endif
115
116 #undef __STR
117 #undef __XSTR
118
119         // support launcher plugin
120         if (!fileNotExist(PLUGIN_PATH)) {
121                 __pluginLib = dlopen(PLUGIN_PATH, RTLD_NOW | RTLD_LOCAL);
122                 if (__pluginLib) {
123                         pluginInitialize  = (plugin_initialize_ptr)dlsym(__pluginLib, "plugin_initialize");
124                         pluginPreload  = (plugin_preload_ptr)dlsym(__pluginLib, "plugin_preload");
125                         pluginSetAppInfo  = (plugin_set_app_info_ptr)dlsym(__pluginLib, "plugin_set_app_info");
126                         pluginSetCoreclrInfo = (plugin_set_coreclr_info_ptr)dlsym(__pluginLib, "plugin_set_coreclr_info");
127                         pluginGetDllPath  = (plugin_get_dll_path_ptr)dlsym(__pluginLib, "plugin_get_dll_path");
128                         pluginBeforeExecute  = (plugin_before_execute_ptr)dlsym(__pluginLib, "plugin_before_execute");
129                         pluginFinalize  = (plugin_finalize_ptr)dlsym(__pluginLib, "plugin_finalize");
130                 }
131         }
132
133         if (pluginInitialize)
134                 pluginInitialize();
135
136         _DBG("Constructor called!!");
137 }
138
139 CoreRuntime::~CoreRuntime()
140 {
141         dispose();
142 }
143
144 int CoreRuntime::initialize(bool standalone)
145 {
146 #ifdef __arm__
147         // libunwind library is used to unwind stack frame, but libunwind for ARM
148         // does not support ARM vfpv3/NEON registers in DWARF format correctly.
149         // Therefore let's disable stack unwinding using DWARF information
150         // See https://github.com/dotnet/coreclr/issues/6698
151         //
152         // libunwind use following methods to unwind stack frame.
153         // UNW_ARM_METHOD_ALL          0xFF
154         // UNW_ARM_METHOD_DWARF        0x01
155         // UNW_ARM_METHOD_FRAME        0x02
156         // UNW_ARM_METHOD_EXIDX        0x04
157         putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
158 #endif // __arm__
159
160         if (__deviceAPIDirectory.empty()) {
161                 _ERR("Empty Device API Directory");
162                 return 1;
163         } else {
164                 __deviceAPIDirectory = absolutePath(__deviceAPIDirectory);
165         }
166
167         if (__runtimeDirectory.empty()) {
168                 _ERR("Empty Runtime Directory");
169                 return 1;
170         } else {
171                 __runtimeDirectory = absolutePath(__runtimeDirectory);
172         }
173
174         // set Reference API directory
175         __refAPIDirectory = __deviceAPIDirectory + "/ref";
176
177         std::string libCoreclr(concatPath(__runtimeDirectory, "libcoreclr.so"));
178
179         _DBG("libcoreclr : %s", libCoreclr.c_str());
180
181         __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
182         if (__coreclrLib == nullptr) {
183                 char *err = dlerror();
184                 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
185                 return 1;
186         }
187
188 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
189         do { \
190                 variable = (type)dlsym(__coreclrLib, name); \
191                 if (variable == nullptr) { \
192                         _ERR(name " is not found in the libcoreclr.so"); \
193                         return 1; \
194                 } \
195         } while (0)
196
197         CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
198         CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
199         CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
200         CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
201
202 #undef CORELIB_RETURN_IF_NOSYM
203
204         _DBG("libcoreclr dlopen and dlsym success");
205
206         if (!standalone && pluginPreload)
207                 pluginPreload();
208
209         fd = open("/proc/self", O_DIRECTORY);
210         std::string path_tmp = std::string("/proc/self/fd/") + std::to_string(fd);
211
212         std::string appRoot = path_tmp;
213         std::string appBin = concatPath(appRoot, "bin");
214         std::string appLib = concatPath(appRoot, "lib");
215         std::string probePath = appBin + ":" + appLib;
216
217         std::string tpa;
218         std::vector<std::string> searchDirectories;
219         searchDirectories.push_back(__runtimeDirectory);
220         searchDirectories.push_back(__deviceAPIDirectory);
221         searchDirectories.push_back(__refAPIDirectory);
222
223         if (pluginGetDllPath) {
224                 std::string pluginPath = pluginGetDllPath();
225                 if (!pluginPath.empty()) {
226                         splitPath(pluginPath, searchDirectories);
227                 }
228         }
229
230         assembliesInDirectory(searchDirectories, tpa);
231
232         std::string nativeLibPath;
233         nativeLibPath = getExtraNativeLibDirs(appRoot) + ":" + appBin + ":" + appLib + ":" + __nativeLibDirectory;
234
235         std::string appName = std::string("dotnet-launcher-") + std::to_string(getpid());
236         if (!initializeCoreClr(appName.c_str(), probePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
237                 _ERR("Failed to initialize coreclr");
238                 return 1;
239         }
240
241         return 0;
242 }
243
244 bool CoreRuntime::initializeCoreClr(const char* appId,
245                                                                          const char* assemblyProbePaths,
246                                                                          const char* pinvokeProbePaths,
247                                                                          const char* tpaList)
248 {
249         const char *propertyKeys[] = {
250                 "TRUSTED_PLATFORM_ASSEMBLIES",
251                 "APP_PATHS",
252                 "APP_NI_PATHS",
253                 "NATIVE_DLL_SEARCH_DIRECTORIES",
254                 "AppDomainCompatSwitch"
255         };
256
257         const char *propertyValues[] = {
258                 tpaList,
259                 assemblyProbePaths,
260                 assemblyProbePaths,
261                 pinvokeProbePaths,
262                 "UseLatestBehaviorWhenTFMNotSpecified"
263         };
264
265         std::string selfPath = readSelfPath();
266
267         int st = initializeClr(selfPath.c_str(),
268                                                         appId,
269                                                         sizeof(propertyKeys) / sizeof(propertyKeys[0]),
270                                                         propertyKeys,
271                                                         propertyValues,
272                                                         &__hostHandle,
273                                                         &__domainId);
274
275         if (st < 0) {
276                 _ERR("initialize core clr fail! (0x%08x)", st);
277                 return false;
278         }
279
280         if (pluginSetCoreclrInfo)
281                 pluginSetCoreclrInfo(__hostHandle, __domainId);
282
283         _DBG("Initialize core clr success");
284         return true;
285 }
286
287 void CoreRuntime::dispose()
288 {
289         if (__hostHandle != nullptr) {
290                 int st = shutdown(__hostHandle, __domainId);
291                 if (st < 0)
292                         _ERR("shutdown core clr fail! (0x%08x)", st);
293         }
294
295         if (dlclose(__coreclrLib) != 0)
296                 _ERR("libcoreclr.so close failed");
297
298         __coreclrLib = nullptr;
299
300         if (pluginFinalize)
301                 pluginFinalize();
302
303         if (__pluginLib != nullptr) {
304                 if (dlclose(__pluginLib) != 0)
305                         _ERR("libdotnet_plugin.so close failed");
306
307                 __pluginLib = nullptr;
308                 pluginInitialize = nullptr;
309                 pluginPreload = nullptr;
310                 pluginSetAppInfo = nullptr;
311                 pluginSetCoreclrInfo = nullptr;
312                 pluginGetDllPath = nullptr;
313                 pluginBeforeExecute = nullptr;
314                 pluginFinalize = nullptr;
315         }
316
317         _DBG("Dotnet runtime disposed");
318 }
319
320 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
321 {
322         if (runLoggingThread() < 0) {
323                 _ERR("Failed to create logging thread");
324         }
325
326         if (path == nullptr) {
327                 _ERR("executable path is null");
328                 return 1;
329         }
330
331         if (fileNotExist(path)) {
332                 _ERR("File not exist : %s", path);
333                 return 1;
334         }
335
336         if (pluginSetAppInfo)
337                 pluginSetAppInfo(appId, path);
338
339         int fd2 = open(root, O_DIRECTORY);
340         dup3(fd2, fd, O_CLOEXEC);
341         close(fd2);
342
343         if (pluginBeforeExecute)
344                 pluginBeforeExecute();
345
346         if (runLoggingThread() < 0) {
347                 _ERR("Failed to create logging thread");
348         }
349
350         unsigned int ret = 0;
351         int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
352         if (st < 0)
353                 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
354         return ret;
355 }
356
357 }  // namespace dotnetcore
358 }  // namespace runtime
359 }  // namespace tizen