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"
50 namespace dotnetcore {
52 #if defined (__aarch64__)
53 #define ARCHITECTURE_IDENTIFIER "arm64"
54 const static std::vector<std::string> RID_FALLBACK_GRAPH =
55 {"linux-arm64", "linux", "unix-arm64", "unix", "any", "base"};
57 #elif defined (__arm__)
58 #define ARCHITECTURE_IDENTIFIER "arm"
59 const static std::vector<std::string> RID_FALLBACK_GRAPH =
60 {"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"};
62 #elif defined (__x86_64__)
63 #define ARCHITECTURE_IDENTIFIER "x64"
64 const static std::vector<std::string> RID_FALLBACK_GRAPH =
65 {"linux-x64", "linux", "unix-x64", "unix", "any", "base"};
67 #elif defined (__i386__)
68 #define ARCHITECTURE_IDENTIFIER "x86"
69 const static std::vector<std::string> RID_FALLBACK_GRAPH =
70 {"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"};
73 #error "Unknown target"
76 static std::string getExtraNativeLibDirs(const std::string& appRoot)
78 std::string candidate;
79 for (unsigned int i = 0; i < RID_FALLBACK_GRAPH.size(); i++) {
80 if(!candidate.empty()) {
83 candidate += concatPath(appRoot, "bin/runtimes/" + RID_FALLBACK_GRAPH[i] + "/native");
86 candidate = candidate + ":" + concatPath(appRoot, "lib/" ARCHITECTURE_IDENTIFIER);
87 if (!strncmp(ARCHITECTURE_IDENTIFIER, "arm64", 5)) {
88 candidate = candidate + ":" + concatPath(appRoot, "lib/aarch64");
95 static std::vector<std::string> __envList;
97 static void setEnvFromFile()
100 std::ifstream inFile(ENV_FILE_PATH);
105 _INFO("coreclr_env.list is found");
108 std::istringstream ss(envList);
111 while (std::getline(ss, token, ':')) {
112 if (!token.empty()) {
113 __envList.push_back(token);
117 for (unsigned int i = 0; i < __envList.size(); i++) {
118 putenv(const_cast<char *>(__envList[i].c_str()));
121 _INFO("coreclr_env.list file is not found. skip");
125 #define _unused(x) ((void)(x))
127 struct sigaction sig_abrt_new;
128 struct sigaction sig_abrt_old;
130 static bool checkOnSigabrt = false;
131 static bool checkOnTerminate = false;
133 static void onSigabrt(int signum)
135 // use unused variable to avoid build warning
136 ssize_t ret = write(STDERR_FILENO, "onSigabrt called\n", 17);
138 if (checkOnTerminate) {
139 ret = write(STDERR_FILENO, "onSigabrt called while terminate. go to exit\n", 45);
144 if (checkOnSigabrt) {
145 ret = write(STDERR_FILENO, "onSigabrt called again. go to exit\n", 35);
150 if (hasException()) {
151 ret = write(STDERR_FILENO, "******************************************************\n", 55);
152 ret = write(STDERR_FILENO, "Unhandled exception is occured. check application code\n", 55);
153 ret = write(STDERR_FILENO, "******************************************************\n", 55);
156 checkOnSigabrt = true;
157 if (sigaction(SIGABRT, &sig_abrt_old, NULL) == 0) {
158 if (raise(signum) < 0) {
159 ret = write(STDERR_FILENO, "Fail to raise SIGABRT\n", 22);
162 ret = write(STDERR_FILENO, "Fail to set original SIGABRT handler\n", 37);
167 static void registerSigHandler()
169 sig_abrt_new.sa_handler = onSigabrt;
170 if (sigemptyset(&sig_abrt_new.sa_mask) != 0) {
171 _ERR("Fail to sigemptyset");
174 if (sigaction(SIGABRT, &sig_abrt_new, &sig_abrt_old) < 0) {
175 _ERR("Fail to add sig handler");
179 static bool storage_cb(int id, storage_type_e type, storage_state_e state, const char *path, void *user_data)
181 int* tmp = (int*)user_data;
182 if (type == STORAGE_TYPE_INTERNAL)
191 static void initEnvForSpecialFolder()
197 error = storage_foreach_device_supported(storage_cb, &storageId);
198 if (error != STORAGE_ERROR_NONE) {
202 error = storage_get_directory(storageId, STORAGE_DIRECTORY_IMAGES, &path);
203 if (error == STORAGE_ERROR_NONE && path != NULL) {
204 setenv("XDG_PICTURES_DIR", const_cast<char *>(path), 1);
209 error = storage_get_directory(storageId, STORAGE_DIRECTORY_MUSIC, &path);
210 if (error == STORAGE_ERROR_NONE && path != NULL) {
211 setenv("XDG_MUSIC_DIR", const_cast<char *>(path), 1);
216 error = storage_get_directory(storageId, STORAGE_DIRECTORY_VIDEOS, &path);
217 if (error == STORAGE_ERROR_NONE && path != NULL) {
218 setenv("XDG_VIDEOS_DIR", const_cast<char *>(path), 1);
224 void CoreRuntime::preloadTypes()
226 const static std::string initDllPath = "/usr/share/dotnet.tizen/framework/Tizen.Init.dll";
227 if (!isFileExist(initDllPath)) {
228 _ERR("Failed to locate Tizen.Init.dll");
232 typedef void (*InitDelegate)();
233 InitDelegate initDelegate;
235 int ret = createDelegate(__hostHandle,
238 "Tizen.Init.TypeLoader",
240 (void**)&initDelegate);
243 _ERR("Failed to create delegate for PreloadTypes (0x%08x)", ret);
249 CoreRuntime::CoreRuntime(const char* mode) :
250 initializeClr(nullptr),
251 executeAssembly(nullptr),
253 createDelegate(nullptr),
254 setEnvironmentVariable(nullptr),
255 preloadAssembly(nullptr),
256 __coreclrLib(nullptr),
257 __hostHandle(nullptr),
260 __initialized(false),
261 __isProfileMode(false)
263 _INFO("Constructor called!!");
266 env = getenv("CORECLR_ENABLE_PROFILING");
267 if (env != nullptr && !strcmp(env, "1")) {
268 _INFO("profiling mode on");
269 __isProfileMode = true;
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()
289 // workaround : to prevent crash while process terminate on profiling mode,
290 // kill process immediately.
291 // see https://github.com/dotnet/coreclr/issues/26687
292 if (__isProfileMode) {
293 _INFO("shutdown process immediately.");
300 int CoreRuntime::preinitialize(bool standalone)
302 // checkInjection checks dotnet-launcher run mode
303 // At the moment, this mechanism is used only when the Memory Profiler is started.
304 int res = checkInjection();
306 _ERR("Failed to initnialize Memory Profiler");
310 #define __STR(x) __XSTR(x)
312 #ifdef NATIVE_LIB_DIR
313 __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
320 // libunwind library is used to unwind stack frame, but libunwind for ARM
321 // does not support ARM vfpv3/NEON registers in DWARF format correctly.
322 // Therefore let's disable stack unwinding using DWARF information
323 // See https://github.com/dotnet/coreclr/issues/6698
325 // libunwind use following methods to unwind stack frame.
326 // UNW_ARM_METHOD_ALL 0xFF
327 // UNW_ARM_METHOD_DWARF 0x01
328 // UNW_ARM_METHOD_FRAME 0x02
329 // UNW_ARM_METHOD_EXIDX 0x04
330 putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
333 // Disable debug pipes and semaphores creation in case of non-standlone mode
335 putenv(const_cast<char *>("COMPlus_EnableDiagnostics=0"));
337 // Write Debug.WriteLine to stderr
338 putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
340 #ifdef USE_DEFAULT_BASE_ADDR
341 putenv(const_cast<char *>("COMPlus_UseDefaultBaseAddr=1"));
342 #endif // USE_DEFAULT_BASE_ADDR
344 // read string from external file and set them to environment value.
347 // Set environment for System.Environment.SpecialFolder
348 initEnvForSpecialFolder();
350 if (initializePathManager(std::string(), std::string(), std::string()) < 0) {
351 _ERR("Failed to initialize PathManager");
355 std::string libCoreclr(concatPath(getRuntimeDir(), "libcoreclr.so"));
357 __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
358 if (__coreclrLib == nullptr) {
359 char *err = dlerror();
360 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
361 if (access(libCoreclr.c_str(), R_OK) == -1)
362 _ERR("access '%s': %s\n", libCoreclr.c_str(), strerror(errno));
366 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
368 variable = (type)dlsym(__coreclrLib, name); \
369 if (variable == nullptr) { \
370 _ERR(name " is not found in the libcoreclr.so"); \
375 CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
376 CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
377 CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
378 CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
379 CORELIB_RETURN_IF_NOSYM(coreclr_preload_assembly_ptr, preloadAssembly, "coreclr_preload_assembly");
381 #undef CORELIB_RETURN_IF_NOSYM
383 _INFO("libcoreclr dlopen and dlsym success");
385 #define PRELOAD_IMAGE(path) \
387 int st = preloadAssembly(path); \
389 _ERR("preload of %s failed! (0x%08x)", path, st); \
391 _DBG("preload of %s succeded", path); \
396 std::ifstream preloadList(AOT_PRELOAD_PATH);
399 while (getline(preloadList, path)) {
400 PRELOAD_IMAGE(absolutePath(path).c_str());
410 int CoreRuntime::initialize(bool standalone)
413 #define __STR(x) __XSTR(x)
415 #ifdef NATIVE_LIB_DIR
416 __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
422 if (__enableLogManager) {
423 if (initializeLogManager() < 0) {
424 _ERR("Failed to initnialize LogManager");
428 if (redirectFD() < 0) {
429 _ERR("Failed to redirect FD");
433 if (runLoggingThread() < 0) {
434 _ERR("Failed to create and run logging thread to redicrect log");
442 fd = open("/proc/self", O_DIRECTORY);
443 std::string appRoot = std::string("/proc/self/fd/") + std::to_string(fd);
444 std::string appBin = concatPath(appRoot, "bin");
445 std::string appLib = concatPath(appRoot, "lib");
446 std::string appTac = concatPath(appBin, TAC_SYMLINK_SUB_DIR);
447 std::string probePath = appBin + ":" + appLib + ":" + appTac;
448 std::string NIprobePath = concatPath(appBin, APP_NI_SUB_DIR) + ":" + concatPath(appLib, APP_NI_SUB_DIR) + ":" + appTac;
449 std::string tpa = getTPA();
450 std::string runtimeDir = getRuntimeDir();
451 std::string nativeLibPath = getExtraNativeLibDirs(appRoot) + ":" + appBin + ":" + appLib + ":" + __nativeLibDirectory + ":" + runtimeDir;
452 std::string appName = std::string("dotnet-launcher-") + std::to_string(getpid());
454 if (!initializeCoreClr(appName.c_str(), probePath.c_str(), NIprobePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
455 _ERR("Failed to initialize coreclr");
459 int st = createDelegate(__hostHandle, __domainId, "Dotnet.Launcher", "Dotnet.Launcher.Environment", "SetEnvironmentVariable", (void**)&setEnvironmentVariable);
460 if (st < 0 || setEnvironmentVariable == nullptr) {
461 _ERR("Create delegate for Dotnet.Launcher.dll -> Dotnet.Launcher.Environment -> SetEnvironmentVariable failed (0x%08x)", st);
465 __initialized = true;
469 // Preload common managed code.
472 // This redundant call effectively reduces JIT overhead at launch time.
473 setEnvironmentVariable("XDG_DATA_HOME", "/");
476 _INFO("CoreRuntime initialize success");
481 bool CoreRuntime::initializeCoreClr(const char* appId,
482 const char* assemblyProbePaths,
483 const char* NIProbePaths,
484 const char* pinvokeProbePaths,
487 const char *propertyKeys[] = {
488 "TRUSTED_PLATFORM_ASSEMBLIES",
491 "NATIVE_DLL_SEARCH_DIRECTORIES",
492 "AppDomainCompatSwitch"
495 const char *propertyValues[] = {
500 "UseLatestBehaviorWhenTFMNotSpecified"
503 std::string selfPath = readSelfPath();
505 int st = initializeClr(selfPath.c_str(),
507 sizeof(propertyKeys) / sizeof(propertyKeys[0]),
514 _ERR("initialize core clr fail! (0x%08x)", st);
518 pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
520 _INFO("Initialize core clr success");
524 void CoreRuntime::dispose()
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 if (__hostHandle != nullptr) {
534 int st = shutdown(__hostHandle, __domainId);
536 _ERR("shutdown core clr fail! (0x%08x)", st);
537 __hostHandle = nullptr;
540 if (__coreclrLib != nullptr) {
541 if (dlclose(__coreclrLib) != 0) {
542 _ERR("libcoreclr.so close failed");
545 __coreclrLib = nullptr;
548 finalizePluginManager();
549 finalizePathManager();
553 _INFO("Dotnet runtime disposed");
556 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
558 if (!__initialized) {
559 _ERR("Runtime is not initialized");
563 if (path == nullptr) {
564 _ERR("executable path is null");
568 if (!isFileExist(path)) {
569 _ERR("File not exist : %s", path);
573 if (__enableLogManager) {
574 // launchpad override stdout and stderr to journalctl before launch application.
575 // we have to re-override that to input pipe for logging thread.
576 if (redirectFD() < 0) {
577 _ERR("Failed to redirect FD");
581 registerSigHandler();
584 pluginSetAppInfo(appId, path);
586 int fd2 = open(root, O_DIRECTORY);
587 dup3(fd2, fd, O_CLOEXEC);
591 // set application data path to coreclr environment.
592 // application data path can be changed by owner. So, we have to set data path just before launching.
593 char* localDataPath = app_get_data_path();
594 if (localDataPath != nullptr) {
595 setEnvironmentVariable("XDG_DATA_HOME", localDataPath);
599 pluginBeforeExecute();
601 _INFO("execute assembly : %s", path);
603 unsigned int ret = 0;
604 int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
606 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
610 } // namespace dotnetcore
611 } // namespace runtime