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