2 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
31 #include <sys/types.h>
34 #include <linux/limits.h>
38 #include <app_common.h>
42 #include "injection.h"
46 #include "dotnet_launcher.h"
47 #include "plugin_manager.h"
48 #include "path_manager.h"
49 #include "log_manager.h"
52 #define __STR(x) __XSTR(x)
53 static const char* __FRAMEWORK_DIR = __STR(FRAMEWORK_DIR);
59 namespace dotnetcore {
61 #if defined (__aarch64__)
62 #define ARCHITECTURE_IDENTIFIER "arm64"
64 #elif defined (__arm__)
65 #define ARCHITECTURE_IDENTIFIER "armel"
67 #elif defined (__x86_64__)
68 #define ARCHITECTURE_IDENTIFIER "x64"
70 #elif defined (__i386__)
71 #define ARCHITECTURE_IDENTIFIER "x86"
74 #error "Unknown target"
77 static const char* __TIZEN_RID_VERSION_KEY = "db/dotnet/tizen_rid_version";
79 // The sequence of RID_FALLBACK graphs must be:
80 // 1. Tizen + Version + Architecture
82 // 3. OS(tizen, linux, unix) + Architecture
83 // 4. OS(tizen, linux, unix)
85 static std::string getExtraNativeLibDirs(const std::string& appRoot)
87 std::vector<std::string> RID_FALLBACK_GRAPH;
88 std::vector<std::string> RID_FALLBACK_TIZEN;
89 char* tizen_rid = vconf_get_str(__TIZEN_RID_VERSION_KEY);
91 std::vector<std::string> version;
92 splitPath(tizen_rid, version);
93 std::reverse(std::begin(version), std::end(version));
94 for (unsigned int i = 0; i < version.size(); i++) {
95 RID_FALLBACK_TIZEN.push_back(std::string("tizen." + version[i] + "-" + ARCHITECTURE_IDENTIFIER));
96 RID_FALLBACK_TIZEN.push_back(std::string("tizen." + version[i]));
101 std::vector<std::string> RID_FALLBACK_OS = {"tizen", "linux", "unix"};
102 for (unsigned int i = 0; i < RID_FALLBACK_OS.size(); i++) {
103 RID_FALLBACK_GRAPH.push_back(std::string(RID_FALLBACK_OS[i] + "-" + ARCHITECTURE_IDENTIFIER));
104 RID_FALLBACK_GRAPH.push_back(std::string(RID_FALLBACK_OS[i]));
106 RID_FALLBACK_GRAPH.push_back("any");
107 RID_FALLBACK_GRAPH.push_back("base");
109 std::string candidate;
110 for (unsigned int i = 0; i < RID_FALLBACK_GRAPH.size(); i++) {
111 if (!candidate.empty()) {
114 candidate += concatPath(appRoot, "bin/runtimes/" + RID_FALLBACK_GRAPH[i] + "/native");
117 candidate = candidate + ":" + concatPath(appRoot, "lib/" ARCHITECTURE_IDENTIFIER);
118 if (!strncmp(ARCHITECTURE_IDENTIFIER, "arm64", 5)) {
119 candidate = candidate + ":" + concatPath(appRoot, "lib/aarch64");
120 } else if (!strncmp(ARCHITECTURE_IDENTIFIER, "armel", 5)) {
121 candidate = candidate + ":" + concatPath(appRoot, "lib/arm");
128 static std::vector<std::string> __envList;
130 static void setEnvFromFile()
133 std::ifstream inFile(ENV_FILE_PATH);
138 _INFO("coreclr_env.list is found");
141 while (std::getline(inFile, token, '\n')) {
142 if (!token.empty()) {
143 __envList.push_back(token);
147 for (unsigned int i = 0; i < __envList.size(); i++) {
148 putenv(const_cast<char *>(__envList[i].c_str()));
151 _INFO("coreclr_env.list file is not found. skip");
155 #define _unused(x) ((void)(x))
157 struct sigaction sig_abrt_new;
158 struct sigaction sig_abrt_old;
160 static bool checkOnSigabrt = false;
161 static bool checkOnTerminate = false;
163 static void onSigabrt(int signum)
165 // use unused variable to avoid build warning
166 ssize_t ret = write(STDERR_FILENO, "onSigabrt called\n", 17);
168 if (checkOnTerminate) {
169 ret = write(STDERR_FILENO, "onSigabrt called while terminate. go to exit\n", 45);
174 if (checkOnSigabrt) {
175 ret = write(STDERR_FILENO, "onSigabrt called again. go to exit\n", 35);
180 checkOnSigabrt = true;
181 if (sigaction(SIGABRT, &sig_abrt_old, NULL) == 0) {
182 if (raise(signum) < 0) {
183 ret = write(STDERR_FILENO, "Fail to raise SIGABRT\n", 22);
186 ret = write(STDERR_FILENO, "Fail to set original SIGABRT handler\n", 37);
191 static void registerSigHandler()
193 sig_abrt_new.sa_handler = onSigabrt;
194 if (sigemptyset(&sig_abrt_new.sa_mask) != 0) {
195 _ERR("Fail to sigemptyset");
198 if (sigaction(SIGABRT, &sig_abrt_new, &sig_abrt_old) < 0) {
199 _ERR("Fail to add sig handler");
203 static bool storage_cb(int id, storage_type_e type, storage_state_e state, const char *path, void *user_data)
205 int* tmp = (int*)user_data;
206 if (type == STORAGE_TYPE_INTERNAL)
215 static void initEnvForSpecialFolder()
221 error = storage_foreach_device_supported(storage_cb, &storageId);
222 if (error != STORAGE_ERROR_NONE) {
226 error = storage_get_directory(storageId, STORAGE_DIRECTORY_IMAGES, &path);
227 if (error == STORAGE_ERROR_NONE && path != NULL) {
228 setenv("XDG_PICTURES_DIR", const_cast<char *>(path), 1);
233 error = storage_get_directory(storageId, STORAGE_DIRECTORY_MUSIC, &path);
234 if (error == STORAGE_ERROR_NONE && path != NULL) {
235 setenv("XDG_MUSIC_DIR", const_cast<char *>(path), 1);
240 error = storage_get_directory(storageId, STORAGE_DIRECTORY_VIDEOS, &path);
241 if (error == STORAGE_ERROR_NONE && path != NULL) {
242 setenv("XDG_VIDEOS_DIR", const_cast<char *>(path), 1);
248 // terminate candidate process when language changed
249 // icu related data (CultureInfo, etc) should be recreated.
250 static void langChangedCB(keynode_t *key, void* data)
252 _INFO("terminiate candidate process to update language.");
256 static void setLang()
258 char* lang = vconf_get_str(VCONFKEY_LANGSET);
260 _ERR("Fail to get language from vconf");
264 // In order to operate ICU (used for globalization) normally, the following
265 // environment variables must be set before using ICU API.
266 // When running Applicaiton, the following environment variables are set by AppFW.
267 // But when preloading the dll in the candidate process, the following environment variables are not set
268 // As a result, CultureInfo is incorrectly generated and malfunctions.
269 // For example, uloc_getDefault() returns en_US_POSIX, CultureInfo is set to invariant mode.
270 setenv("LANG", const_cast<char *>(lang), 1);
271 setenv("LC_MESSAGES", const_cast<char *>(lang), 1);
272 setenv("LC_ALL", const_cast<char *>(lang), 1);
277 void CoreRuntime::preloadTypes()
279 const static std::string initDllPath = concatPath(__FRAMEWORK_DIR, "Tizen.Init.dll");
280 if (!isFileExist(initDllPath)) {
281 _ERR("Failed to locate Tizen.Init.dll");
285 typedef void (*InitDelegate)();
286 InitDelegate initDelegate;
288 int ret = createDelegate(__hostHandle,
291 "Tizen.Init.TypeLoader",
293 (void**)&initDelegate);
296 _ERR("Failed to create delegate for PreloadTypes (0x%08x)", ret);
302 CoreRuntime::CoreRuntime(const char* mode) :
303 initializeClr(nullptr),
304 executeAssembly(nullptr),
306 createDelegate(nullptr),
307 setEnvironmentVariable(nullptr),
308 __coreclrLib(nullptr),
309 __hostHandle(nullptr),
312 __initialized(false),
313 __isProfileMode(false)
315 _INFO("Constructor called!!");
317 // Intiailize ecore first (signal handlers, etc.) before runtime init.
320 // set language environment to support ICU
324 env = getenv("CORECLR_ENABLE_PROFILING");
325 if (env != nullptr && !strcmp(env, "1")) {
326 _INFO("profiling mode on");
327 __isProfileMode = true;
330 // plugin initialize should be called before start loader mainloop.
331 // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
332 // When attaching to a secure zone, if there is a created thread, it will failed.
333 // So, plugin initialize should be called before mainloop start.
334 if (initializePluginManager(mode) < 0) {
335 _ERR("Failed to initialize PluginManager");
339 CoreRuntime::~CoreRuntime()
341 // workaround : to prevent crash while process terminate on profiling mode,
342 // kill process immediately.
343 // see https://github.com/dotnet/coreclr/issues/26687
344 if (__isProfileMode) {
345 _INFO("shutdown process immediately.");
352 int CoreRuntime::initialize(bool standalone, bool useDlog, const char* corerunRoot)
354 // checkInjection checks dotnet-launcher run mode
355 // At the moment, this mechanism is used only when the Memory Profiler is started.
356 int res = checkInjection();
358 _ERR("Failed to initnialize Memory Profiler");
362 #define __STR(x) __XSTR(x)
364 #ifdef NATIVE_LIB_DIR
365 __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
372 // libunwind library is used to unwind stack frame, but libunwind for ARM
373 // does not support ARM vfpv3/NEON registers in DWARF format correctly.
374 // Therefore let's disable stack unwinding using DWARF information
375 // See https://github.com/dotnet/coreclr/issues/6698
377 // libunwind use following methods to unwind stack frame.
378 // UNW_ARM_METHOD_ALL 0xFF
379 // UNW_ARM_METHOD_DWARF 0x01
380 // UNW_ARM_METHOD_FRAME 0x02
381 // UNW_ARM_METHOD_EXIDX 0x04
382 putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
385 // Disable debug pipes and semaphores creation in case of non-standlone mode
387 putenv(const_cast<char *>("COMPlus_EnableDiagnostics=0"));
389 // Write Debug.WriteLine to stderr
390 putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
392 #ifdef USE_DEFAULT_BASE_ADDR
393 putenv(const_cast<char *>("COMPlus_UseDefaultBaseAddr=1"));
394 #endif // USE_DEFAULT_BASE_ADDR
396 // read string from external file and set them to environment value.
399 if (initializePathManager(std::string(), std::string(), std::string()) < 0) {
400 _ERR("Failed to initialize PathManager");
404 if (useDlog && !pluginHasLogControl()) {
405 if (initializeLogManager() < 0) {
406 _ERR("Failed to initnialize LogManager");
411 std::string libCoreclr(concatPath(getRuntimeDir(), "libcoreclr.so"));
413 __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
414 if (__coreclrLib == nullptr) {
415 char *err = dlerror();
416 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
417 if (access(libCoreclr.c_str(), R_OK) == -1)
418 _ERR("access '%s': %s\n", libCoreclr.c_str(), strerror(errno));
422 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
424 variable = (type)dlsym(__coreclrLib, name); \
425 if (variable == nullptr) { \
426 _ERR(name " is not found in the libcoreclr.so"); \
431 CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
432 CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
433 CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
434 CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
436 #undef CORELIB_RETURN_IF_NOSYM
438 _INFO("libcoreclr dlopen and dlsym success");
443 // terminate candidate process if language is changed.
444 // CurrentCulture created for preloaded dlls should be updated.
445 vconf_notify_key_changed(VCONFKEY_LANGSET, langChangedCB, NULL);
448 // Set environment for System.Environment.SpecialFolder
449 // Below function creates dbus connection by callging storage API.
450 // If dbus connection is created bofere fork(), forked process cannot use dbus.
451 // To avoid gdbus blocking issue, below function should be called after fork()
452 initEnvForSpecialFolder();
454 std::string tpa = getTPA();
455 std::string runtimeDir = getRuntimeDir();
456 std::string appName = std::string("dotnet-launcher-") + std::to_string(getpid());
457 std::string probePath;
458 std::string NIprobePath;
459 std::string nativeLibPath;
462 probePath = corerunRoot;
463 NIprobePath = corerunRoot;
464 nativeLibPath = corerunRoot;
466 __fd = open("/proc/self", O_DIRECTORY);
468 _ERR("Failed to open /proc/self");
471 std::string appRoot = std::string("/proc/self/fd/") + std::to_string(__fd);
472 std::string appBin = concatPath(appRoot, "bin");
473 std::string appLib = concatPath(appRoot, "lib");
474 std::string appTac = concatPath(appBin, TAC_SYMLINK_SUB_DIR);
475 probePath = appRoot + ":" + appBin + ":" + appLib + ":" + appTac;
476 NIprobePath = concatPath(appBin, APP_NI_SUB_DIR) + ":" + concatPath(appLib, APP_NI_SUB_DIR) + ":" + appTac;
477 nativeLibPath = getExtraNativeLibDirs(appRoot) + ":" + appBin + ":" + appLib + ":" + __nativeLibDirectory + ":" + runtimeDir;
480 if (!initializeCoreClr(appName.c_str(), probePath.c_str(), NIprobePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
481 _ERR("Failed to initialize coreclr");
485 int st = createDelegate(__hostHandle, __domainId, "Dotnet.Launcher", "Dotnet.Launcher.Environment", "SetEnvironmentVariable", (void**)&setEnvironmentVariable);
486 if (st < 0 || setEnvironmentVariable == nullptr) {
487 _ERR("Create delegate for Dotnet.Launcher.dll -> Dotnet.Launcher.Environment -> SetEnvironmentVariable failed (0x%08x)", st);
491 __initialized = true;
494 preloadTypes(); // Preload common managed code
497 _INFO("CoreRuntime initialize success");
502 bool CoreRuntime::initializeCoreClr(const char* appId,
503 const char* assemblyProbePaths,
504 const char* NIProbePaths,
505 const char* pinvokeProbePaths,
508 const char *propertyKeys[] = {
509 "TRUSTED_PLATFORM_ASSEMBLIES",
512 "NATIVE_DLL_SEARCH_DIRECTORIES",
513 "AppDomainCompatSwitch"
516 const char *propertyValues[] = {
521 "UseLatestBehaviorWhenTFMNotSpecified"
524 std::string selfPath = readSelfPath();
526 int st = initializeClr(selfPath.c_str(),
528 sizeof(propertyKeys) / sizeof(propertyKeys[0]),
535 _ERR("initialize core clr fail! (0x%08x)", st);
539 pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
541 _INFO("Initialize core clr success");
545 void CoreRuntime::dispose()
547 // call plugin finalize function to notify finalize to plugin
548 // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
551 // ignore the signal generated by an exception that occurred during shutdown
552 checkOnTerminate = true;
554 if (__hostHandle != nullptr) {
555 int st = shutdown(__hostHandle, __domainId);
557 _ERR("shutdown core clr fail! (0x%08x)", st);
558 __hostHandle = nullptr;
561 if (__coreclrLib != nullptr) {
562 if (dlclose(__coreclrLib) != 0) {
563 _ERR("libcoreclr.so close failed");
566 __coreclrLib = nullptr;
569 finalizePluginManager();
570 finalizePathManager();
574 _INFO("Dotnet runtime disposed");
577 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
579 if (!__initialized) {
580 _ERR("Runtime is not initialized");
584 if (path == nullptr) {
585 _ERR("executable path is null");
589 if (!isFileExist(path)) {
590 _ERR("File not exist : %s", path);
594 // launchpad override stdout and stderr to journalctl before launch application.
595 // we have to re-override that to input pipe for logging thread.
596 // if LogManager is not initialized, below redirectFD will return 0;
597 if (redirectFD() < 0) {
598 _ERR("Failed to redirect FD");
602 // VD has their own signal handler.
603 if (!pluginHasLogControl()) {
604 registerSigHandler();
607 pluginSetAppInfo(appId, path);
609 // override root path for application launch mode (candidate / standalone mode)
611 int fd2 = open(root, O_DIRECTORY);
612 dup3(fd2, __fd, O_CLOEXEC);
617 // set application data path to coreclr environment.
618 // application data path can be changed by owner. So, we have to set data path just before launching.
619 char* localDataPath = app_get_data_path();
620 if (localDataPath != nullptr) {
621 setEnvironmentVariable("XDG_DATA_HOME", localDataPath);
625 vconf_ignore_key_changed(VCONFKEY_LANGSET, langChangedCB);
627 pluginBeforeExecute();
629 _INFO("execute assembly : %s", path);
631 unsigned int ret = 0;
632 int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
634 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
638 } // namespace dotnetcore
639 } // namespace runtime