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"
45 #include "core_runtime.h"
46 #include "plugin_manager.h"
47 #include "path_manager.h"
48 #include "log_manager.h"
52 namespace dotnetcore {
54 static coreclr_initialize_ptr initializeClr = nullptr;
55 static coreclr_execute_assembly_ptr executeAssembly = nullptr;
56 static coreclr_shutdown_ptr shutdown = nullptr;
57 static coreclr_create_delegate_ptr createDelegate = nullptr;
58 static set_environment_variable_ptr setEnvironmentVariable = nullptr;
59 static void* __coreclrLib = nullptr;
60 static void* __hostHandle = nullptr;
61 static unsigned int __domainId = -1;
63 static bool __initialized = false;
64 static bool __isProfileMode = false;
67 #define __STR(x) __XSTR(x)
70 static std::string __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
76 #if defined (__aarch64__)
77 #define ARCHITECTURE_IDENTIFIER "arm64"
79 #elif defined (__arm__)
80 #define ARCHITECTURE_IDENTIFIER "armel"
82 #elif defined (__x86_64__)
83 #define ARCHITECTURE_IDENTIFIER "x64"
85 #elif defined (__i386__)
86 #define ARCHITECTURE_IDENTIFIER "x86"
89 #error "Unknown target"
92 static const char* __TIZEN_RID_VERSION_KEY = "db/dotnet/tizen_rid_version";
94 // The sequence of RID_FALLBACK graphs must be:
95 // 1. Tizen + Version + Architecture
97 // 3. OS(tizen, linux, unix) + Architecture
98 // 4. OS(tizen, linux, unix)
100 static std::string getExtraNativeLibDirs(const std::string& appRoot)
102 std::vector<std::string> RID_FALLBACK_GRAPH;
103 char* tizen_rid = vconf_get_str(__TIZEN_RID_VERSION_KEY);
105 std::vector<std::string> version;
106 splitPath(tizen_rid, version);
107 std::reverse(std::begin(version), std::end(version));
108 for (unsigned int i = 0; i < version.size(); i++) {
109 RID_FALLBACK_GRAPH.push_back(std::string("tizen." + version[i] + "-" + ARCHITECTURE_IDENTIFIER));
110 RID_FALLBACK_GRAPH.push_back(std::string("tizen." + version[i]));
115 std::vector<std::string> RID_FALLBACK_OS = {"tizen", "linux", "unix"};
116 for (unsigned int i = 0; i < RID_FALLBACK_OS.size(); i++) {
117 RID_FALLBACK_GRAPH.push_back(std::string(RID_FALLBACK_OS[i] + "-" + ARCHITECTURE_IDENTIFIER));
118 RID_FALLBACK_GRAPH.push_back(std::string(RID_FALLBACK_OS[i]));
120 RID_FALLBACK_GRAPH.push_back("any");
121 RID_FALLBACK_GRAPH.push_back("base");
123 std::string candidate;
124 for (unsigned int i = 0; i < RID_FALLBACK_GRAPH.size(); i++) {
125 if (!candidate.empty()) {
128 candidate += concatPath(appRoot, "bin/runtimes/" + RID_FALLBACK_GRAPH[i] + "/native");
131 candidate = candidate + ":" + concatPath(appRoot, "lib/" ARCHITECTURE_IDENTIFIER);
132 if (!strncmp(ARCHITECTURE_IDENTIFIER, "arm64", 5)) {
133 candidate = candidate + ":" + concatPath(appRoot, "lib/aarch64");
134 } else if (!strncmp(ARCHITECTURE_IDENTIFIER, "armel", 5)) {
135 candidate = candidate + ":" + concatPath(appRoot, "lib/arm");
142 static std::vector<std::string> __envList;
144 static void setEnvFromFile()
147 std::ifstream inFile(ENV_FILE_PATH);
152 _INFO("coreclr_env.list is found");
155 while (std::getline(inFile, token, '\n')) {
156 if (!token.empty()) {
157 __envList.push_back(token);
161 for (unsigned int i = 0; i < __envList.size(); i++) {
162 putenv(const_cast<char *>(__envList[i].c_str()));
165 _INFO("coreclr_env.list file is not found. skip");
169 #define _unused(x) ((void)(x))
171 struct sigaction sig_abrt_new;
172 struct sigaction sig_abrt_old;
174 static bool checkOnSigabrt = false;
175 static bool checkOnTerminate = false;
177 static void onSigabrt(int signum)
179 // use unused variable to avoid build warning
180 ssize_t ret = write(STDERR_FILENO, "onSigabrt called\n", 17);
182 if (checkOnTerminate) {
183 ret = write(STDERR_FILENO, "onSigabrt called while terminate. go to exit\n", 45);
188 if (checkOnSigabrt) {
189 ret = write(STDERR_FILENO, "onSigabrt called again. go to exit\n", 35);
194 checkOnSigabrt = true;
195 if (sigaction(SIGABRT, &sig_abrt_old, NULL) == 0) {
196 if (raise(signum) < 0) {
197 ret = write(STDERR_FILENO, "Fail to raise SIGABRT\n", 22);
200 ret = write(STDERR_FILENO, "Fail to set original SIGABRT handler\n", 37);
205 static void registerSigHandler()
207 sig_abrt_new.sa_handler = onSigabrt;
208 if (sigemptyset(&sig_abrt_new.sa_mask) != 0) {
209 _ERR("Fail to sigemptyset");
212 if (sigaction(SIGABRT, &sig_abrt_new, &sig_abrt_old) < 0) {
213 _ERR("Fail to add sig handler");
217 static bool storage_cb(int id, storage_type_e type, storage_state_e state, const char *path, void *user_data)
219 int* tmp = (int*)user_data;
220 if (type == STORAGE_TYPE_INTERNAL)
229 static void initEnvForSpecialFolder()
235 error = storage_foreach_device_supported(storage_cb, &storageId);
236 if (error != STORAGE_ERROR_NONE) {
240 error = storage_get_directory(storageId, STORAGE_DIRECTORY_IMAGES, &path);
241 if (error == STORAGE_ERROR_NONE && path != NULL) {
242 setenv("XDG_PICTURES_DIR", const_cast<char *>(path), 1);
247 error = storage_get_directory(storageId, STORAGE_DIRECTORY_MUSIC, &path);
248 if (error == STORAGE_ERROR_NONE && path != NULL) {
249 setenv("XDG_MUSIC_DIR", const_cast<char *>(path), 1);
254 error = storage_get_directory(storageId, STORAGE_DIRECTORY_VIDEOS, &path);
255 if (error == STORAGE_ERROR_NONE && path != NULL) {
256 setenv("XDG_VIDEOS_DIR", const_cast<char *>(path), 1);
262 // terminate candidate process when language changed
263 // icu related data (CultureInfo, etc) should be recreated.
264 static void langChangedCB(keynode_t *key, void* data)
266 _INFO("terminiate candidate process to update language.");
270 static void setLang()
272 char* lang = vconf_get_str(VCONFKEY_LANGSET);
274 _ERR("Fail to get language from vconf");
278 // In order to operate ICU (used for globalization) normally, the following
279 // environment variables must be set before using ICU API.
280 // When running Applicaiton, the following environment variables are set by AppFW.
281 // But when preloading the dll in the candidate process, the following environment variables are not set
282 // As a result, CultureInfo is incorrectly generated and malfunctions.
283 // For example, uloc_getDefault() returns en_US_POSIX, CultureInfo is set to invariant mode.
284 setenv("LANG", const_cast<char *>(lang), 1);
285 setlocale(LC_ALL, const_cast<char *>(lang));
290 static std::string readSelfPath()
293 ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
296 return std::string(buff);
304 typedef void (*PreloadDelegate)();
305 PreloadDelegate preloadDelegate;
307 int ret = createDelegate(__hostHandle,
310 "Tizen.Runtime.Preloader",
312 (void**)&preloadDelegate);
315 _ERR("Failed to create delegate for Tizen.Runtime Preload (0x%08x)", ret);
321 bool initializeCoreClr(const char* appId,
322 const char* assemblyProbePaths,
323 const char* NIProbePaths,
324 const char* pinvokeProbePaths,
327 const char *propertyKeys[] = {
328 "TRUSTED_PLATFORM_ASSEMBLIES",
331 "NATIVE_DLL_SEARCH_DIRECTORIES",
332 "AppDomainCompatSwitch"
335 const char *propertyValues[] = {
340 "UseLatestBehaviorWhenTFMNotSpecified"
343 std::string selfPath = readSelfPath();
345 int st = initializeClr(selfPath.c_str(),
347 sizeof(propertyKeys) / sizeof(propertyKeys[0]),
354 _ERR("initialize core clr fail! (0x%08x)", st);
358 pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
360 _INFO("Initialize core clr success");
364 int CoreRuntime::initialize(const char* appType, LaunchMode launchMode)
367 _ERR("CoreRuntime is already initialized");
371 // Intiailize ecore first (signal handlers, etc.) before runtime init.
374 // set language environment to support ICU
378 env = getenv("CORECLR_ENABLE_PROFILING");
379 if (env != nullptr && !strcmp(env, "1")) {
380 _INFO("profiling mode on");
381 __isProfileMode = true;
384 // plugin initialize should be called before creating threads.
385 // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
386 // When attaching to a secure zone, if there is a created thread, it will failed.
387 // So, plugin initialize should be called before creating threads.
388 if (initializePluginManager(appType) < 0) {
389 _ERR("Failed to initialize PluginManager");
392 // checkInjection checks dotnet-launcher run mode
393 // At the moment, this mechanism is used only when the Memory Profiler is started.
394 int res = checkInjection();
396 _ERR("Failed to initnialize Memory Profiler");
401 // libunwind library is used to unwind stack frame, but libunwind for ARM
402 // does not support ARM vfpv3/NEON registers in DWARF format correctly.
403 // Therefore let's disable stack unwinding using DWARF information
404 // See https://github.com/dotnet/coreclr/issues/6698
406 // libunwind use following methods to unwind stack frame.
407 // UNW_ARM_METHOD_ALL 0xFF
408 // UNW_ARM_METHOD_DWARF 0x01
409 // UNW_ARM_METHOD_FRAME 0x02
410 // UNW_ARM_METHOD_EXIDX 0x04
411 putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
414 // Enable diagnostics.
415 // clr create clr-debug-pipe-xxx and dotnet-diagnostics-xxx file under /tmp dir.
416 putenv(const_cast<char *>("COMPlus_EnableDiagnostics=1"));
418 // Write Debug.WriteLine to stderr
419 putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
421 #ifdef USE_DEFAULT_BASE_ADDR
422 putenv(const_cast<char *>("COMPlus_UseDefaultBaseAddr=1"));
423 #endif // USE_DEFAULT_BASE_ADDR
425 // read string from external file and set them to environment value.
428 if (initializePathManager(std::string(), std::string(), std::string()) < 0) {
429 _ERR("Failed to initialize PathManager");
433 if (!pluginHasLogControl()) {
434 if (initializeLogManager() < 0) {
435 _ERR("Failed to initnialize LogManager");
440 std::string libCoreclr(concatPath(getRuntimeDir(), "libcoreclr.so"));
442 __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
443 if (__coreclrLib == nullptr) {
444 char *err = dlerror();
445 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
446 if (access(libCoreclr.c_str(), R_OK) == -1)
447 _ERR("access '%s': %s\n", libCoreclr.c_str(), strerror(errno));
451 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
453 variable = (type)dlsym(__coreclrLib, name); \
454 if (variable == nullptr) { \
455 _ERR(name " is not found in the libcoreclr.so"); \
460 CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
461 CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
462 CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
463 CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
465 #undef CORELIB_RETURN_IF_NOSYM
467 _INFO("libcoreclr dlopen and dlsym success");
469 // Set environment for System.Environment.SpecialFolder
470 // Below function creates dbus connection by callging storage API.
471 // If dbus connection is created bofere fork(), forked process cannot use dbus.
472 // To avoid gdbus blocking issue, below function should be called after fork()
473 initEnvForSpecialFolder();
475 __fd = open("/proc/self", O_DIRECTORY);
477 _ERR("Failed to open /proc/self");
481 std::string tpa = getTPA();
482 std::string runtimeDir = getRuntimeDir();
483 std::string appName = std::string("dotnet-launcher-") + std::to_string(getpid());
484 std::string appRoot = std::string("/proc/self/fd/") + std::to_string(__fd);
485 std::string appBin = concatPath(appRoot, "bin");
486 std::string appLib = concatPath(appRoot, "lib");
487 std::string appTac = concatPath(appBin, TAC_SYMLINK_SUB_DIR);
488 std::string probePath = appRoot + ":" + appBin + ":" + appLib + ":" + appTac;
489 std::string NIprobePath = concatPath(appBin, APP_NI_SUB_DIR) + ":" + concatPath(appLib, APP_NI_SUB_DIR) + ":" + appTac;
490 std::string nativeLibPath = runtimeDir + ":" + __nativeLibDirectory + ":" + getExtraNativeLibDirs(appRoot) + ":" + appBin + ":" + appLib;
492 if (!initializeCoreClr(appName.c_str(), probePath.c_str(), NIprobePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
493 _ERR("Failed to initialize coreclr");
497 int st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Environment", "SetEnvironmentVariable", (void**)&setEnvironmentVariable);
498 if (st < 0 || setEnvironmentVariable == nullptr) {
499 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Environment -> SetEnvironmentVariable failed (0x%08x)", st);
503 __initialized = true;
505 if (launchMode == LaunchMode::loader) {
506 // terminate candidate process if language is changed.
507 // CurrentCulture created for preloaded dlls should be updated.
508 vconf_notify_key_changed(VCONFKEY_LANGSET, langChangedCB, NULL);
511 preload(); // Preload common managed code
514 _INFO("CoreRuntime initialize success");
519 void CoreRuntime::finalize()
521 if (!__initialized) {
522 _ERR("Runtime is not initialized");
526 // call plugin finalize function to notify finalize to plugin
527 // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
530 // ignore the signal generated by an exception that occurred during shutdown
531 checkOnTerminate = true;
533 // workaround : to prevent crash while process terminate on profiling mode,
534 // kill process immediately.
535 // see https://github.com/dotnet/coreclr/issues/26687
536 if (__isProfileMode) {
537 _INFO("shutdown process immediately.");
541 if (__hostHandle != nullptr) {
542 int st = shutdown(__hostHandle, __domainId);
544 _ERR("shutdown core clr fail! (0x%08x)", st);
545 __hostHandle = nullptr;
548 if (__coreclrLib != nullptr) {
549 if (dlclose(__coreclrLib) != 0) {
550 _ERR("libcoreclr.so close failed");
553 __coreclrLib = nullptr;
556 finalizePluginManager();
557 finalizePathManager();
561 _INFO("CoreRuntime finalized");
564 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
566 if (!__initialized) {
567 _ERR("Runtime is not initialized");
571 if (path == nullptr) {
572 _ERR("executable path is null");
577 _ERR("File not exist : %s", path);
581 // launchpad override stdout and stderr to journalctl before launch application.
582 // we have to re-override that to input pipe for logging thread.
583 // if LogManager is not initialized, below redirectFD will return 0;
584 if (redirectFD() < 0) {
585 _ERR("Failed to redirect FD");
589 // VD has their own signal handler.
590 if (!pluginHasLogControl()) {
591 registerSigHandler();
594 pluginSetAppInfo(appId, path);
596 // override root path for application launch mode (candidate / standalone mode)
598 int fd2 = open(root, O_DIRECTORY);
599 dup3(fd2, __fd, O_CLOEXEC);
604 // set application data path to coreclr environment.
605 // application data path can be changed by owner. So, we have to set data path just before launching.
606 char* localDataPath = app_get_data_path();
607 if (localDataPath != nullptr) {
608 setEnvironmentVariable("XDG_DATA_HOME", localDataPath);
612 vconf_ignore_key_changed(VCONFKEY_LANGSET, langChangedCB);
614 pluginBeforeExecute();
616 _INFO("execute assembly : %s", path);
618 unsigned int ret = 0;
619 int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
621 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
625 } // namespace dotnetcore
626 } // namespace runtime