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>
35 #include "dotnet_launcher.h"
36 #include "plugin_manager.h"
37 #include "path_manager.h"
38 #include "log_manager.h"
40 #define PLUGIN_PATH "/usr/share/dotnet.tizen/lib/libdotnet_plugin.so"
41 #define ENV_FILE_PATH "/usr/share/dotnet.tizen/lib/coreclr_env.list"
45 namespace dotnetcore {
47 #if defined (__aarch64__)
48 #define ARCHITECTURE_IDENTIFIER "arm64"
49 const static std::vector<std::string> RID_FALLBACK_GRAPH =
50 {"linux-arm64", "linux", "unix-arm64", "unix", "any", "base"};
52 #elif defined (__arm__)
53 #define ARCHITECTURE_IDENTIFIER "arm"
54 const static std::vector<std::string> RID_FALLBACK_GRAPH =
55 {"tizen.4.0.0-armel", "tizen.4.0.0", "tizen-armel", "tizen", "linux-armel", "linux", "unix-armel", "unix", "any", "base"};
57 #elif defined (__x86_64__)
58 #define ARCHITECTURE_IDENTIFIER "x64"
59 const static std::vector<std::string> RID_FALLBACK_GRAPH =
60 {"linux-x64", "linux", "unix-x64", "unix", "any", "base"};
62 #elif defined (__i386__)
63 #define ARCHITECTURE_IDENTIFIER "x86"
64 const static std::vector<std::string> RID_FALLBACK_GRAPH =
65 {"linux-x86", "linux", "unix-x86", "unix", "any", "base"};
68 #error "Unknown target"
71 static std::string getExtraNativeLibDirs(const std::string& appRoot)
73 std::string candidate;
74 for (unsigned int i = 0; i < RID_FALLBACK_GRAPH.size(); i++) {
75 if(!candidate.empty()) {
78 candidate += concatPath(appRoot, "bin/runtimes/" + RID_FALLBACK_GRAPH[i] + "/native");
81 candidate = candidate + ":" + concatPath(appRoot, "lib/" ARCHITECTURE_IDENTIFIER);
82 if (!strncmp(ARCHITECTURE_IDENTIFIER, "arm64", 5)) {
83 candidate = candidate + ":" + concatPath(appRoot, "lib/aarch64");
90 static std::vector<std::string> __envList;
92 static void setEnvFromFile()
95 std::ifstream inFile(ENV_FILE_PATH);
100 _INFO("coreclr_env.list is found");
103 std::istringstream ss(envList);
106 while (std::getline(ss, token, ':')) {
107 if (!token.empty()) {
108 __envList.push_back(token);
112 for (unsigned int i = 0; i < __envList.size(); i++) {
113 putenv(const_cast<char *>(__envList[i].c_str()));
116 _INFO("coreclr_env.list file is not found. skip");
120 struct sigaction sig_abrt_new;
121 struct sigaction sig_abrt_old;
123 static bool checkOnSigabrt = false;
124 static void onSigabrt(int signum)
126 fprintf(stderr, "onSigabrt is called!!!\n");
128 if (checkOnSigabrt) {
129 fprintf(stderr, "SIGABRT is already handled. Go to exit\n");
133 if (hasException()) {
134 fprintf(stderr, "Unhandled exception is occured. Ignore coredump creation and terminate normally\n");
137 fprintf(stderr, "SIGABRT from native. raise(%d)\n", signum);
138 checkOnSigabrt = true;
139 if (sigaction(SIGABRT, &sig_abrt_old, NULL) == 0) {
140 if (raise(signum) < 0) {
141 fprintf(stderr, "Fail to raise SIGABRT\n");
144 fprintf(stderr, "Fail to set original SIGABRT handler\n");
149 static void registerSigHandler()
151 sig_abrt_new.sa_handler = onSigabrt;
152 if (sigemptyset(&sig_abrt_new.sa_mask) == 0) {
153 _ERR("Fail to initialize signal set");
156 if (sigaction(SIGABRT, &sig_abrt_new, &sig_abrt_old) < 0) {
157 _ERR("Fail to add sig handler");
161 CoreRuntime::CoreRuntime(const char* mode) :
162 initializeClr(nullptr),
163 executeAssembly(nullptr),
165 createDelegate(nullptr),
166 __coreclrLib(nullptr),
167 __hostHandle(nullptr),
172 _INFO("Constructor called!!");
174 // plugin initialize should be called before start loader mainloop.
175 // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
176 // When attaching to a secure zone, if there is a created thread, it will failed.
177 // So, plugin initialize should be called before mainloop start.
178 if (initializePluginManager(mode) < 0) {
179 _ERR("Failed to initialize PluginManager");
182 if (pluginHasLogControl()) {
183 __enableLogManager = false;
185 __enableLogManager = true;
189 CoreRuntime::~CoreRuntime()
194 int CoreRuntime::initialize(bool standalone)
197 #define __STR(x) __XSTR(x)
199 #ifdef NATIVE_LIB_DIR
200 __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
207 // libunwind library is used to unwind stack frame, but libunwind for ARM
208 // does not support ARM vfpv3/NEON registers in DWARF format correctly.
209 // Therefore let's disable stack unwinding using DWARF information
210 // See https://github.com/dotnet/coreclr/issues/6698
212 // libunwind use following methods to unwind stack frame.
213 // UNW_ARM_METHOD_ALL 0xFF
214 // UNW_ARM_METHOD_DWARF 0x01
215 // UNW_ARM_METHOD_FRAME 0x02
216 // UNW_ARM_METHOD_EXIDX 0x04
217 putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
220 // read string from external file and set them to environment value.
223 if (initializePathManager(std::string(), std::string(), std::string()) < 0) {
224 _ERR("Failed to initialize PathManager");
228 if (__enableLogManager) {
229 if (initializeLogManager() < 0) {
230 _ERR("Failed to initnialize LogManager");
234 if (redirectFD() < 0) {
235 _ERR("Failed to redirect FD");
239 if (runLoggingThread() < 0) {
240 _ERR("Failed to create and run logging thread to redicrect log");
245 std::string libCoreclr(concatPath(getRuntimeDir(), "libcoreclr.so"));
247 __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
248 if (__coreclrLib == nullptr) {
249 char *err = dlerror();
250 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
254 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
256 variable = (type)dlsym(__coreclrLib, name); \
257 if (variable == nullptr) { \
258 _ERR(name " is not found in the libcoreclr.so"); \
263 CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
264 CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
265 CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
266 CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
268 #undef CORELIB_RETURN_IF_NOSYM
270 _INFO("libcoreclr dlopen and dlsym success");
275 fd = open("/proc/self", O_DIRECTORY);
276 std::string appRoot = std::string("/proc/self/fd/") + std::to_string(fd);
277 std::string appBin = concatPath(appRoot, "bin");
278 std::string appLib = concatPath(appRoot, "lib");
279 std::string probePath = appBin + ":" + appLib;
280 std::string tpa = getTPA();
281 std::string nativeLibPath = getExtraNativeLibDirs(appRoot) + ":" + appBin + ":" + appLib + ":" + __nativeLibDirectory;
282 std::string appName = std::string("dotnet-launcher-") + std::to_string(getpid());
284 if (!initializeCoreClr(appName.c_str(), probePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
285 _ERR("Failed to initialize coreclr");
289 __initialized = true;
291 _INFO("CoreRuntime initialize success");
296 bool CoreRuntime::initializeCoreClr(const char* appId,
297 const char* assemblyProbePaths,
298 const char* pinvokeProbePaths,
301 const char *propertyKeys[] = {
302 "TRUSTED_PLATFORM_ASSEMBLIES",
305 "NATIVE_DLL_SEARCH_DIRECTORIES",
306 "AppDomainCompatSwitch"
309 const char *propertyValues[] = {
314 "UseLatestBehaviorWhenTFMNotSpecified"
317 std::string selfPath = readSelfPath();
319 int st = initializeClr(selfPath.c_str(),
321 sizeof(propertyKeys) / sizeof(propertyKeys[0]),
328 _ERR("initialize core clr fail! (0x%08x)", st);
332 pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
334 _INFO("Initialize core clr success");
338 void CoreRuntime::dispose()
340 if (__hostHandle != nullptr) {
341 int st = shutdown(__hostHandle, __domainId);
343 _ERR("shutdown core clr fail! (0x%08x)", st);
344 __hostHandle = nullptr;
347 if (__coreclrLib != nullptr) {
348 if (dlclose(__coreclrLib) != 0) {
349 _ERR("libcoreclr.so close failed");
352 __coreclrLib = nullptr;
355 finalizePluginManager();
356 finalizePathManager();
360 _INFO("Dotnet runtime disposed");
363 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
365 if (!__initialized) {
366 _ERR("Runtime is not initialized");
370 if (path == nullptr) {
371 _ERR("executable path is null");
375 if (!isFileExist(path)) {
376 _ERR("File not exist : %s", path);
380 if (__enableLogManager) {
381 // launchpad override stdout and stderr to journalctl before launch application.
382 // we have to re-override that to input pipe for logging thread.
383 if (redirectFD() < 0) {
384 _ERR("Failed to redirect FD");
388 registerSigHandler();
391 pluginSetAppInfo(appId, path);
393 int fd2 = open(root, O_DIRECTORY);
394 dup3(fd2, fd, O_CLOEXEC);
398 pluginBeforeExecute();
400 _INFO("execute assembly : %s", path);
402 unsigned int ret = 0;
403 int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
405 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
409 } // namespace dotnetcore
410 } // namespace runtime