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 "dotnet_launcher.h"
46 #include "plugin_manager.h"
47 #include "path_manager.h"
48 #include "log_manager.h"
52 namespace dotnetcore {
54 #if defined (__aarch64__)
55 #define ARCHITECTURE_IDENTIFIER "arm64"
57 #elif defined (__arm__)
58 #define ARCHITECTURE_IDENTIFIER "armel"
60 #elif defined (__x86_64__)
61 #define ARCHITECTURE_IDENTIFIER "x64"
63 #elif defined (__i386__)
64 #define ARCHITECTURE_IDENTIFIER "x86"
67 #error "Unknown target"
70 static const char* __TIZEN_RID_VERSION_KEY = "db/dotnet/tizen_rid_version";
72 // The sequence of RID_FALLBACK graphs must be:
73 // 1. Tizen + Version + Architecture
75 // 3. OS(tizen, linux, unix) + Architecture
76 // 4. OS(tizen, linux, unix)
78 static std::string getExtraNativeLibDirs(const std::string& appRoot)
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);
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]));
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]));
99 RID_FALLBACK_GRAPH.push_back("any");
100 RID_FALLBACK_GRAPH.push_back("base");
102 std::string candidate;
103 for (unsigned int i = 0; i < RID_FALLBACK_GRAPH.size(); i++) {
104 if (!candidate.empty()) {
107 candidate += concatPath(appRoot, "bin/runtimes/" + RID_FALLBACK_GRAPH[i] + "/native");
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");
121 static std::vector<std::string> __envList;
123 static void setEnvFromFile()
126 std::ifstream inFile(ENV_FILE_PATH);
131 _INFO("coreclr_env.list is found");
134 while (std::getline(inFile, token, '\n')) {
135 if (!token.empty()) {
136 __envList.push_back(token);
140 for (unsigned int i = 0; i < __envList.size(); i++) {
141 putenv(const_cast<char *>(__envList[i].c_str()));
144 _INFO("coreclr_env.list file is not found. skip");
148 #define _unused(x) ((void)(x))
150 struct sigaction sig_abrt_new;
151 struct sigaction sig_abrt_old;
153 static bool checkOnSigabrt = false;
154 static bool checkOnTerminate = false;
156 static void onSigabrt(int signum)
158 // use unused variable to avoid build warning
159 ssize_t ret = write(STDERR_FILENO, "onSigabrt called\n", 17);
161 if (checkOnTerminate) {
162 ret = write(STDERR_FILENO, "onSigabrt called while terminate. go to exit\n", 45);
167 if (checkOnSigabrt) {
168 ret = write(STDERR_FILENO, "onSigabrt called again. go to exit\n", 35);
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);
179 ret = write(STDERR_FILENO, "Fail to set original SIGABRT handler\n", 37);
184 static void registerSigHandler()
186 sig_abrt_new.sa_handler = onSigabrt;
187 if (sigemptyset(&sig_abrt_new.sa_mask) != 0) {
188 _ERR("Fail to sigemptyset");
191 if (sigaction(SIGABRT, &sig_abrt_new, &sig_abrt_old) < 0) {
192 _ERR("Fail to add sig handler");
196 static bool storage_cb(int id, storage_type_e type, storage_state_e state, const char *path, void *user_data)
198 int* tmp = (int*)user_data;
199 if (type == STORAGE_TYPE_INTERNAL)
208 static void initEnvForSpecialFolder()
214 error = storage_foreach_device_supported(storage_cb, &storageId);
215 if (error != STORAGE_ERROR_NONE) {
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);
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);
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);
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)
245 _INFO("terminiate candidate process to update language.");
249 static void setLang()
251 char* lang = vconf_get_str(VCONFKEY_LANGSET);
253 _ERR("Fail to get language from vconf");
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));
269 void CoreRuntime::preload()
271 typedef void (*PreloadDelegate)();
272 PreloadDelegate preloadDelegate;
274 int ret = createDelegate(__hostHandle,
277 "Tizen.Runtime.Preloader",
279 (void**)&preloadDelegate);
282 _ERR("Failed to create delegate for Tizen.Runtime Preload (0x%08x)", ret);
288 CoreRuntime::CoreRuntime(const char* mode) :
289 initializeClr(nullptr),
290 executeAssembly(nullptr),
292 createDelegate(nullptr),
293 setEnvironmentVariable(nullptr),
294 __coreclrLib(nullptr),
295 __hostHandle(nullptr),
298 __initialized(false),
299 __isProfileMode(false)
301 _INFO("Constructor called!!");
303 // Intiailize ecore first (signal handlers, etc.) before runtime init.
306 // set language environment to support ICU
310 env = getenv("CORECLR_ENABLE_PROFILING");
311 if (env != nullptr && !strcmp(env, "1")) {
312 _INFO("profiling mode on");
313 __isProfileMode = true;
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");
325 CoreRuntime::~CoreRuntime()
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.");
338 int CoreRuntime::initialize(LaunchMode launchMode)
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();
344 _ERR("Failed to initnialize Memory Profiler");
348 #define __STR(x) __XSTR(x)
350 #ifdef NATIVE_LIB_DIR
351 __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
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
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"));
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"));
375 // Write Debug.WriteLine to stderr
376 putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
378 #ifdef USE_DEFAULT_BASE_ADDR
379 putenv(const_cast<char *>("COMPlus_UseDefaultBaseAddr=1"));
380 #endif // USE_DEFAULT_BASE_ADDR
382 // read string from external file and set them to environment value.
385 if (initializePathManager(std::string(), std::string(), std::string()) < 0) {
386 _ERR("Failed to initialize PathManager");
390 if (!pluginHasLogControl()) {
391 if (initializeLogManager() < 0) {
392 _ERR("Failed to initnialize LogManager");
397 std::string libCoreclr(concatPath(getRuntimeDir(), "libcoreclr.so"));
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));
408 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
410 variable = (type)dlsym(__coreclrLib, name); \
411 if (variable == nullptr) { \
412 _ERR(name " is not found in the libcoreclr.so"); \
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");
422 #undef CORELIB_RETURN_IF_NOSYM
424 _INFO("libcoreclr dlopen and dlsym success");
426 if (launchMode == LaunchMode::loader) {
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);
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();
440 __fd = open("/proc/self", O_DIRECTORY);
442 _ERR("Failed to open /proc/self");
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;
457 if (!initializeCoreClr(appName.c_str(), probePath.c_str(), NIprobePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
458 _ERR("Failed to initialize coreclr");
462 int st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Environment", "SetEnvironmentVariable", (void**)&setEnvironmentVariable);
463 if (st < 0 || setEnvironmentVariable == nullptr) {
464 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Environment -> SetEnvironmentVariable failed (0x%08x)", st);
468 __initialized = true;
470 if (launchMode == LaunchMode::loader) {
471 preload(); // Preload common managed code
474 _INFO("CoreRuntime initialize success");
479 bool CoreRuntime::initializeCoreClr(const char* appId,
480 const char* assemblyProbePaths,
481 const char* NIProbePaths,
482 const char* pinvokeProbePaths,
485 const char *propertyKeys[] = {
486 "TRUSTED_PLATFORM_ASSEMBLIES",
489 "NATIVE_DLL_SEARCH_DIRECTORIES",
490 "AppDomainCompatSwitch"
493 const char *propertyValues[] = {
498 "UseLatestBehaviorWhenTFMNotSpecified"
501 std::string selfPath = readSelfPath();
503 int st = initializeClr(selfPath.c_str(),
505 sizeof(propertyKeys) / sizeof(propertyKeys[0]),
512 _ERR("initialize core clr fail! (0x%08x)", st);
516 pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
518 _INFO("Initialize core clr success");
522 void CoreRuntime::dispose()
524 // call plugin finalize function to notify finalize to plugin
525 // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
528 // ignore the signal generated by an exception that occurred during shutdown
529 checkOnTerminate = true;
531 if (__hostHandle != nullptr) {
532 int st = shutdown(__hostHandle, __domainId);
534 _ERR("shutdown core clr fail! (0x%08x)", st);
535 __hostHandle = nullptr;
538 if (__coreclrLib != nullptr) {
539 if (dlclose(__coreclrLib) != 0) {
540 _ERR("libcoreclr.so close failed");
543 __coreclrLib = nullptr;
546 finalizePluginManager();
547 finalizePathManager();
551 _INFO("Dotnet runtime disposed");
554 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
556 if (!__initialized) {
557 _ERR("Runtime is not initialized");
561 if (path == nullptr) {
562 _ERR("executable path is null");
566 if (!isFileExist(path)) {
567 _ERR("File not exist : %s", path);
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");
579 // VD has their own signal handler.
580 if (!pluginHasLogControl()) {
581 registerSigHandler();
584 pluginSetAppInfo(appId, path);
586 // override root path for application launch mode (candidate / standalone mode)
588 int fd2 = open(root, O_DIRECTORY);
589 dup3(fd2, __fd, O_CLOEXEC);
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);
602 vconf_ignore_key_changed(VCONFKEY_LANGSET, langChangedCB);
604 pluginBeforeExecute();
606 _INFO("execute assembly : %s", path);
608 unsigned int ret = 0;
609 int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
611 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
615 } // namespace dotnetcore
616 } // namespace runtime