Sometimes a process terminates abnormally due to a signal generated during coreclr_sh...
[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.5.0.0-armel", "tizen.5.0.0", "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         {"tizen.5.0.0-x86", "tizen.5.0.0", "tizen.4.0.0-x86", "tizen.4.0.0", "tizen-x86", "tizen", "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 #define _unused(x) ((void)(x))
125
126 struct sigaction sig_abrt_new;
127 struct sigaction sig_abrt_old;
128
129 static bool checkOnSigabrt = false;
130 static bool checkOnTerminate = false;
131
132 static void onSigabrt(int signum)
133 {
134         // use unused variable to avoid build warning
135         ssize_t ret = write(STDERR_FILENO, "onSigabrt called\n", 17);
136
137         if (checkOnTerminate) {
138                 ret = write(STDERR_FILENO, "onSigabrt called while terminate. go to exit\n", 45);
139                 _unused(ret);
140                 exit(0);
141         }
142
143         if (checkOnSigabrt) {
144                 ret = write(STDERR_FILENO, "onSigabrt called again. go to exit\n", 35);
145                 _unused(ret);
146                 exit(0);
147         }
148
149         if (hasException()) {
150                 ret = write(STDERR_FILENO, "******************************************************\n", 55);
151                 ret = write(STDERR_FILENO, "Unhandled exception is occured. check application code\n", 55);
152                 ret = write(STDERR_FILENO, "******************************************************\n", 55);
153         }
154
155         checkOnSigabrt = true;
156         if (sigaction(SIGABRT, &sig_abrt_old, NULL) == 0) {
157                 if (raise(signum) < 0) {
158                         ret = write(STDERR_FILENO, "Fail to raise SIGABRT\n", 22);
159                 }
160         } else {
161                 ret = write(STDERR_FILENO, "Fail to set original SIGABRT handler\n", 37);
162         }
163         _unused(ret);
164 }
165
166 static void registerSigHandler()
167 {
168         sig_abrt_new.sa_handler = onSigabrt;
169         if (sigemptyset(&sig_abrt_new.sa_mask) != 0) {
170                 _ERR("Fail to sigemptyset");
171         }
172
173         if (sigaction(SIGABRT, &sig_abrt_new, &sig_abrt_old) < 0) {
174                 _ERR("Fail to add sig handler");
175         }
176 }
177
178 static bool storage_cb(int id, storage_type_e type, storage_state_e state, const char *path, void *user_data)
179 {
180         int* tmp = (int*)user_data;
181         if (type == STORAGE_TYPE_INTERNAL)
182         {
183                 *tmp = id;
184                 return false;
185         }
186
187         return true;
188 }
189
190 static void initEnvForSpecialFolder()
191 {
192         int storageId;
193         int error;
194         char *path = NULL;
195
196         error = storage_foreach_device_supported(storage_cb, &storageId);
197         if (error != STORAGE_ERROR_NONE) {
198                 return;
199         }
200
201         error = storage_get_directory(storageId, STORAGE_DIRECTORY_IMAGES, &path);
202         if (error == STORAGE_ERROR_NONE && path != NULL) {
203                 setenv("XDG_PICTURES_DIR", const_cast<char *>(path), 1);
204                 free(path);
205                 path = NULL;
206         }
207
208         error = storage_get_directory(storageId, STORAGE_DIRECTORY_MUSIC, &path);
209         if (error == STORAGE_ERROR_NONE && path != NULL) {
210                 setenv("XDG_MUSIC_DIR", const_cast<char *>(path), 1);
211                 free(path);
212                 path = NULL;
213         }
214
215         error = storage_get_directory(storageId, STORAGE_DIRECTORY_VIDEOS, &path);
216         if (error == STORAGE_ERROR_NONE && path != NULL) {
217                 setenv("XDG_VIDEOS_DIR", const_cast<char *>(path), 1);
218                 free(path);
219                 path = NULL;
220         }
221 }
222
223 CoreRuntime::CoreRuntime(const char* mode) :
224         initializeClr(nullptr),
225         executeAssembly(nullptr),
226         shutdown(nullptr),
227         createDelegate(nullptr),
228         setEnvironmentVariable(nullptr),
229         multiByteToWideChar(nullptr),
230         __coreclrLib(nullptr),
231         __hostHandle(nullptr),
232         __domainId(-1),
233         fd(0),
234         __initialized(false)
235 {
236         _INFO("Constructor called!!");
237
238         // plugin initialize should be called before start loader mainloop.
239         // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
240         // When attaching to a secure zone, if there is a created thread, it will failed.
241         // So, plugin initialize should be called before mainloop start.
242         if (initializePluginManager(mode) < 0) {
243                 _ERR("Failed to initialize PluginManager");
244         }
245
246         if (pluginHasLogControl()) {
247                 __enableLogManager = false;
248         } else {
249                 __enableLogManager = true;
250         }
251 }
252
253 CoreRuntime::~CoreRuntime()
254 {
255         dispose();
256 }
257
258 int CoreRuntime::initialize(bool standalone)
259 {
260 #define __XSTR(x) #x
261 #define __STR(x) __XSTR(x)
262
263 #ifdef NATIVE_LIB_DIR
264         __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
265 #endif
266
267 #undef __STR
268 #undef __XSTR
269
270 #ifdef __arm__
271         // libunwind library is used to unwind stack frame, but libunwind for ARM
272         // does not support ARM vfpv3/NEON registers in DWARF format correctly.
273         // Therefore let's disable stack unwinding using DWARF information
274         // See https://github.com/dotnet/coreclr/issues/6698
275         //
276         // libunwind use following methods to unwind stack frame.
277         // UNW_ARM_METHOD_ALL          0xFF
278         // UNW_ARM_METHOD_DWARF        0x01
279         // UNW_ARM_METHOD_FRAME        0x02
280         // UNW_ARM_METHOD_EXIDX        0x04
281         putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
282 #endif // __arm__
283
284         // Disable debug pipes and semaphores creation in case of non-standlone mode
285         if (!standalone)
286                 putenv(const_cast<char *>("COMPlus_EnableDiagnostics=0"));
287
288         // read string from external file and set them to environment value.
289         setEnvFromFile();
290
291         // Set environment for System.Environment.SpecialFolder
292         initEnvForSpecialFolder();
293
294         if (initializePathManager(std::string(), std::string(), std::string()) < 0) {
295                 _ERR("Failed to initialize PathManager");
296                 return -1;
297         }
298
299         if (__enableLogManager) {
300                 if (initializeLogManager() < 0) {
301                         _ERR("Failed to initnialize LogManager");
302                         return -1;
303                 }
304
305                 if (redirectFD() < 0) {
306                         _ERR("Failed to redirect FD");
307                         return -1;
308                 }
309
310                 if (runLoggingThread() < 0) {
311                         _ERR("Failed to create and run logging thread to redicrect log");
312                         return -1;
313                 }
314         }
315
316         std::string libCoreclr(concatPath(getRuntimeDir(), "libcoreclr.so"));
317
318         __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
319         if (__coreclrLib == nullptr) {
320                 char *err = dlerror();
321                 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
322                 return -1;
323         }
324
325 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
326         do { \
327                 variable = (type)dlsym(__coreclrLib, name); \
328                 if (variable == nullptr) { \
329                         _ERR(name " is not found in the libcoreclr.so"); \
330                         return -1; \
331                 } \
332         } while (0)
333
334         CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
335         CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
336         CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
337         CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
338         CORELIB_RETURN_IF_NOSYM(set_environment_variable_ptr, setEnvironmentVariable, "SetEnvironmentVariableW");
339         CORELIB_RETURN_IF_NOSYM(multi_byte_to_wide_char_ptr, multiByteToWideChar, "MultiByteToWideChar");
340
341 #undef CORELIB_RETURN_IF_NOSYM
342
343         _INFO("libcoreclr dlopen and dlsym success");
344
345         if (!standalone)
346                 pluginPreload();
347
348         fd = open("/proc/self", O_DIRECTORY);
349         std::string appRoot = std::string("/proc/self/fd/") + std::to_string(fd);
350         std::string appBin = concatPath(appRoot, "bin");
351         std::string appLib = concatPath(appRoot, "lib");
352         std::string probePath = appBin + ":" + appLib;
353         std::string tpa = getTPA();
354         std::string nativeLibPath = getExtraNativeLibDirs(appRoot) + ":" + appBin + ":" + appLib + ":" + __nativeLibDirectory;
355         std::string appName = std::string("dotnet-launcher-") + std::to_string(getpid());
356
357         if (!initializeCoreClr(appName.c_str(), probePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
358                 _ERR("Failed to initialize coreclr");
359                 return -1;
360         }
361
362         __initialized = true;
363
364         _INFO("CoreRuntime initialize success");
365
366         return 0;
367 }
368
369 bool CoreRuntime::initializeCoreClr(const char* appId,
370                                                                          const char* assemblyProbePaths,
371                                                                          const char* pinvokeProbePaths,
372                                                                          const char* tpaList)
373 {
374         const char *propertyKeys[] = {
375                 "TRUSTED_PLATFORM_ASSEMBLIES",
376                 "APP_PATHS",
377                 "APP_NI_PATHS",
378                 "NATIVE_DLL_SEARCH_DIRECTORIES",
379                 "AppDomainCompatSwitch"
380         };
381
382         const char *propertyValues[] = {
383                 tpaList,
384                 assemblyProbePaths,
385                 assemblyProbePaths,
386                 pinvokeProbePaths,
387                 "UseLatestBehaviorWhenTFMNotSpecified"
388         };
389
390         std::string selfPath = readSelfPath();
391
392         int st = initializeClr(selfPath.c_str(),
393                                                         appId,
394                                                         sizeof(propertyKeys) / sizeof(propertyKeys[0]),
395                                                         propertyKeys,
396                                                         propertyValues,
397                                                         &__hostHandle,
398                                                         &__domainId);
399
400         if (st < 0) {
401                 _ERR("initialize core clr fail! (0x%08x)", st);
402                 return false;
403         }
404
405         pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
406
407         _INFO("Initialize core clr success");
408         return true;
409 }
410
411 void CoreRuntime::dispose()
412 {
413         // call plugin finalize function to notify finalize to plugin
414         // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
415         pluginFinalize();
416
417         // ignore the signal generated by an exception that occurred during shutdown
418         checkOnTerminate = true;
419
420         if (__hostHandle != nullptr) {
421                 int st = shutdown(__hostHandle, __domainId);
422                 if (st < 0)
423                         _ERR("shutdown core clr fail! (0x%08x)", st);
424                 __hostHandle = nullptr;
425         }
426
427         if (__coreclrLib != nullptr) {
428                 if (dlclose(__coreclrLib) != 0) {
429                         _ERR("libcoreclr.so close failed");
430                 }
431
432                 __coreclrLib = nullptr;
433         }
434
435         finalizePluginManager();
436         finalizePathManager();
437
438         __envList.clear();
439
440         _INFO("Dotnet runtime disposed");
441 }
442
443 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
444 {
445         if (!__initialized) {
446                 _ERR("Runtime is not initialized");
447                 return -1;
448         }
449
450         if (path == nullptr) {
451                 _ERR("executable path is null");
452                 return -1;
453         }
454
455         if (!isFileExist(path)) {
456                 _ERR("File not exist : %s", path);
457                 return -1;
458         }
459
460         if (__enableLogManager) {
461                 // launchpad override stdout and stderr to journalctl before launch application.
462                 // we have to re-override that to input pipe for logging thread.
463                 if (redirectFD() < 0) {
464                         _ERR("Failed to redirect FD");
465                         return -1;
466                 }
467
468                 registerSigHandler();
469         }
470
471         pluginSetAppInfo(appId, path);
472
473         int fd2 = open(root, O_DIRECTORY);
474         dup3(fd2, fd, O_CLOEXEC);
475         if (fd2 >= 0)
476                 close(fd2);
477
478         // set application data path to coreclr environment.
479         // application data path can be changed by owner. So, we have to set data path just before launching.
480         char* localDataPath = app_get_data_path();
481         if (localDataPath != nullptr) {
482                 char16_t envval[PATH_MAX] = {0};
483                 int copied = multiByteToWideChar(0 /* CP_ACP */, 0, localDataPath, -1, envval, PATH_MAX);
484                 if (copied >= PATH_MAX) {
485                         _ERR("Data Path is bigger than PATH_MAX");
486                 }
487
488                 if (!setEnvironmentVariable(u"XDG_DATA_HOME", envval)) {
489                         _ERR("Failed to set XDG_DATA_HOME");
490                 }
491         }
492
493         pluginBeforeExecute();
494
495         _INFO("execute assembly : %s", path);
496
497         unsigned int ret = 0;
498         int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
499         if (st < 0)
500                 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
501         return ret;
502 }
503
504 }  // namespace dotnetcore
505 }  // namespace runtime
506 }  // namespace tizen