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);
234 CoreRuntime::CoreRuntime(const char* mode) :
235 initializeClr(nullptr),
236 executeAssembly(nullptr),
238 createDelegate(nullptr),
239 setEnvironmentVariable(nullptr),
240 __coreclrLib(nullptr),
241 __hostHandle(nullptr),
246 _INFO("Constructor called!!");
248 // plugin initialize should be called before start loader mainloop.
249 // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
250 // When attaching to a secure zone, if there is a created thread, it will failed.
251 // So, plugin initialize should be called before mainloop start.
252 if (initializePluginManager(mode) < 0) {
253 _ERR("Failed to initialize PluginManager");
256 if (pluginHasLogControl()) {
257 __enableLogManager = false;
259 __enableLogManager = true;
263 CoreRuntime::~CoreRuntime()
268 int CoreRuntime::initialize(bool standalone)
270 // checkInjection checks dotnet-launcher run mode,
271 // if it contains DOTNET_LAUNCHER_INJECT variable, it injects library.
272 // At the moment, this mechanism is used only when the Memory Profiler is started.
273 int res = checkInjection();
275 _ERR("Failed to initnialize Memory Profiler");
279 #define __STR(x) __XSTR(x)
281 #ifdef NATIVE_LIB_DIR
282 __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
289 // libunwind library is used to unwind stack frame, but libunwind for ARM
290 // does not support ARM vfpv3/NEON registers in DWARF format correctly.
291 // Therefore let's disable stack unwinding using DWARF information
292 // See https://github.com/dotnet/coreclr/issues/6698
294 // libunwind use following methods to unwind stack frame.
295 // UNW_ARM_METHOD_ALL 0xFF
296 // UNW_ARM_METHOD_DWARF 0x01
297 // UNW_ARM_METHOD_FRAME 0x02
298 // UNW_ARM_METHOD_EXIDX 0x04
299 putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
302 // Disable debug pipes and semaphores creation in case of non-standlone mode
304 putenv(const_cast<char *>("COMPlus_EnableDiagnostics=0"));
306 // Write Debug.WriteLine to stderr
307 putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
309 // read string from external file and set them to environment value.
312 // Set environment for System.Environment.SpecialFolder
313 initEnvForSpecialFolder();
315 if (initializePathManager(std::string(), std::string(), std::string()) < 0) {
316 _ERR("Failed to initialize PathManager");
320 if (__enableLogManager) {
321 if (initializeLogManager() < 0) {
322 _ERR("Failed to initnialize LogManager");
326 if (redirectFD() < 0) {
327 _ERR("Failed to redirect FD");
331 if (runLoggingThread() < 0) {
332 _ERR("Failed to create and run logging thread to redicrect log");
337 std::string libCoreclr(concatPath(getRuntimeDir(), "libcoreclr.so"));
339 __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
340 if (__coreclrLib == nullptr) {
341 char *err = dlerror();
342 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
346 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
348 variable = (type)dlsym(__coreclrLib, name); \
349 if (variable == nullptr) { \
350 _ERR(name " is not found in the libcoreclr.so"); \
355 CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
356 CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
357 CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
358 CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
359 CORELIB_RETURN_IF_NOSYM(set_environment_variable_ptr, setEnvironmentVariable, "SetEnvironmentVariableW");
361 #undef CORELIB_RETURN_IF_NOSYM
363 _INFO("libcoreclr dlopen and dlsym success");
368 fd = open("/proc/self", O_DIRECTORY);
369 std::string appRoot = std::string("/proc/self/fd/") + std::to_string(fd);
370 std::string appBin = concatPath(appRoot, "bin");
371 std::string appLib = concatPath(appRoot, "lib");
372 std::string probePath = appBin + ":" + appLib;
373 std::string tpa = getTPA();
374 std::string nativeLibPath = getExtraNativeLibDirs(appRoot) + ":" + appBin + ":" + appLib + ":" + __nativeLibDirectory;
375 std::string appName = std::string("dotnet-launcher-") + std::to_string(getpid());
377 if (!initializeCoreClr(appName.c_str(), probePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
378 _ERR("Failed to initialize coreclr");
382 __initialized = true;
384 _INFO("CoreRuntime initialize success");
389 bool CoreRuntime::initializeCoreClr(const char* appId,
390 const char* assemblyProbePaths,
391 const char* pinvokeProbePaths,
394 const char *propertyKeys[] = {
395 "TRUSTED_PLATFORM_ASSEMBLIES",
398 "NATIVE_DLL_SEARCH_DIRECTORIES",
399 "AppDomainCompatSwitch"
402 const char *propertyValues[] = {
407 "UseLatestBehaviorWhenTFMNotSpecified"
410 std::string selfPath = readSelfPath();
412 int st = initializeClr(selfPath.c_str(),
414 sizeof(propertyKeys) / sizeof(propertyKeys[0]),
421 _ERR("initialize core clr fail! (0x%08x)", st);
425 pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
427 _INFO("Initialize core clr success");
431 void CoreRuntime::dispose()
433 // call plugin finalize function to notify finalize to plugin
434 // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
437 // ignore the signal generated by an exception that occurred during shutdown
438 checkOnTerminate = true;
440 if (__hostHandle != nullptr) {
441 int st = shutdown(__hostHandle, __domainId);
443 _ERR("shutdown core clr fail! (0x%08x)", st);
444 __hostHandle = nullptr;
447 if (__coreclrLib != nullptr) {
448 if (dlclose(__coreclrLib) != 0) {
449 _ERR("libcoreclr.so close failed");
452 __coreclrLib = nullptr;
455 finalizePluginManager();
456 finalizePathManager();
460 _INFO("Dotnet runtime disposed");
463 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
465 if (!__initialized) {
466 _ERR("Runtime is not initialized");
470 if (path == nullptr) {
471 _ERR("executable path is null");
475 if (!isFileExist(path)) {
476 _ERR("File not exist : %s", path);
480 if (__enableLogManager) {
481 // launchpad override stdout and stderr to journalctl before launch application.
482 // we have to re-override that to input pipe for logging thread.
483 if (redirectFD() < 0) {
484 _ERR("Failed to redirect FD");
488 registerSigHandler();
491 pluginSetAppInfo(appId, path);
493 int fd2 = open(root, O_DIRECTORY);
494 dup3(fd2, fd, O_CLOEXEC);
498 // set application data path to coreclr environment.
499 // application data path can be changed by owner. So, we have to set data path just before launching.
500 char* localDataPath = app_get_data_path();
501 if (localDataPath != nullptr) {
502 std::u16string envval = utf8ToUtf16(localDataPath);
504 if (!setEnvironmentVariable(u"XDG_DATA_HOME", envval.c_str())) {
505 _ERR("Failed to set XDG_DATA_HOME");
511 pluginBeforeExecute();
513 _INFO("execute assembly : %s", path);
515 unsigned int ret = 0;
516 int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
518 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
522 } // namespace dotnetcore
523 } // namespace runtime