Do not need to check if the Tizen.Runtime.dll exists
[platform/core/dotnet/launcher.git] / NativeLauncher / launcher / lib / 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 <vconf.h>
38 #include <app_common.h>
39
40 #include <Ecore.h>
41
42 #include "injection.h"
43 #include "utils.h"
44 #include "log.h"
45 #include "dotnet_launcher.h"
46 #include "plugin_manager.h"
47 #include "path_manager.h"
48 #include "log_manager.h"
49
50 namespace tizen {
51 namespace runtime {
52 namespace dotnetcore {
53
54 #if defined (__aarch64__)
55 #define ARCHITECTURE_IDENTIFIER "arm64"
56
57 #elif defined (__arm__)
58 #define ARCHITECTURE_IDENTIFIER "armel"
59
60 #elif defined (__x86_64__)
61 #define ARCHITECTURE_IDENTIFIER "x64"
62
63 #elif defined (__i386__)
64 #define ARCHITECTURE_IDENTIFIER "x86"
65
66 #else
67 #error "Unknown target"
68 #endif
69
70 static const char* __TIZEN_RID_VERSION_KEY = "db/dotnet/tizen_rid_version";
71
72 // The sequence of RID_FALLBACK graphs must be:
73 // 1. Tizen + Version + Architecture
74 // 2. Tizen + Version
75 // 3. OS(tizen, linux, unix) + Architecture
76 // 4. OS(tizen, linux, unix)
77 // 5. any, base
78 static std::string getExtraNativeLibDirs(const std::string& appRoot)
79 {
80         std::vector<std::string> RID_FALLBACK_GRAPH;
81         std::vector<std::string> RID_FALLBACK_TIZEN;
82         char* tizen_rid = vconf_get_str(__TIZEN_RID_VERSION_KEY);
83         if (tizen_rid) {
84                 std::vector<std::string> version;
85                 splitPath(tizen_rid, version);
86                 std::reverse(std::begin(version), std::end(version));
87                 for (unsigned int i = 0; i < version.size(); i++) {
88                         RID_FALLBACK_TIZEN.push_back(std::string("tizen." + version[i] + "-" + ARCHITECTURE_IDENTIFIER));
89                         RID_FALLBACK_TIZEN.push_back(std::string("tizen." + version[i]));
90                 }
91                 free(tizen_rid);
92         }
93
94         std::vector<std::string> RID_FALLBACK_OS = {"tizen", "linux", "unix"};
95         for (unsigned int i = 0; i < RID_FALLBACK_OS.size(); i++) {
96                 RID_FALLBACK_GRAPH.push_back(std::string(RID_FALLBACK_OS[i] + "-" +  ARCHITECTURE_IDENTIFIER));
97                 RID_FALLBACK_GRAPH.push_back(std::string(RID_FALLBACK_OS[i]));
98         }
99         RID_FALLBACK_GRAPH.push_back("any");
100         RID_FALLBACK_GRAPH.push_back("base");
101
102         std::string candidate;
103         for (unsigned int i = 0; i < RID_FALLBACK_GRAPH.size(); i++) {
104                 if (!candidate.empty()) {
105                         candidate += ":";
106                 }
107                 candidate += concatPath(appRoot, "bin/runtimes/" + RID_FALLBACK_GRAPH[i] + "/native");
108         }
109
110         candidate = candidate + ":" + concatPath(appRoot, "lib/" ARCHITECTURE_IDENTIFIER);
111         if (!strncmp(ARCHITECTURE_IDENTIFIER, "arm64", 5)) {
112                 candidate = candidate + ":" + concatPath(appRoot, "lib/aarch64");
113         } else if (!strncmp(ARCHITECTURE_IDENTIFIER, "armel", 5)) {
114                 candidate = candidate + ":" + concatPath(appRoot, "lib/arm");
115         }
116
117         return candidate;
118 }
119
120
121 static std::vector<std::string> __envList;
122
123 static void setEnvFromFile()
124 {
125         std::string envList;
126         std::ifstream inFile(ENV_FILE_PATH);
127
128         __envList.clear();
129
130         if (inFile) {
131                 _INFO("coreclr_env.list is found");
132
133                 std::string token;
134                 while (std::getline(inFile, token, '\n')) {
135                         if (!token.empty()) {
136                                 __envList.push_back(token);
137                         }
138                 }
139
140                 for (unsigned int i = 0; i < __envList.size(); i++) {
141                         putenv(const_cast<char *>(__envList[i].c_str()));
142                 }
143         } else {
144                 _INFO("coreclr_env.list file is not found. skip");
145         }
146 }
147
148 #define _unused(x) ((void)(x))
149
150 struct sigaction sig_abrt_new;
151 struct sigaction sig_abrt_old;
152
153 static bool checkOnSigabrt = false;
154 static bool checkOnTerminate = false;
155
156 static void onSigabrt(int signum)
157 {
158         // use unused variable to avoid build warning
159         ssize_t ret = write(STDERR_FILENO, "onSigabrt called\n", 17);
160
161         if (checkOnTerminate) {
162                 ret = write(STDERR_FILENO, "onSigabrt called while terminate. go to exit\n", 45);
163                 _unused(ret);
164                 exit(0);
165         }
166
167         if (checkOnSigabrt) {
168                 ret = write(STDERR_FILENO, "onSigabrt called again. go to exit\n", 35);
169                 _unused(ret);
170                 exit(0);
171         }
172
173         checkOnSigabrt = true;
174         if (sigaction(SIGABRT, &sig_abrt_old, NULL) == 0) {
175                 if (raise(signum) < 0) {
176                         ret = write(STDERR_FILENO, "Fail to raise SIGABRT\n", 22);
177                 }
178         } else {
179                 ret = write(STDERR_FILENO, "Fail to set original SIGABRT handler\n", 37);
180         }
181         _unused(ret);
182 }
183
184 static void registerSigHandler()
185 {
186         sig_abrt_new.sa_handler = onSigabrt;
187         if (sigemptyset(&sig_abrt_new.sa_mask) != 0) {
188                 _ERR("Fail to sigemptyset");
189         }
190
191         if (sigaction(SIGABRT, &sig_abrt_new, &sig_abrt_old) < 0) {
192                 _ERR("Fail to add sig handler");
193         }
194 }
195
196 static bool storage_cb(int id, storage_type_e type, storage_state_e state, const char *path, void *user_data)
197 {
198         int* tmp = (int*)user_data;
199         if (type == STORAGE_TYPE_INTERNAL)
200         {
201                 *tmp = id;
202                 return false;
203         }
204
205         return true;
206 }
207
208 static void initEnvForSpecialFolder()
209 {
210         int storageId;
211         int error;
212         char *path = NULL;
213
214         error = storage_foreach_device_supported(storage_cb, &storageId);
215         if (error != STORAGE_ERROR_NONE) {
216                 return;
217         }
218
219         error = storage_get_directory(storageId, STORAGE_DIRECTORY_IMAGES, &path);
220         if (error == STORAGE_ERROR_NONE && path != NULL) {
221                 setenv("XDG_PICTURES_DIR", const_cast<char *>(path), 1);
222                 free(path);
223                 path = NULL;
224         }
225
226         error = storage_get_directory(storageId, STORAGE_DIRECTORY_MUSIC, &path);
227         if (error == STORAGE_ERROR_NONE && path != NULL) {
228                 setenv("XDG_MUSIC_DIR", const_cast<char *>(path), 1);
229                 free(path);
230                 path = NULL;
231         }
232
233         error = storage_get_directory(storageId, STORAGE_DIRECTORY_VIDEOS, &path);
234         if (error == STORAGE_ERROR_NONE && path != NULL) {
235                 setenv("XDG_VIDEOS_DIR", const_cast<char *>(path), 1);
236                 free(path);
237                 path = NULL;
238         }
239 }
240
241 // terminate candidate process when language changed
242 // icu related data (CultureInfo, etc) should be recreated.
243 static void langChangedCB(keynode_t *key, void* data)
244 {
245         _INFO("terminiate candidate process to update language.");
246         exit(0);
247 }
248
249 static void setLang()
250 {
251         char* lang = vconf_get_str(VCONFKEY_LANGSET);
252         if (!lang) {
253                 _ERR("Fail to get language from vconf");
254                 return;
255         }
256
257         // In order to operate ICU (used for globalization) normally, the following
258         // environment variables must be set before using ICU API.
259         // When running Applicaiton, the following environment variables are set by AppFW.
260         // But when preloading the dll in the candidate process, the following environment variables are not set
261         // As a result, CultureInfo is incorrectly generated and malfunctions.
262         // For example, uloc_getDefault() returns en_US_POSIX, CultureInfo is set to invariant mode.
263         setenv("LANG", const_cast<char *>(lang), 1);
264         setlocale(LC_ALL, const_cast<char *>(lang));
265
266         free(lang);
267 }
268
269 void CoreRuntime::preload()
270 {
271         typedef void (*PreloadDelegate)();
272         PreloadDelegate preloadDelegate;
273
274         int ret = createDelegate(__hostHandle,
275                 __domainId,
276                 "Tizen.Runtime",
277                 "Tizen.Runtime.Preloader",
278                 "Preload",
279                 (void**)&preloadDelegate);
280
281         if (ret < 0) {
282                 _ERR("Failed to create delegate for Tizen.Runtime Preload (0x%08x)", ret);
283         } else {
284                 preloadDelegate();
285         }
286 }
287
288 CoreRuntime::CoreRuntime(const char* mode) :
289         initializeClr(nullptr),
290         executeAssembly(nullptr),
291         shutdown(nullptr),
292         createDelegate(nullptr),
293         setEnvironmentVariable(nullptr),
294         __coreclrLib(nullptr),
295         __hostHandle(nullptr),
296         __domainId(-1),
297         __fd(-1),
298         __initialized(false),
299         __isProfileMode(false)
300 {
301         _INFO("Constructor called!!");
302
303         // Intiailize ecore first (signal handlers, etc.) before runtime init.
304         ecore_init();
305
306         // set language environment to support ICU
307         setLang();
308
309         char *env = nullptr;
310         env = getenv("CORECLR_ENABLE_PROFILING");
311         if (env != nullptr && !strcmp(env, "1")) {
312                 _INFO("profiling mode on");
313                 __isProfileMode = true;
314         }
315
316         // plugin initialize should be called before start loader mainloop.
317         // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
318         // When attaching to a secure zone, if there is a created thread, it will failed.
319         // So, plugin initialize should be called before mainloop start.
320         if (initializePluginManager(mode) < 0) {
321                 _ERR("Failed to initialize PluginManager");
322         }
323 }
324
325 CoreRuntime::~CoreRuntime()
326 {
327         // workaround : to prevent crash while process terminate on profiling mode,
328         //              kill process immediately.
329         // see https://github.com/dotnet/coreclr/issues/26687
330         if (__isProfileMode) {
331                 _INFO("shutdown process immediately.");
332                 _exit(0);
333         }
334
335         dispose();
336 }
337
338 int CoreRuntime::initialize(LaunchMode launchMode)
339 {
340         // checkInjection checks dotnet-launcher run mode
341         // At the moment, this mechanism is used only when the Memory Profiler is started.
342         int res = checkInjection();
343         if (res != 0) {
344                 _ERR("Failed to initnialize Memory Profiler");
345                 return -1;
346         }
347 #define __XSTR(x) #x
348 #define __STR(x) __XSTR(x)
349
350 #ifdef NATIVE_LIB_DIR
351         __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
352 #endif
353
354 #undef __STR
355 #undef __XSTR
356
357 #ifdef __arm__
358         // libunwind library is used to unwind stack frame, but libunwind for ARM
359         // does not support ARM vfpv3/NEON registers in DWARF format correctly.
360         // Therefore let's disable stack unwinding using DWARF information
361         // See https://github.com/dotnet/coreclr/issues/6698
362         //
363         // libunwind use following methods to unwind stack frame.
364         // UNW_ARM_METHOD_ALL          0xFF
365         // UNW_ARM_METHOD_DWARF        0x01
366         // UNW_ARM_METHOD_FRAME        0x02
367         // UNW_ARM_METHOD_EXIDX        0x04
368         putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
369 #endif // __arm__
370
371         // Enable diagnostics.
372         // clr create clr-debug-pipe-xxx and dotnet-diagnostics-xxx file under /tmp dir.
373         putenv(const_cast<char *>("COMPlus_EnableDiagnostics=1"));
374
375         // Write Debug.WriteLine to stderr
376         putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
377
378 #ifdef USE_DEFAULT_BASE_ADDR
379         putenv(const_cast<char *>("COMPlus_UseDefaultBaseAddr=1"));
380 #endif // USE_DEFAULT_BASE_ADDR
381
382         // read string from external file and set them to environment value.
383         setEnvFromFile();
384
385         if (initializePathManager(std::string(), std::string(), std::string()) < 0) {
386                 _ERR("Failed to initialize PathManager");
387                 return -1;
388         }
389
390         if (!pluginHasLogControl()) {
391                 if (initializeLogManager() < 0) {
392                         _ERR("Failed to initnialize LogManager");
393                         return -1;
394                 }
395         }
396
397         std::string libCoreclr(concatPath(getRuntimeDir(), "libcoreclr.so"));
398
399         __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
400         if (__coreclrLib == nullptr) {
401                 char *err = dlerror();
402                 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
403                 if (access(libCoreclr.c_str(), R_OK) == -1)
404                         _ERR("access '%s': %s\n", libCoreclr.c_str(), strerror(errno));
405                 return -1;
406         }
407
408 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
409         do { \
410                 variable = (type)dlsym(__coreclrLib, name); \
411                 if (variable == nullptr) { \
412                         _ERR(name " is not found in the libcoreclr.so"); \
413                         return -1; \
414                 } \
415         } while (0)
416
417         CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
418         CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
419         CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
420         CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
421
422 #undef CORELIB_RETURN_IF_NOSYM
423
424         _INFO("libcoreclr dlopen and dlsym success");
425
426         if (launchMode == LaunchMode::loader) {
427                 pluginPreload();
428
429                 // terminate candidate process if language is changed.
430                 // CurrentCulture created for preloaded dlls should be updated.
431                 vconf_notify_key_changed(VCONFKEY_LANGSET, langChangedCB, NULL);
432         }
433
434         // Set environment for System.Environment.SpecialFolder
435         // Below function creates dbus connection by callging storage API.
436         // If dbus connection is created bofere fork(), forked process cannot use dbus.
437         // To avoid gdbus blocking issue, below function should be called after fork()
438         initEnvForSpecialFolder();
439
440         __fd = open("/proc/self", O_DIRECTORY);
441         if (__fd < 0) {
442                 _ERR("Failed to open /proc/self");
443                 return -1;
444         }
445
446         std::string tpa = getTPA();
447         std::string runtimeDir = getRuntimeDir();
448         std::string appName = std::string("dotnet-launcher-") + std::to_string(getpid());
449         std::string appRoot = std::string("/proc/self/fd/") + std::to_string(__fd);
450         std::string appBin = concatPath(appRoot, "bin");
451         std::string appLib = concatPath(appRoot, "lib");
452         std::string appTac = concatPath(appBin, TAC_SYMLINK_SUB_DIR);
453         std::string probePath = appRoot + ":" + appBin + ":" + appLib + ":" + appTac;
454         std::string NIprobePath = concatPath(appBin, APP_NI_SUB_DIR) + ":" + concatPath(appLib, APP_NI_SUB_DIR) + ":" + appTac;
455         std::string nativeLibPath = getExtraNativeLibDirs(appRoot) + ":" + appBin + ":" + appLib + ":" + __nativeLibDirectory + ":" + runtimeDir;
456
457         if (!initializeCoreClr(appName.c_str(), probePath.c_str(), NIprobePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
458                 _ERR("Failed to initialize coreclr");
459                 return -1;
460         }
461
462         int st = createDelegate(__hostHandle, __domainId, "Dotnet.Launcher", "Dotnet.Launcher.Environment", "SetEnvironmentVariable", (void**)&setEnvironmentVariable);
463         if (st < 0 || setEnvironmentVariable == nullptr) {
464                 _ERR("Create delegate for Dotnet.Launcher.dll -> Dotnet.Launcher.Environment -> SetEnvironmentVariable failed (0x%08x)", st);
465                 return -1;
466         }
467
468         __initialized = true;
469
470         if (launchMode == LaunchMode::loader) {
471                 preload();              // Preload common managed code
472         }
473
474         _INFO("CoreRuntime initialize success");
475
476         return 0;
477 }
478
479 bool CoreRuntime::initializeCoreClr(const char* appId,
480                                                                          const char* assemblyProbePaths,
481                                                                          const char* NIProbePaths,
482                                                                          const char* pinvokeProbePaths,
483                                                                          const char* tpaList)
484 {
485         const char *propertyKeys[] = {
486                 "TRUSTED_PLATFORM_ASSEMBLIES",
487                 "APP_PATHS",
488                 "APP_NI_PATHS",
489                 "NATIVE_DLL_SEARCH_DIRECTORIES",
490                 "AppDomainCompatSwitch"
491         };
492
493         const char *propertyValues[] = {
494                 tpaList,
495                 assemblyProbePaths,
496                 NIProbePaths,
497                 pinvokeProbePaths,
498                 "UseLatestBehaviorWhenTFMNotSpecified"
499         };
500
501         std::string selfPath = readSelfPath();
502
503         int st = initializeClr(selfPath.c_str(),
504                                                         appId,
505                                                         sizeof(propertyKeys) / sizeof(propertyKeys[0]),
506                                                         propertyKeys,
507                                                         propertyValues,
508                                                         &__hostHandle,
509                                                         &__domainId);
510
511         if (st < 0) {
512                 _ERR("initialize core clr fail! (0x%08x)", st);
513                 return false;
514         }
515
516         pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
517
518         _INFO("Initialize core clr success");
519         return true;
520 }
521
522 void CoreRuntime::dispose()
523 {
524         // call plugin finalize function to notify finalize to plugin
525         // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
526         pluginFinalize();
527
528         // ignore the signal generated by an exception that occurred during shutdown
529         checkOnTerminate = true;
530
531         if (__hostHandle != nullptr) {
532                 int st = shutdown(__hostHandle, __domainId);
533                 if (st < 0)
534                         _ERR("shutdown core clr fail! (0x%08x)", st);
535                 __hostHandle = nullptr;
536         }
537
538         if (__coreclrLib != nullptr) {
539                 if (dlclose(__coreclrLib) != 0) {
540                         _ERR("libcoreclr.so close failed");
541                 }
542
543                 __coreclrLib = nullptr;
544         }
545
546         finalizePluginManager();
547         finalizePathManager();
548
549         __envList.clear();
550
551         _INFO("Dotnet runtime disposed");
552 }
553
554 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
555 {
556         if (!__initialized) {
557                 _ERR("Runtime is not initialized");
558                 return -1;
559         }
560
561         if (path == nullptr) {
562                 _ERR("executable path is null");
563                 return -1;
564         }
565
566         if (!isFileExist(path)) {
567                 _ERR("File not exist : %s", path);
568                 return -1;
569         }
570
571         // launchpad override stdout and stderr to journalctl before launch application.
572         // we have to re-override that to input pipe for logging thread.
573         // if LogManager is not initialized, below redirectFD will return 0;
574         if (redirectFD() < 0) {
575                 _ERR("Failed to redirect FD");
576                 return -1;
577         }
578
579         // VD has their own signal handler.
580         if (!pluginHasLogControl()) {
581                 registerSigHandler();
582         }
583
584         pluginSetAppInfo(appId, path);
585
586         // override root path for application launch mode (candidate / standalone mode)
587         if (__fd >= 0) {
588                 int fd2 = open(root, O_DIRECTORY);
589                 dup3(fd2, __fd, O_CLOEXEC);
590                 if (fd2 >= 0)
591                         close(fd2);
592         }
593
594         // set application data path to coreclr environment.
595         // application data path can be changed by owner. So, we have to set data path just before launching.
596         char* localDataPath = app_get_data_path();
597         if (localDataPath != nullptr) {
598                 setEnvironmentVariable("XDG_DATA_HOME", localDataPath);
599                 free(localDataPath);
600         }
601
602         vconf_ignore_key_changed(VCONFKEY_LANGSET, langChangedCB);
603
604         pluginBeforeExecute();
605
606         _INFO("execute assembly : %s", path);
607
608         unsigned int ret = 0;
609         int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
610         if (st < 0)
611                 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
612         return ret;
613 }
614
615 }  // namespace dotnetcore
616 }  // namespace runtime
617 }  // namespace tizen