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