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>
37 #include <app_common.h>
39 #include "injection.h"
43 #include "dotnet_launcher.h"
44 #include "plugin_manager.h"
45 #include "path_manager.h"
46 #include "log_manager.h"
48 #define PLUGIN_PATH "/usr/share/dotnet.tizen/lib/libdotnet_plugin.so"
49 #define ENV_FILE_PATH "/usr/share/dotnet.tizen/lib/coreclr_env.list"
53 namespace dotnetcore {
55 #if defined (__aarch64__)
56 #define ARCHITECTURE_IDENTIFIER "arm64"
57 const static std::vector<std::string> RID_FALLBACK_GRAPH =
58 {"linux-arm64", "linux", "unix-arm64", "unix", "any", "base"};
60 #elif defined (__arm__)
61 #define ARCHITECTURE_IDENTIFIER "arm"
62 const static std::vector<std::string> RID_FALLBACK_GRAPH =
63 {"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"};
65 #elif defined (__x86_64__)
66 #define ARCHITECTURE_IDENTIFIER "x64"
67 const static std::vector<std::string> RID_FALLBACK_GRAPH =
68 {"linux-x64", "linux", "unix-x64", "unix", "any", "base"};
70 #elif defined (__i386__)
71 #define ARCHITECTURE_IDENTIFIER "x86"
72 const static std::vector<std::string> RID_FALLBACK_GRAPH =
73 {"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"};
76 #error "Unknown target"
79 static std::string getExtraNativeLibDirs(const std::string& appRoot)
81 std::string candidate;
82 for (unsigned int i = 0; i < RID_FALLBACK_GRAPH.size(); i++) {
83 if(!candidate.empty()) {
86 candidate += concatPath(appRoot, "bin/runtimes/" + RID_FALLBACK_GRAPH[i] + "/native");
89 candidate = candidate + ":" + concatPath(appRoot, "lib/" ARCHITECTURE_IDENTIFIER);
90 if (!strncmp(ARCHITECTURE_IDENTIFIER, "arm64", 5)) {
91 candidate = candidate + ":" + concatPath(appRoot, "lib/aarch64");
98 static std::vector<std::string> __envList;
100 static void setEnvFromFile()
103 std::ifstream inFile(ENV_FILE_PATH);
108 _INFO("coreclr_env.list is found");
111 std::istringstream ss(envList);
114 while (std::getline(ss, token, ':')) {
115 if (!token.empty()) {
116 __envList.push_back(token);
120 for (unsigned int i = 0; i < __envList.size(); i++) {
121 putenv(const_cast<char *>(__envList[i].c_str()));
124 _INFO("coreclr_env.list file is not found. skip");
128 #define _unused(x) ((void)(x))
130 struct sigaction sig_abrt_new;
131 struct sigaction sig_abrt_old;
133 static bool checkOnSigabrt = false;
134 static bool checkOnTerminate = false;
136 static void onSigabrt(int signum)
138 // use unused variable to avoid build warning
139 ssize_t ret = write(STDERR_FILENO, "onSigabrt called\n", 17);
141 if (checkOnTerminate) {
142 ret = write(STDERR_FILENO, "onSigabrt called while terminate. go to exit\n", 45);
147 if (checkOnSigabrt) {
148 ret = write(STDERR_FILENO, "onSigabrt called again. go to exit\n", 35);
153 if (hasException()) {
154 ret = write(STDERR_FILENO, "******************************************************\n", 55);
155 ret = write(STDERR_FILENO, "Unhandled exception is occured. check application code\n", 55);
156 ret = write(STDERR_FILENO, "******************************************************\n", 55);
159 checkOnSigabrt = true;
160 if (sigaction(SIGABRT, &sig_abrt_old, NULL) == 0) {
161 if (raise(signum) < 0) {
162 ret = write(STDERR_FILENO, "Fail to raise SIGABRT\n", 22);
165 ret = write(STDERR_FILENO, "Fail to set original SIGABRT handler\n", 37);
170 static void registerSigHandler()
172 sig_abrt_new.sa_handler = onSigabrt;
173 if (sigemptyset(&sig_abrt_new.sa_mask) != 0) {
174 _ERR("Fail to sigemptyset");
177 if (sigaction(SIGABRT, &sig_abrt_new, &sig_abrt_old) < 0) {
178 _ERR("Fail to add sig handler");
182 static bool storage_cb(int id, storage_type_e type, storage_state_e state, const char *path, void *user_data)
184 int* tmp = (int*)user_data;
185 if (type == STORAGE_TYPE_INTERNAL)
194 static void initEnvForSpecialFolder()
200 error = storage_foreach_device_supported(storage_cb, &storageId);
201 if (error != STORAGE_ERROR_NONE) {
205 error = storage_get_directory(storageId, STORAGE_DIRECTORY_IMAGES, &path);
206 if (error == STORAGE_ERROR_NONE && path != NULL) {
207 setenv("XDG_PICTURES_DIR", const_cast<char *>(path), 1);
212 error = storage_get_directory(storageId, STORAGE_DIRECTORY_MUSIC, &path);
213 if (error == STORAGE_ERROR_NONE && path != NULL) {
214 setenv("XDG_MUSIC_DIR", const_cast<char *>(path), 1);
219 error = storage_get_directory(storageId, STORAGE_DIRECTORY_VIDEOS, &path);
220 if (error == STORAGE_ERROR_NONE && path != NULL) {
221 setenv("XDG_VIDEOS_DIR", const_cast<char *>(path), 1);
227 static std::u16string utf8ToUtf16(char* str)
229 std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
230 return convert.from_bytes(str);
233 void CoreRuntime::preloadTypes()
235 const static std::string initDllPath = "/usr/share/dotnet.tizen/framework/Tizen.Init.dll";
236 if (!isFileExist(initDllPath)) {
237 _ERR("Failed to locate Tizen.Init.dll");
241 typedef void (*InitDelegate)();
242 InitDelegate initDelegate;
244 int ret = createDelegate(__hostHandle,
247 "Tizen.Init.TypeLoader",
249 (void**)&initDelegate);
252 _ERR("Failed to create delegate for PreloadTypes (0x%08x)", ret);
258 CoreRuntime::CoreRuntime(const char* mode) :
259 initializeClr(nullptr),
260 executeAssembly(nullptr),
262 createDelegate(nullptr),
263 setEnvironmentVariable(nullptr),
264 __coreclrLib(nullptr),
265 __hostHandle(nullptr),
270 _INFO("Constructor called!!");
272 // plugin initialize should be called before start loader mainloop.
273 // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
274 // When attaching to a secure zone, if there is a created thread, it will failed.
275 // So, plugin initialize should be called before mainloop start.
276 if (initializePluginManager(mode) < 0) {
277 _ERR("Failed to initialize PluginManager");
280 if (pluginHasLogControl()) {
281 __enableLogManager = false;
283 __enableLogManager = true;
287 CoreRuntime::~CoreRuntime()
292 int CoreRuntime::initialize(bool standalone)
294 // checkInjection checks dotnet-launcher run mode
295 // At the moment, this mechanism is used only when the Memory Profiler is started.
296 int res = checkInjection();
298 _ERR("Failed to initnialize Memory Profiler");
302 #define __STR(x) __XSTR(x)
304 #ifdef NATIVE_LIB_DIR
305 __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
312 // libunwind library is used to unwind stack frame, but libunwind for ARM
313 // does not support ARM vfpv3/NEON registers in DWARF format correctly.
314 // Therefore let's disable stack unwinding using DWARF information
315 // See https://github.com/dotnet/coreclr/issues/6698
317 // libunwind use following methods to unwind stack frame.
318 // UNW_ARM_METHOD_ALL 0xFF
319 // UNW_ARM_METHOD_DWARF 0x01
320 // UNW_ARM_METHOD_FRAME 0x02
321 // UNW_ARM_METHOD_EXIDX 0x04
322 putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
325 // Disable debug pipes and semaphores creation in case of non-standlone mode
327 putenv(const_cast<char *>("COMPlus_EnableDiagnostics=0"));
329 // Write Debug.WriteLine to stderr
330 putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
332 // read string from external file and set them to environment value.
335 // Set environment for System.Environment.SpecialFolder
336 initEnvForSpecialFolder();
338 if (initializePathManager(std::string(), std::string(), std::string()) < 0) {
339 _ERR("Failed to initialize PathManager");
343 if (__enableLogManager) {
344 if (initializeLogManager() < 0) {
345 _ERR("Failed to initnialize LogManager");
349 if (redirectFD() < 0) {
350 _ERR("Failed to redirect FD");
354 if (runLoggingThread() < 0) {
355 _ERR("Failed to create and run logging thread to redicrect log");
360 std::string libCoreclr(concatPath(getRuntimeDir(), "libcoreclr.so"));
362 __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
363 if (__coreclrLib == nullptr) {
364 char *err = dlerror();
365 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
369 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
371 variable = (type)dlsym(__coreclrLib, name); \
372 if (variable == nullptr) { \
373 _ERR(name " is not found in the libcoreclr.so"); \
378 CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
379 CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
380 CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
381 CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
382 CORELIB_RETURN_IF_NOSYM(set_environment_variable_ptr, setEnvironmentVariable, "SetEnvironmentVariableW");
384 #undef CORELIB_RETURN_IF_NOSYM
386 _INFO("libcoreclr dlopen and dlsym success");
391 fd = open("/proc/self", O_DIRECTORY);
392 std::string appRoot = std::string("/proc/self/fd/") + std::to_string(fd);
393 std::string appBin = concatPath(appRoot, "bin");
394 std::string appLib = concatPath(appRoot, "lib");
395 std::string appTAC = concatPath(appBin, "TAC.Release");
396 std::string probePath = appBin + ":" + appLib + ":" + appTAC;
397 std::string tpa = getTPA();
398 std::string nativeLibPath = getExtraNativeLibDirs(appRoot) + ":" + appBin + ":" + appLib + ":" + __nativeLibDirectory;
399 std::string appName = std::string("dotnet-launcher-") + std::to_string(getpid());
401 if (!initializeCoreClr(appName.c_str(), probePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
402 _ERR("Failed to initialize coreclr");
406 __initialized = true;
410 preloadTypes(); // Preload common managed code
413 _INFO("CoreRuntime initialize success");
418 bool CoreRuntime::initializeCoreClr(const char* appId,
419 const char* assemblyProbePaths,
420 const char* pinvokeProbePaths,
423 const char *propertyKeys[] = {
424 "TRUSTED_PLATFORM_ASSEMBLIES",
427 "NATIVE_DLL_SEARCH_DIRECTORIES",
428 "AppDomainCompatSwitch"
431 const char *propertyValues[] = {
436 "UseLatestBehaviorWhenTFMNotSpecified"
439 std::string selfPath = readSelfPath();
441 int st = initializeClr(selfPath.c_str(),
443 sizeof(propertyKeys) / sizeof(propertyKeys[0]),
450 _ERR("initialize core clr fail! (0x%08x)", st);
454 pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
456 _INFO("Initialize core clr success");
460 void CoreRuntime::dispose()
462 // call plugin finalize function to notify finalize to plugin
463 // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
466 // ignore the signal generated by an exception that occurred during shutdown
467 checkOnTerminate = true;
469 if (__hostHandle != nullptr) {
470 int st = shutdown(__hostHandle, __domainId);
472 _ERR("shutdown core clr fail! (0x%08x)", st);
473 __hostHandle = nullptr;
476 if (__coreclrLib != nullptr) {
477 if (dlclose(__coreclrLib) != 0) {
478 _ERR("libcoreclr.so close failed");
481 __coreclrLib = nullptr;
484 finalizePluginManager();
485 finalizePathManager();
489 _INFO("Dotnet runtime disposed");
492 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
494 if (!__initialized) {
495 _ERR("Runtime is not initialized");
499 if (path == nullptr) {
500 _ERR("executable path is null");
504 if (!isFileExist(path)) {
505 _ERR("File not exist : %s", path);
509 if (__enableLogManager) {
510 // launchpad override stdout and stderr to journalctl before launch application.
511 // we have to re-override that to input pipe for logging thread.
512 if (redirectFD() < 0) {
513 _ERR("Failed to redirect FD");
517 registerSigHandler();
520 pluginSetAppInfo(appId, path);
522 int fd2 = open(root, O_DIRECTORY);
523 dup3(fd2, fd, O_CLOEXEC);
527 // set application data path to coreclr environment.
528 // application data path can be changed by owner. So, we have to set data path just before launching.
529 char* localDataPath = app_get_data_path();
530 if (localDataPath != nullptr) {
531 std::u16string envval = utf8ToUtf16(localDataPath);
533 if (!setEnvironmentVariable(u"XDG_DATA_HOME", envval.c_str())) {
534 _ERR("Failed to set XDG_DATA_HOME");
540 pluginBeforeExecute();
542 _INFO("execute assembly : %s", path);
544 unsigned int ret = 0;
545 int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
547 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
551 } // namespace dotnetcore
552 } // namespace runtime