Support hydra mode
[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 void CoreRuntime::preloadTypes()
225 {
226         const static std::string initDllPath = "/usr/share/dotnet.tizen/framework/Tizen.Init.dll";
227         if (!isFileExist(initDllPath)) {
228                 _ERR("Failed to locate Tizen.Init.dll");
229                 return;
230         }
231
232         typedef void (*InitDelegate)();
233         InitDelegate initDelegate;
234
235         int ret = createDelegate(__hostHandle,
236                 __domainId,
237                 "Tizen.Init",
238                 "Tizen.Init.TypeLoader",
239                 "PreloadTypes",
240                 (void**)&initDelegate);
241
242         if (ret < 0) {
243                 _ERR("Failed to create delegate for PreloadTypes (0x%08x)", ret);
244         } else {
245                 initDelegate();
246         }
247 }
248
249 CoreRuntime::CoreRuntime(const char* mode) :
250         initializeClr(nullptr),
251         executeAssembly(nullptr),
252         shutdown(nullptr),
253         createDelegate(nullptr),
254         setEnvironmentVariable(nullptr),
255         __coreclrLib(nullptr),
256         __hostHandle(nullptr),
257         __domainId(-1),
258         fd(0),
259         __initialized(false),
260         __isProfileMode(false)
261 {
262         _INFO("Constructor called!!");
263
264         char *env = nullptr;
265         env = getenv("CORECLR_ENABLE_PROFILING");
266         if (env != nullptr && !strcmp(env, "1")) {
267                 _INFO("profiling mode on");
268                 __isProfileMode = true;
269         }
270
271         // plugin initialize should be called before start loader mainloop.
272         // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
273         // When attaching to a secure zone, if there is a created thread, it will failed.
274         // So, plugin initialize should be called before mainloop start.
275         if (initializePluginManager(mode) < 0) {
276                 _ERR("Failed to initialize PluginManager");
277         }
278
279         if (pluginHasLogControl()) {
280                 __enableLogManager = false;
281         } else {
282                 __enableLogManager = true;
283         }
284 }
285
286 CoreRuntime::~CoreRuntime()
287 {
288         // workaround : to prevent crash while process terminate on profiling mode,
289         //              kill process immediately.
290         // see https://github.com/dotnet/coreclr/issues/26687
291         if (__isProfileMode) {
292                 _INFO("shutdown process immediately.");
293                 _exit(0);
294         }
295
296         dispose();
297 }
298
299 int CoreRuntime::preinitialize(bool standalone)
300 {
301         // checkInjection checks dotnet-launcher run mode
302         // At the moment, this mechanism is used only when the Memory Profiler is started.
303         int res = checkInjection();
304         if (res != 0) {
305                 _ERR("Failed to initnialize Memory Profiler");
306                 return -1;
307         }
308 #define __XSTR(x) #x
309 #define __STR(x) __XSTR(x)
310
311 #ifdef NATIVE_LIB_DIR
312         __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
313 #endif
314
315 #undef __STR
316 #undef __XSTR
317
318 #ifdef __arm__
319         // libunwind library is used to unwind stack frame, but libunwind for ARM
320         // does not support ARM vfpv3/NEON registers in DWARF format correctly.
321         // Therefore let's disable stack unwinding using DWARF information
322         // See https://github.com/dotnet/coreclr/issues/6698
323         //
324         // libunwind use following methods to unwind stack frame.
325         // UNW_ARM_METHOD_ALL          0xFF
326         // UNW_ARM_METHOD_DWARF        0x01
327         // UNW_ARM_METHOD_FRAME        0x02
328         // UNW_ARM_METHOD_EXIDX        0x04
329         putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
330 #endif // __arm__
331
332         // Disable debug pipes and semaphores creation in case of non-standlone mode
333         if (!standalone)
334                 putenv(const_cast<char *>("COMPlus_EnableDiagnostics=0"));
335
336         // Write Debug.WriteLine to stderr
337         putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
338
339 #ifdef USE_DEFAULT_BASE_ADDR
340         putenv(const_cast<char *>("COMPlus_UseDefaultBaseAddr=1"));
341 #endif // USE_DEFAULT_BASE_ADDR
342
343         // read string from external file and set them to environment value.
344         setEnvFromFile();
345
346         // Set environment for System.Environment.SpecialFolder
347         initEnvForSpecialFolder();
348
349         if (initializePathManager(std::string(), std::string(), std::string()) < 0) {
350                 _ERR("Failed to initialize PathManager");
351                 return -1;
352         }
353
354         std::string libCoreclr(concatPath(getRuntimeDir(), "libcoreclr.so"));
355
356         __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
357         if (__coreclrLib == nullptr) {
358                 char *err = dlerror();
359                 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
360                 if (access(libCoreclr.c_str(), R_OK) == -1)
361                         _ERR("access '%s': %s\n", libCoreclr.c_str(), strerror(errno));
362                 return -1;
363         }
364
365 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
366         do { \
367                 variable = (type)dlsym(__coreclrLib, name); \
368                 if (variable == nullptr) { \
369                         _ERR(name " is not found in the libcoreclr.so"); \
370                         return -1; \
371                 } \
372         } while (0)
373
374         CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
375         CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
376         CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
377         CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
378
379 #undef CORELIB_RETURN_IF_NOSYM
380
381         _INFO("libcoreclr dlopen and dlsym success");
382
383         return 0;
384 }
385
386 int CoreRuntime::initialize(bool standalone)
387 {
388 #define __XSTR(x) #x
389 #define __STR(x) __XSTR(x)
390
391 #ifdef NATIVE_LIB_DIR
392         __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
393 #endif
394
395 #undef __STR
396 #undef __XSTR
397
398         if (__enableLogManager) {
399                 if (initializeLogManager() < 0) {
400                         _ERR("Failed to initnialize LogManager");
401                         return -1;
402                 }
403
404                 if (redirectFD() < 0) {
405                         _ERR("Failed to redirect FD");
406                         return -1;
407                 }
408
409                 if (runLoggingThread() < 0) {
410                         _ERR("Failed to create and run logging thread to redicrect log");
411                         return -1;
412                 }
413         }
414
415         if (!standalone)
416                 pluginPreload();
417
418         fd = open("/proc/self", O_DIRECTORY);
419         std::string appRoot = std::string("/proc/self/fd/") + std::to_string(fd);
420         std::string appBin = concatPath(appRoot, "bin");
421         std::string appLib = concatPath(appRoot, "lib");
422         std::string appTac = concatPath(appBin, TAC_SYMLINK_SUB_DIR);
423         std::string probePath = appBin + ":" + appLib + ":" + appTac;
424         std::string NIprobePath = concatPath(appBin, APP_NI_SUB_DIR) + ":" + concatPath(appLib, APP_NI_SUB_DIR) + ":" + appTac;
425         std::string tpa = getTPA();
426         std::string runtimeDir = getRuntimeDir();
427         std::string nativeLibPath = getExtraNativeLibDirs(appRoot) + ":" + appBin + ":" + appLib + ":" + __nativeLibDirectory + ":" + runtimeDir;
428         std::string appName = std::string("dotnet-launcher-") + std::to_string(getpid());
429
430         if (!initializeCoreClr(appName.c_str(), probePath.c_str(), NIprobePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
431                 _ERR("Failed to initialize coreclr");
432                 return -1;
433         }
434
435         int st = createDelegate(__hostHandle, __domainId, "Dotnet.Launcher", "Dotnet.Launcher.Environment", "SetEnvironmentVariable", (void**)&setEnvironmentVariable);
436         if (st < 0 || setEnvironmentVariable == nullptr) {
437                 _ERR("Create delegate for Dotnet.Launcher.dll -> Dotnet.Launcher.Environment -> SetEnvironmentVariable failed (0x%08x)", st);
438                 return -1;
439         }
440
441         __initialized = true;
442
443         if (!standalone)
444         {
445                 preloadTypes();         // Preload common managed code
446         }
447
448         _INFO("CoreRuntime initialize success");
449
450         return 0;
451 }
452
453 bool CoreRuntime::initializeCoreClr(const char* appId,
454                                                                          const char* assemblyProbePaths,
455                                                                          const char* NIProbePaths,
456                                                                          const char* pinvokeProbePaths,
457                                                                          const char* tpaList)
458 {
459         const char *propertyKeys[] = {
460                 "TRUSTED_PLATFORM_ASSEMBLIES",
461                 "APP_PATHS",
462                 "APP_NI_PATHS",
463                 "NATIVE_DLL_SEARCH_DIRECTORIES",
464                 "AppDomainCompatSwitch"
465         };
466
467         const char *propertyValues[] = {
468                 tpaList,
469                 assemblyProbePaths,
470                 NIProbePaths,
471                 pinvokeProbePaths,
472                 "UseLatestBehaviorWhenTFMNotSpecified"
473         };
474
475         std::string selfPath = readSelfPath();
476
477         int st = initializeClr(selfPath.c_str(),
478                                                         appId,
479                                                         sizeof(propertyKeys) / sizeof(propertyKeys[0]),
480                                                         propertyKeys,
481                                                         propertyValues,
482                                                         &__hostHandle,
483                                                         &__domainId);
484
485         if (st < 0) {
486                 _ERR("initialize core clr fail! (0x%08x)", st);
487                 return false;
488         }
489
490         pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
491
492         _INFO("Initialize core clr success");
493         return true;
494 }
495
496 void CoreRuntime::dispose()
497 {
498         // call plugin finalize function to notify finalize to plugin
499         // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
500         pluginFinalize();
501
502         // ignore the signal generated by an exception that occurred during shutdown
503         checkOnTerminate = true;
504
505         if (__hostHandle != nullptr) {
506                 int st = shutdown(__hostHandle, __domainId);
507                 if (st < 0)
508                         _ERR("shutdown core clr fail! (0x%08x)", st);
509                 __hostHandle = nullptr;
510         }
511
512         if (__coreclrLib != nullptr) {
513                 if (dlclose(__coreclrLib) != 0) {
514                         _ERR("libcoreclr.so close failed");
515                 }
516
517                 __coreclrLib = nullptr;
518         }
519
520         finalizePluginManager();
521         finalizePathManager();
522
523         __envList.clear();
524
525         _INFO("Dotnet runtime disposed");
526 }
527
528 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
529 {
530         if (!__initialized) {
531                 _ERR("Runtime is not initialized");
532                 return -1;
533         }
534
535         if (path == nullptr) {
536                 _ERR("executable path is null");
537                 return -1;
538         }
539
540         if (!isFileExist(path)) {
541                 _ERR("File not exist : %s", path);
542                 return -1;
543         }
544
545         if (__enableLogManager) {
546                 // launchpad override stdout and stderr to journalctl before launch application.
547                 // we have to re-override that to input pipe for logging thread.
548                 if (redirectFD() < 0) {
549                         _ERR("Failed to redirect FD");
550                         return -1;
551                 }
552
553                 registerSigHandler();
554         }
555
556         pluginSetAppInfo(appId, path);
557
558         int fd2 = open(root, O_DIRECTORY);
559         dup3(fd2, fd, O_CLOEXEC);
560         if (fd2 >= 0)
561                 close(fd2);
562
563         // set application data path to coreclr environment.
564         // application data path can be changed by owner. So, we have to set data path just before launching.
565         char* localDataPath = app_get_data_path();
566         if (localDataPath != nullptr) {
567                 setEnvironmentVariable("XDG_DATA_HOME", localDataPath);
568                 free(localDataPath);
569         }
570
571         pluginBeforeExecute();
572
573         _INFO("execute assembly : %s", path);
574
575         unsigned int ret = 0;
576         int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
577         if (st < 0)
578                 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
579         return ret;
580 }
581
582 }  // namespace dotnetcore
583 }  // namespace runtime
584 }  // namespace tizen