884a5a2e19a0d3084aa4c44e9194a1720df58308
[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         if (pluginHasLogControl()) {
141                 __enableLogManager = false;
142         } else {
143                 __enableLogManager = true;
144         }
145 }
146
147 CoreRuntime::~CoreRuntime()
148 {
149         dispose();
150 }
151
152 int CoreRuntime::initialize(bool standalone)
153 {
154 #define __XSTR(x) #x
155 #define __STR(x) __XSTR(x)
156
157 #ifdef NATIVE_LIB_DIR
158         __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
159 #endif
160
161 #undef __STR
162 #undef __XSTR
163
164 #ifdef __arm__
165         // libunwind library is used to unwind stack frame, but libunwind for ARM
166         // does not support ARM vfpv3/NEON registers in DWARF format correctly.
167         // Therefore let's disable stack unwinding using DWARF information
168         // See https://github.com/dotnet/coreclr/issues/6698
169         //
170         // libunwind use following methods to unwind stack frame.
171         // UNW_ARM_METHOD_ALL          0xFF
172         // UNW_ARM_METHOD_DWARF        0x01
173         // UNW_ARM_METHOD_FRAME        0x02
174         // UNW_ARM_METHOD_EXIDX        0x04
175         putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
176 #endif // __arm__
177
178         // read string from external file and set them to environment value.
179         setEnvFromFile();
180
181         if (initializePathManager(std::string(), std::string(), std::string()) < 0) {
182                 _ERR("Failed to initialize PathManager");
183                 return -1;
184         }
185
186         if (__enableLogManager) {
187                 if (initializeLogManager() < 0) {
188                         _ERR("Failed to initnialize LogManager");
189                         return -1;
190                 }
191
192                 if (redirectFD() < 0) {
193                         _ERR("Failed to redirect FD");
194                         return -1;
195                 }
196
197                 if (runLoggingThread() < 0) {
198                         _ERR("Failed to create and run logging thread to redicrect log");
199                         return -1;
200                 }
201         }
202
203         std::string libCoreclr(concatPath(getRuntimeDir(), "libcoreclr.so"));
204
205         __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
206         if (__coreclrLib == nullptr) {
207                 char *err = dlerror();
208                 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
209                 return -1;
210         }
211
212 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
213         do { \
214                 variable = (type)dlsym(__coreclrLib, name); \
215                 if (variable == nullptr) { \
216                         _ERR(name " is not found in the libcoreclr.so"); \
217                         return -1; \
218                 } \
219         } while (0)
220
221         CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
222         CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
223         CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
224         CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
225
226 #undef CORELIB_RETURN_IF_NOSYM
227
228         _INFO("libcoreclr dlopen and dlsym success");
229
230         if (!standalone)
231                 pluginPreload();
232
233         fd = open("/proc/self", O_DIRECTORY);
234         std::string appRoot = std::string("/proc/self/fd/") + std::to_string(fd);
235         std::string appBin = concatPath(appRoot, "bin");
236         std::string appLib = concatPath(appRoot, "lib");
237         std::string probePath = appBin + ":" + appLib;
238         std::string tpa = getTPA();
239         std::string nativeLibPath = getExtraNativeLibDirs(appRoot) + ":" + appBin + ":" + appLib + ":" + __nativeLibDirectory;
240         std::string appName = std::string("dotnet-launcher-") + std::to_string(getpid());
241
242         if (!initializeCoreClr(appName.c_str(), probePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
243                 _ERR("Failed to initialize coreclr");
244                 return -1;
245         }
246
247         __initialized = true;
248
249         _INFO("CoreRuntime initialize success");
250
251         return 0;
252 }
253
254 bool CoreRuntime::initializeCoreClr(const char* appId,
255                                                                          const char* assemblyProbePaths,
256                                                                          const char* pinvokeProbePaths,
257                                                                          const char* tpaList)
258 {
259         const char *propertyKeys[] = {
260                 "TRUSTED_PLATFORM_ASSEMBLIES",
261                 "APP_PATHS",
262                 "APP_NI_PATHS",
263                 "NATIVE_DLL_SEARCH_DIRECTORIES",
264                 "AppDomainCompatSwitch"
265         };
266
267         const char *propertyValues[] = {
268                 tpaList,
269                 assemblyProbePaths,
270                 assemblyProbePaths,
271                 pinvokeProbePaths,
272                 "UseLatestBehaviorWhenTFMNotSpecified"
273         };
274
275         std::string selfPath = readSelfPath();
276
277         int st = initializeClr(selfPath.c_str(),
278                                                         appId,
279                                                         sizeof(propertyKeys) / sizeof(propertyKeys[0]),
280                                                         propertyKeys,
281                                                         propertyValues,
282                                                         &__hostHandle,
283                                                         &__domainId);
284
285         if (st < 0) {
286                 _ERR("initialize core clr fail! (0x%08x)", st);
287                 return false;
288         }
289
290         pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
291
292         _INFO("Initialize core clr success");
293         return true;
294 }
295
296 void CoreRuntime::dispose()
297 {
298         if (__hostHandle != nullptr) {
299                 int st = shutdown(__hostHandle, __domainId);
300                 if (st < 0)
301                         _ERR("shutdown core clr fail! (0x%08x)", st);
302                 __hostHandle = nullptr;
303         }
304
305         if (__coreclrLib != nullptr) {
306                 if (dlclose(__coreclrLib) != 0) {
307                         _ERR("libcoreclr.so close failed");
308                 }
309
310                 __coreclrLib = nullptr;
311         }
312
313         finalizePluginManager();
314         finalizePathManager();
315
316         __envList.clear();
317
318         _INFO("Dotnet runtime disposed");
319 }
320
321 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
322 {
323         if (!__initialized) {
324                 _ERR("Runtime is not initialized");
325                 return -1;
326         }
327
328         if (path == nullptr) {
329                 _ERR("executable path is null");
330                 return -1;
331         }
332
333         if (!isFileExist(path)) {
334                 _ERR("File not exist : %s", path);
335                 return -1;
336         }
337
338         if (__enableLogManager) {
339                 // launchpad override stdout and stderr to journalctl before launch application.
340                 // we have to re-override that to input pipe for logging thread.
341                 if (redirectFD() < 0) {
342                         _ERR("Failed to redirect FD");
343                         return -1;
344                 }
345         }
346
347         pluginSetAppInfo(appId, path);
348
349         int fd2 = open(root, O_DIRECTORY);
350         dup3(fd2, fd, O_CLOEXEC);
351         if (fd2 >= 0)
352                 close(fd2);
353
354         pluginBeforeExecute();
355
356         _INFO("execute assembly : %s", path);
357
358         unsigned int ret = 0;
359         int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
360         if (st < 0)
361                 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
362         return ret;
363 }
364
365 }  // namespace dotnetcore
366 }  // namespace runtime
367 }  // namespace tizen