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.
32 #include <sys/types.h>
35 #include <linux/limits.h>
39 #include <app_common.h>
43 #include "injection.h"
46 #include "core_runtime.h"
47 #include "plugin_manager.h"
48 #include "path_manager.h"
49 #include "log_manager.h"
53 namespace dotnetcore {
55 static coreclr_initialize_ptr initializeClr = nullptr;
56 static coreclr_execute_assembly_ptr executeAssembly = nullptr;
57 static coreclr_shutdown_ptr shutdown = nullptr;
58 static coreclr_create_delegate_ptr createDelegate = nullptr;
59 static set_environment_variable_ptr setEnvironmentVariable = nullptr;
60 static void* __coreclrLib = nullptr;
61 static void* __hostHandle = nullptr;
62 static unsigned int __domainId = -1;
63 static bool __initialized = false;
64 static bool __isProfileMode = false;
65 PathManager* CoreRuntime::__pm = nullptr;
67 static std::vector<std::string> __envList;
69 static void setEnvFromFile()
72 std::ifstream inFile(ENV_FILE_PATH);
77 _INFO("coreclr_env.list is found");
80 while (std::getline(inFile, token, '\n')) {
82 __envList.push_back(token);
86 for (unsigned int i = 0; i < __envList.size(); i++) {
87 putenv(const_cast<char *>(__envList[i].c_str()));
90 _INFO("coreclr_env.list file is not found. skip");
94 #define _unused(x) ((void)(x))
96 struct sigaction sig_abrt_new;
97 struct sigaction sig_abrt_old;
99 static bool checkOnSigabrt = false;
100 static bool checkOnTerminate = false;
102 static void onSigabrt(int signum)
104 // use unused variable to avoid build warning
105 ssize_t ret = write(STDERR_FILENO, "onSigabrt called\n", 17);
107 if (checkOnTerminate) {
108 ret = write(STDERR_FILENO, "onSigabrt called while terminate. go to exit\n", 45);
113 if (checkOnSigabrt) {
114 ret = write(STDERR_FILENO, "onSigabrt called again. go to exit\n", 35);
119 checkOnSigabrt = true;
120 if (sigaction(SIGABRT, &sig_abrt_old, NULL) == 0) {
121 if (raise(signum) < 0) {
122 ret = write(STDERR_FILENO, "Fail to raise SIGABRT\n", 22);
125 ret = write(STDERR_FILENO, "Fail to set original SIGABRT handler\n", 37);
130 static void registerSigHandler()
132 sig_abrt_new.sa_handler = onSigabrt;
133 if (sigemptyset(&sig_abrt_new.sa_mask) != 0) {
134 _ERR("Fail to sigemptyset");
137 if (sigaction(SIGABRT, &sig_abrt_new, &sig_abrt_old) < 0) {
138 _ERR("Fail to add sig handler");
142 static bool storage_cb(int id, storage_type_e type, storage_state_e state, const char *path, void *user_data)
144 int* tmp = (int*)user_data;
145 if (type == STORAGE_TYPE_INTERNAL)
154 static void initEnvForSpecialFolder()
160 error = storage_foreach_device_supported(storage_cb, &storageId);
161 if (error != STORAGE_ERROR_NONE) {
165 error = storage_get_directory(storageId, STORAGE_DIRECTORY_IMAGES, &path);
166 if (error == STORAGE_ERROR_NONE && path != NULL) {
167 setenv("XDG_PICTURES_DIR", const_cast<char *>(path), 1);
172 error = storage_get_directory(storageId, STORAGE_DIRECTORY_MUSIC, &path);
173 if (error == STORAGE_ERROR_NONE && path != NULL) {
174 setenv("XDG_MUSIC_DIR", const_cast<char *>(path), 1);
179 error = storage_get_directory(storageId, STORAGE_DIRECTORY_VIDEOS, &path);
180 if (error == STORAGE_ERROR_NONE && path != NULL) {
181 setenv("XDG_VIDEOS_DIR", const_cast<char *>(path), 1);
187 // terminate candidate process when language changed
188 // icu related data (CultureInfo, etc) should be recreated.
189 static void langChangedCB(keynode_t *key, void* data)
191 _INFO("terminiate candidate process to update language.");
195 static void setLang()
197 char* lang = vconf_get_str(VCONFKEY_LANGSET);
199 _ERR("Fail to get language from vconf");
203 // In order to operate ICU (used for globalization) normally, the following
204 // environment variables must be set before using ICU API.
205 // When running Applicaiton, the following environment variables are set by AppFW.
206 // But when preloading the dll in the candidate process, the following environment variables are not set
207 // As a result, CultureInfo is incorrectly generated and malfunctions.
208 // For example, uloc_getDefault() returns en_US_POSIX, CultureInfo is set to invariant mode.
209 setenv("LANG", const_cast<char *>(lang), 1);
210 setlocale(LC_ALL, const_cast<char *>(lang));
215 static std::string readSelfPath()
218 ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
221 return std::string(buff);
227 static void removeDebugPipe()
230 struct dirent* entry;
231 char debugPipeFiles[PATH_MAX];;
232 sprintf(debugPipeFiles, "/tmp/clr-debug-pipe-%d-", getpid());
234 dir = opendir("/tmp");
235 if (dir == nullptr) {
236 _ERR("Fail to open /tmp directory");
240 while ((entry = readdir(dir)) != nullptr) {
241 std::string path = concatPath("/tmp", entry->d_name);
242 if (path.find(debugPipeFiles) != std::string::npos) {
243 if (!removeFile(path)) {
244 _ERR("Fail to remove file (%s)", path.c_str());
254 typedef void (*PreloadDelegate)();
255 PreloadDelegate preloadDelegate;
257 int ret = createDelegate(__hostHandle,
260 "Tizen.Runtime.Preloader",
262 (void**)&preloadDelegate);
265 _ERR("Failed to create delegate for Tizen.Runtime Preload (0x%08x)", ret);
273 bool initializeCoreClr(PathManager* pm, const std::string& tpa)
275 const char *propertyKeys[] = {
276 "TRUSTED_PLATFORM_ASSEMBLIES",
279 "NATIVE_DLL_SEARCH_DIRECTORIES",
280 "AppDomainCompatSwitch"
283 const char *propertyValues[] = {
285 pm->getAppPaths().c_str(),
286 pm->getAppNIPaths().c_str(),
287 pm->getNativeDllSearchingPaths().c_str(),
288 "UseLatestBehaviorWhenTFMNotSpecified"
291 std::string selfPath = readSelfPath();
293 int st = initializeClr(selfPath.c_str(),
295 sizeof(propertyKeys) / sizeof(propertyKeys[0]),
302 _ERR("initialize core clr fail! (0x%08x)", st);
306 pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
308 _INFO("Initialize core clr success");
312 int CoreRuntime::initialize(const char* appType, LaunchMode launchMode)
315 _ERR("CoreRuntime is already initialized");
319 // Intiailize ecore first (signal handlers, etc.) before runtime init.
322 // set language environment to support ICU
326 env = getenv("CORECLR_ENABLE_PROFILING");
327 if (env != nullptr && !strcmp(env, "1")) {
328 _INFO("profiling mode on");
329 __isProfileMode = true;
332 // plugin initialize should be called before creating threads.
333 // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
334 // When attaching to a secure zone, if there is a created thread, it will failed.
335 // So, plugin initialize should be called before creating threads.
336 if (initializePluginManager(appType) < 0) {
337 _ERR("Failed to initialize PluginManager");
340 // checkInjection checks dotnet-launcher run mode
341 // At the moment, this mechanism is used only when the Memory Profiler is started.
342 int res = checkInjection();
344 _ERR("Failed to initnialize Memory Profiler");
349 // libunwind library is used to unwind stack frame, but libunwind for ARM
350 // does not support ARM vfpv3/NEON registers in DWARF format correctly.
351 // Therefore let's disable stack unwinding using DWARF information
352 // See https://github.com/dotnet/coreclr/issues/6698
354 // libunwind use following methods to unwind stack frame.
355 // UNW_ARM_METHOD_ALL 0xFF
356 // UNW_ARM_METHOD_DWARF 0x01
357 // UNW_ARM_METHOD_FRAME 0x02
358 // UNW_ARM_METHOD_EXIDX 0x04
359 putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
362 // Enable diagnostics.
363 // clr create clr-debug-pipe-xxx and dotnet-diagnostics-xxx file under /tmp dir.
364 putenv(const_cast<char *>("COMPlus_EnableDiagnostics=1"));
366 // Write Debug.WriteLine to stderr
367 putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
369 #ifdef USE_DEFAULT_BASE_ADDR
370 putenv(const_cast<char *>("COMPlus_UseDefaultBaseAddr=1"));
371 #endif // USE_DEFAULT_BASE_ADDR
373 // read string from external file and set them to environment value.
377 __pm = new PathManager();
378 } catch (const std::exception& e) {
379 _ERR("Failed to create PathManager");
383 char* pluginPath = pluginGetDllPath();
385 __pm->addPlatformAssembliesPaths(pluginPath);
388 if (!pluginHasLogControl()) {
389 if (initializeLogManager() < 0) {
390 _ERR("Failed to initnialize LogManager");
395 std::string libCoreclr(concatPath(__pm->getRuntimePath(), "libcoreclr.so"));
397 __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
398 if (__coreclrLib == nullptr) {
399 char *err = dlerror();
400 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
404 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
406 variable = (type)dlsym(__coreclrLib, name); \
407 if (variable == nullptr) { \
408 _ERR(name " is not found in the libcoreclr.so"); \
413 CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
414 CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
415 CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
416 CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
418 #undef CORELIB_RETURN_IF_NOSYM
420 _INFO("libcoreclr dlopen and dlsym success");
422 // Set environment for System.Environment.SpecialFolder
423 // Below function creates dbus connection by callging storage API.
424 // If dbus connection is created bofere fork(), forked process cannot use dbus.
425 // To avoid gdbus blocking issue, below function should be called after fork()
426 initEnvForSpecialFolder();
429 char* pluginTPA = pluginGetTPA();
431 tpa = std::string(pluginTPA);
433 addAssembliesFromDirectories(__pm->getPlatformAssembliesPaths(), tpa);
436 if (!initializeCoreClr(__pm, tpa)) {
437 _ERR("Failed to initialize coreclr");
441 int st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Environment", "SetEnvironmentVariable", (void**)&setEnvironmentVariable);
442 if (st < 0 || setEnvironmentVariable == nullptr) {
443 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Environment -> SetEnvironmentVariable failed (0x%08x)", st);
447 if (launchMode == LaunchMode::loader) {
448 // terminate candidate process if language is changed.
449 // CurrentCulture created for preloaded dlls should be updated.
450 vconf_notify_key_changed(VCONFKEY_LANGSET, langChangedCB, NULL);
452 // preload libraries and manage dlls for optimizing startup time
455 // The debug pipe created in the candidate process has a "User" label.
456 // As a result, smack deny occurs when app process try to access the debug pipe.
457 // Also, since debugging is performed only in standalone mode,
458 // the debug pipe doesnot be used in the candidate process.
459 // So, to avoid smack deny error, delete unused debug pipe files.
463 __initialized = true;
465 _INFO("CoreRuntime initialize success");
470 void CoreRuntime::finalize()
472 // call plugin finalize function to notify finalize to plugin
473 // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
476 // ignore the signal generated by an exception that occurred during shutdown
477 checkOnTerminate = true;
479 // workaround : to prevent crash while process terminate on profiling mode,
480 // kill process immediately.
481 // see https://github.com/dotnet/coreclr/issues/26687
482 if (__isProfileMode) {
483 _INFO("shutdown process immediately.");
487 if (__hostHandle != nullptr) {
488 int st = shutdown(__hostHandle, __domainId);
490 _ERR("shutdown core clr fail! (0x%08x)", st);
491 __hostHandle = nullptr;
494 if (__coreclrLib != nullptr) {
495 if (dlclose(__coreclrLib) != 0) {
496 _ERR("libcoreclr.so close failed");
499 __coreclrLib = nullptr;
502 finalizePluginManager();
509 _INFO("CoreRuntime finalized");
512 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
514 if (!__initialized) {
515 _ERR("Runtime is not initialized");
519 if (path == nullptr) {
520 _ERR("executable path is null");
525 _ERR("File not exist : %s", path);
529 // launchpad override stdout and stderr to journalctl before launch application.
530 // we have to re-override that to input pipe for logging thread.
531 // if LogManager is not initialized, below redirectFD will return 0;
532 if (redirectFD() < 0) {
533 _ERR("Failed to redirect FD");
537 // VD has their own signal handler.
538 if (!pluginHasLogControl()) {
539 registerSigHandler();
542 pluginSetAppInfo(appId, path);
544 // temporal root path is overrided to real application root path
545 __pm->setAppRootPath(root);
547 // set application data path to coreclr environment.
548 // application data path can be changed by owner. So, we have to set data path just before launching.
549 char* localDataPath = app_get_data_path();
550 if (localDataPath != nullptr) {
551 setEnvironmentVariable("XDG_DATA_HOME", localDataPath);
555 vconf_ignore_key_changed(VCONFKEY_LANGSET, langChangedCB);
557 pluginBeforeExecute();
559 _INFO("execute assembly : %s", path);
561 unsigned int ret = 0;
562 int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
564 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
568 } // namespace dotnetcore
569 } // namespace runtime