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