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