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