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.
28 #include <sys/types.h>
31 #include <linux/limits.h>
34 #include <app_common.h>
39 #include "dotnet_launcher.h"
40 #include "plugin_manager.h"
41 #include "path_manager.h"
42 #include "log_manager.h"
44 #define PLUGIN_PATH "/usr/share/dotnet.tizen/lib/libdotnet_plugin.so"
45 #define ENV_FILE_PATH "/usr/share/dotnet.tizen/lib/coreclr_env.list"
49 namespace dotnetcore {
51 #if defined (__aarch64__)
52 #define ARCHITECTURE_IDENTIFIER "arm64"
53 const static std::vector<std::string> RID_FALLBACK_GRAPH =
54 {"linux-arm64", "linux", "unix-arm64", "unix", "any", "base"};
56 #elif defined (__arm__)
57 #define ARCHITECTURE_IDENTIFIER "arm"
58 const static std::vector<std::string> RID_FALLBACK_GRAPH =
59 {"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"};
61 #elif defined (__x86_64__)
62 #define ARCHITECTURE_IDENTIFIER "x64"
63 const static std::vector<std::string> RID_FALLBACK_GRAPH =
64 {"linux-x64", "linux", "unix-x64", "unix", "any", "base"};
66 #elif defined (__i386__)
67 #define ARCHITECTURE_IDENTIFIER "x86"
68 const static std::vector<std::string> RID_FALLBACK_GRAPH =
69 {"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"};
72 #error "Unknown target"
75 static std::string getExtraNativeLibDirs(const std::string& appRoot)
77 std::string candidate;
78 for (unsigned int i = 0; i < RID_FALLBACK_GRAPH.size(); i++) {
79 if(!candidate.empty()) {
82 candidate += concatPath(appRoot, "bin/runtimes/" + RID_FALLBACK_GRAPH[i] + "/native");
85 candidate = candidate + ":" + concatPath(appRoot, "lib/" ARCHITECTURE_IDENTIFIER);
86 if (!strncmp(ARCHITECTURE_IDENTIFIER, "arm64", 5)) {
87 candidate = candidate + ":" + concatPath(appRoot, "lib/aarch64");
94 static std::vector<std::string> __envList;
96 static void setEnvFromFile()
99 std::ifstream inFile(ENV_FILE_PATH);
104 _INFO("coreclr_env.list is found");
107 std::istringstream ss(envList);
110 while (std::getline(ss, token, ':')) {
111 if (!token.empty()) {
112 __envList.push_back(token);
116 for (unsigned int i = 0; i < __envList.size(); i++) {
117 putenv(const_cast<char *>(__envList[i].c_str()));
120 _INFO("coreclr_env.list file is not found. skip");
124 struct sigaction sig_abrt_new;
125 struct sigaction sig_abrt_old;
127 static bool checkOnSigabrt = false;
128 static void onSigabrt(int signum)
130 // ignore return value of write().
131 // this function is called when process go to die
132 // there is no need to handle return value for logging.
133 write(2, "onSigabrt called\n", 17);
135 if (checkOnSigabrt) {
136 write(2, "onSigabrt called again. go to exit\n", 35);
140 if (hasException()) {
141 write(2, "******************************************************\n", 55);
142 write(2, "Unhandled exception is occured. check application code\n", 55);
143 write(2, "******************************************************\n", 55);
146 checkOnSigabrt = true;
147 if (sigaction(SIGABRT, &sig_abrt_old, NULL) == 0) {
148 if (raise(signum) < 0) {
149 write(2, "Fail to raise SIGABRT\n", 22);
152 write(2, "Fail to set original SIGABRT handler\n", 37);
156 static void registerSigHandler()
158 sig_abrt_new.sa_handler = onSigabrt;
159 if (sigemptyset(&sig_abrt_new.sa_mask) != 0) {
160 _ERR("Fail to sigemptyset");
163 if (sigaction(SIGABRT, &sig_abrt_new, &sig_abrt_old) < 0) {
164 _ERR("Fail to add sig handler");
168 static bool storage_cb(int id, storage_type_e type, storage_state_e state, const char *path, void *user_data)
170 int* tmp = (int*)user_data;
171 if (type == STORAGE_TYPE_INTERNAL)
180 static void initEnvForSpecialFolder()
186 error = storage_foreach_device_supported(storage_cb, &storageId);
187 if (error != STORAGE_ERROR_NONE) {
191 error = storage_get_directory(storageId, STORAGE_DIRECTORY_IMAGES, &path);
192 if (error == STORAGE_ERROR_NONE && path != NULL) {
193 setenv("XDG_PICTURES_DIR", const_cast<char *>(path), 1);
198 error = storage_get_directory(storageId, STORAGE_DIRECTORY_MUSIC, &path);
199 if (error == STORAGE_ERROR_NONE && path != NULL) {
200 setenv("XDG_MUSIC_DIR", const_cast<char *>(path), 1);
205 error = storage_get_directory(storageId, STORAGE_DIRECTORY_VIDEOS, &path);
206 if (error == STORAGE_ERROR_NONE && path != NULL) {
207 setenv("XDG_VIDEOS_DIR", const_cast<char *>(path), 1);
213 CoreRuntime::CoreRuntime(const char* mode) :
214 initializeClr(nullptr),
215 executeAssembly(nullptr),
217 createDelegate(nullptr),
218 setEnvironmentVariable(nullptr),
219 multiByteToWideChar(nullptr),
220 __coreclrLib(nullptr),
221 __hostHandle(nullptr),
226 _INFO("Constructor called!!");
228 // plugin initialize should be called before start loader mainloop.
229 // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
230 // When attaching to a secure zone, if there is a created thread, it will failed.
231 // So, plugin initialize should be called before mainloop start.
232 if (initializePluginManager(mode) < 0) {
233 _ERR("Failed to initialize PluginManager");
236 if (pluginHasLogControl()) {
237 __enableLogManager = false;
239 __enableLogManager = true;
243 CoreRuntime::~CoreRuntime()
248 int CoreRuntime::initialize(bool standalone)
251 #define __STR(x) __XSTR(x)
253 #ifdef NATIVE_LIB_DIR
254 __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
261 // libunwind library is used to unwind stack frame, but libunwind for ARM
262 // does not support ARM vfpv3/NEON registers in DWARF format correctly.
263 // Therefore let's disable stack unwinding using DWARF information
264 // See https://github.com/dotnet/coreclr/issues/6698
266 // libunwind use following methods to unwind stack frame.
267 // UNW_ARM_METHOD_ALL 0xFF
268 // UNW_ARM_METHOD_DWARF 0x01
269 // UNW_ARM_METHOD_FRAME 0x02
270 // UNW_ARM_METHOD_EXIDX 0x04
271 putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
274 // Disable debug pipes and semaphores creation in case of non-standlone mode
276 putenv(const_cast<char *>("COMPlus_EnableDiagnostics=0"));
278 // read string from external file and set them to environment value.
281 // Set environment for System.Environment.SpecialFolder
282 initEnvForSpecialFolder();
284 if (initializePathManager(std::string(), std::string(), std::string()) < 0) {
285 _ERR("Failed to initialize PathManager");
289 if (__enableLogManager) {
290 if (initializeLogManager() < 0) {
291 _ERR("Failed to initnialize LogManager");
295 if (redirectFD() < 0) {
296 _ERR("Failed to redirect FD");
300 if (runLoggingThread() < 0) {
301 _ERR("Failed to create and run logging thread to redicrect log");
306 std::string libCoreclr(concatPath(getRuntimeDir(), "libcoreclr.so"));
308 __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
309 if (__coreclrLib == nullptr) {
310 char *err = dlerror();
311 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
315 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
317 variable = (type)dlsym(__coreclrLib, name); \
318 if (variable == nullptr) { \
319 _ERR(name " is not found in the libcoreclr.so"); \
324 CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
325 CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
326 CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
327 CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
328 CORELIB_RETURN_IF_NOSYM(set_environment_variable_ptr, setEnvironmentVariable, "SetEnvironmentVariableW");
329 CORELIB_RETURN_IF_NOSYM(multi_byte_to_wide_char_ptr, multiByteToWideChar, "MultiByteToWideChar");
331 #undef CORELIB_RETURN_IF_NOSYM
333 _INFO("libcoreclr dlopen and dlsym success");
338 fd = open("/proc/self", O_DIRECTORY);
339 std::string appRoot = std::string("/proc/self/fd/") + std::to_string(fd);
340 std::string appBin = concatPath(appRoot, "bin");
341 std::string appLib = concatPath(appRoot, "lib");
342 std::string probePath = appBin + ":" + appLib;
343 std::string tpa = getTPA();
344 std::string nativeLibPath = getExtraNativeLibDirs(appRoot) + ":" + appBin + ":" + appLib + ":" + __nativeLibDirectory;
345 std::string appName = std::string("dotnet-launcher-") + std::to_string(getpid());
347 if (!initializeCoreClr(appName.c_str(), probePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
348 _ERR("Failed to initialize coreclr");
352 __initialized = true;
354 _INFO("CoreRuntime initialize success");
359 bool CoreRuntime::initializeCoreClr(const char* appId,
360 const char* assemblyProbePaths,
361 const char* pinvokeProbePaths,
364 const char *propertyKeys[] = {
365 "TRUSTED_PLATFORM_ASSEMBLIES",
368 "NATIVE_DLL_SEARCH_DIRECTORIES",
369 "AppDomainCompatSwitch"
372 const char *propertyValues[] = {
377 "UseLatestBehaviorWhenTFMNotSpecified"
380 std::string selfPath = readSelfPath();
382 int st = initializeClr(selfPath.c_str(),
384 sizeof(propertyKeys) / sizeof(propertyKeys[0]),
391 _ERR("initialize core clr fail! (0x%08x)", st);
395 pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
397 _INFO("Initialize core clr success");
401 void CoreRuntime::dispose()
403 if (__hostHandle != nullptr) {
404 int st = shutdown(__hostHandle, __domainId);
406 _ERR("shutdown core clr fail! (0x%08x)", st);
407 __hostHandle = nullptr;
410 if (__coreclrLib != nullptr) {
411 if (dlclose(__coreclrLib) != 0) {
412 _ERR("libcoreclr.so close failed");
415 __coreclrLib = nullptr;
418 finalizePluginManager();
419 finalizePathManager();
423 _INFO("Dotnet runtime disposed");
426 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
428 if (!__initialized) {
429 _ERR("Runtime is not initialized");
433 if (path == nullptr) {
434 _ERR("executable path is null");
438 if (!isFileExist(path)) {
439 _ERR("File not exist : %s", path);
443 if (__enableLogManager) {
444 // launchpad override stdout and stderr to journalctl before launch application.
445 // we have to re-override that to input pipe for logging thread.
446 if (redirectFD() < 0) {
447 _ERR("Failed to redirect FD");
451 registerSigHandler();
454 pluginSetAppInfo(appId, path);
456 int fd2 = open(root, O_DIRECTORY);
457 dup3(fd2, fd, O_CLOEXEC);
461 // set application data path to coreclr environment.
462 // application data path can be changed by owner. So, we have to set data path just before launching.
463 char* localDataPath = app_get_data_path();
464 if (localDataPath != nullptr) {
465 char16_t envval[PATH_MAX] = {0};
466 int copied = multiByteToWideChar(0 /* CP_ACP */, 0, localDataPath, -1, envval, PATH_MAX);
467 if (copied >= PATH_MAX) {
468 _ERR("Data Path is bigger than PATH_MAX");
471 if (!setEnvironmentVariable(u"XDG_DATA_HOME", envval)) {
472 _ERR("Failed to set XDG_DATA_HOME");
476 pluginBeforeExecute();
478 _INFO("execute assembly : %s", path);
480 unsigned int ret = 0;
481 int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
483 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
487 } // namespace dotnetcore
488 } // namespace runtime