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"
52 namespace dotnetcore {
54 static coreclr_initialize_ptr initializeClr = nullptr;
55 static coreclr_execute_assembly_ptr executeAssembly = nullptr;
56 static coreclr_shutdown_ptr shutdown = nullptr;
57 static coreclr_create_delegate_ptr createDelegate = nullptr;
58 static set_environment_variable_ptr setEnvironmentVariable = nullptr;
59 static stop_profile_after_delay_ptr stopProfileAfterDelay = nullptr;
60 static set_switch_ptr setSwitch = nullptr;
61 static void* __coreclrLib = nullptr;
62 static void* __hostHandle = nullptr;
63 static unsigned int __domainId = -1;
64 static bool __initialized = false;
65 static bool __isProfileMode = false;
66 PathManager* CoreRuntime::__pm = nullptr;
68 #define MAX_DELAY_SEC 100
70 static std::vector<std::string> __envList;
72 static void setEnvFromFile()
75 std::ifstream inFile(ENV_FILE_PATH);
80 _INFO("coreclr_env.list is found");
83 while (std::getline(inFile, token, '\n')) {
85 __envList.push_back(token);
89 for (unsigned int i = 0; i < __envList.size(); i++) {
90 putenv(const_cast<char *>(__envList[i].c_str()));
93 _INFO("coreclr_env.list file is not found. skip");
97 #define _unused(x) ((void)(x))
99 struct sigaction sig_abrt_new;
100 struct sigaction sig_abrt_old;
102 static bool checkOnSigabrt = false;
103 static bool checkOnTerminate = false;
105 static void onSigabrt(int signum)
107 // use unused variable to avoid build warning
108 ssize_t ret = write(STDERR_FILENO, "onSigabrt called\n", 17);
110 if (checkOnTerminate) {
111 ret = write(STDERR_FILENO, "onSigabrt called while terminate. go to exit\n", 45);
116 if (checkOnSigabrt) {
117 ret = write(STDERR_FILENO, "onSigabrt called again. go to exit\n", 35);
122 checkOnSigabrt = true;
123 if (sigaction(SIGABRT, &sig_abrt_old, NULL) == 0) {
124 if (raise(signum) < 0) {
125 ret = write(STDERR_FILENO, "Fail to raise SIGABRT\n", 22);
128 ret = write(STDERR_FILENO, "Fail to set original SIGABRT handler\n", 37);
133 static void registerSigHandler()
135 sig_abrt_new.sa_handler = onSigabrt;
136 if (sigemptyset(&sig_abrt_new.sa_mask) != 0) {
137 _ERR("Fail to sigemptyset");
140 if (sigaction(SIGABRT, &sig_abrt_new, &sig_abrt_old) < 0) {
141 _ERR("Fail to add sig handler");
145 static bool storage_cb(int id, storage_type_e type, storage_state_e state, const char *path, void *user_data)
147 int* tmp = (int*)user_data;
148 if (type == STORAGE_TYPE_INTERNAL)
157 static void setSpecialFolder(storage_directory_e type, const char* key)
161 static int __storageId = -1;
163 if (__storageId < 0) {
164 error = storage_foreach_device_supported(storage_cb, &__storageId);
165 if (error != STORAGE_ERROR_NONE) {
170 error = storage_get_directory(__storageId, type, &path);
171 if (error == STORAGE_ERROR_NONE && path != NULL) {
172 setenv(key, const_cast<char *>(path), 1);
177 static void initEnvForSpecialFolder()
179 if (getenv("XDG_PICTURES_DIR") == NULL) {
180 setSpecialFolder(STORAGE_DIRECTORY_IMAGES, "XDG_PICTURES_DIR");
183 if (getenv("XDG_MUSIC_DIR") == NULL) {
184 setSpecialFolder(STORAGE_DIRECTORY_MUSIC, "XDG_MUSIC_DIR");
187 if (getenv("XDG_VIDEOS_DIR") == NULL) {
188 setSpecialFolder(STORAGE_DIRECTORY_VIDEOS, "XDG_VIDEOS_DIR");
192 static void setLang()
194 char* lang = vconf_get_str(VCONFKEY_LANGSET);
196 _ERR("Fail to get language from vconf");
200 // In order to operate ICU (used for globalization) normally, the following
201 // environment variables must be set before using ICU API.
202 // When running Applicaiton, the following environment variables are set by AppFW.
203 // But when preloading the dll in the candidate process, the following environment variables are not set
204 // As a result, CultureInfo is incorrectly generated and malfunctions.
205 // For example, uloc_getDefault() returns en_US_POSIX, CultureInfo is set to invariant mode.
206 setenv("LANG", const_cast<char *>(lang), 1);
207 setlocale(LC_ALL, const_cast<char *>(lang));
212 static std::string readSelfPath()
215 ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
218 return std::string(buff);
224 static void removeDebugPipe()
227 struct dirent* entry;
228 char debugPipeFiles[PATH_MAX];;
229 sprintf(debugPipeFiles, "/tmp/clr-debug-pipe-%d-", getpid());
231 dir = opendir("/tmp");
232 if (dir == nullptr) {
233 _ERR("Fail to open /tmp directory");
237 while ((entry = readdir(dir)) != nullptr) {
238 std::string path = concatPath("/tmp", entry->d_name);
239 if (path.find(debugPipeFiles) != std::string::npos) {
240 if (!removeFile(path)) {
241 _ERR("Fail to remove file (%s)", path.c_str());
251 typedef void (*PreloadDelegate)();
252 PreloadDelegate preloadDelegate;
254 int ret = createDelegate(__hostHandle,
257 "Tizen.Runtime.Preloader",
259 (void**)&preloadDelegate);
262 _ERR("Failed to create delegate for Tizen.Runtime Preload (0x%08x)", ret);
270 bool initializeCoreClr(PathManager* pm, const std::string& tpa)
272 bool ncdbStartupHook = isNCDBStartupHookProvided();
274 const char *propertyKeys[] = {
275 "TRUSTED_PLATFORM_ASSEMBLIES",
278 "NATIVE_DLL_SEARCH_DIRECTORIES",
279 "AppDomainCompatSwitch",
280 ncdbStartupHook ? "STARTUP_HOOKS" : "" // must be the last one
283 const char *propertyValues[] = {
285 pm->getAppPaths().c_str(),
286 pm->getAppNIPaths().c_str(),
287 pm->getNativeDllSearchingPaths().c_str(),
288 "UseLatestBehaviorWhenTFMNotSpecified",
289 ncdbStartupHook ? getNCDBStartupHook() : "" // must be the last one
292 std::string selfPath = readSelfPath();
294 int st = initializeClr(selfPath.c_str(),
296 sizeof(propertyKeys) / sizeof(propertyKeys[0]) - (ncdbStartupHook ? 0 : 1),
303 _ERR("initialize core clr fail! (0x%08x)", st);
307 pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
309 _INFO("Initialize core clr success");
313 int CoreRuntime::initialize(const char* appType, LaunchMode launchMode)
316 _ERR("CoreRuntime is already initialized");
320 // Intiailize ecore first (signal handlers, etc.) before runtime init.
323 // set language environment to support ICU
327 env = getenv("CORECLR_ENABLE_PROFILING");
328 if (env != nullptr && !strcmp(env, "1")) {
329 _INFO("profiling mode on");
330 __isProfileMode = true;
333 // plugin initialize should be called before creating threads.
334 // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
335 // When attaching to a secure zone, if there is a created thread, it will failed.
336 // So, plugin initialize should be called before creating threads.
337 if (initializePluginManager(appType) < 0) {
338 _ERR("Failed to initialize PluginManager");
341 // checkInjection checks dotnet-launcher run mode
342 // At the moment, this mechanism is used only when the Memory Profiler is started.
343 int res = checkInjection();
345 _ERR("Failed to initnialize Memory Profiler");
350 // libunwind library is used to unwind stack frame, but libunwind for ARM
351 // does not support ARM vfpv3/NEON registers in DWARF format correctly.
352 // Therefore let's disable stack unwinding using DWARF information
353 // See https://github.com/dotnet/coreclr/issues/6698
355 // libunwind use following methods to unwind stack frame.
356 // UNW_ARM_METHOD_ALL 0xFF
357 // UNW_ARM_METHOD_DWARF 0x01
358 // UNW_ARM_METHOD_FRAME 0x02
359 // UNW_ARM_METHOD_EXIDX 0x04
360 putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
363 // Enable diagnostics.
364 // clr create clr-debug-pipe-xxx and dotnet-diagnostics-xxx file under /tmp dir.
365 putenv(const_cast<char *>("COMPlus_EnableDiagnostics=1"));
367 // Write Debug.WriteLine to stderr
368 putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
370 #ifdef USE_DEFAULT_BASE_ADDR
371 putenv(const_cast<char *>("COMPlus_UseDefaultBaseAddr=1"));
372 #endif // USE_DEFAULT_BASE_ADDR
374 // Disable config cache to set environment after coreclr_initialize()
375 putenv(const_cast<char *>("COMPlus_DisableConfigCache=1"));
377 // read string from external file and set them to environment value.
381 __pm = new PathManager();
382 } catch (const std::exception& e) {
383 _ERR("Failed to create PathManager");
387 char* pluginDllPaths = pluginGetDllPath();
388 if (pluginDllPaths && pluginDllPaths[0] != '\0') {
389 __pm->addPlatformAssembliesPaths(pluginDllPaths, true);
392 char* pluginNativePaths = pluginGetNativeDllSearchingPath();
393 if (pluginNativePaths && pluginNativePaths[0] != '\0') {
394 __pm->addNativeDllSearchingPaths(pluginNativePaths, true);
397 char* pluginExtraDllPaths = pluginGetExtraDllPath();
398 if (pluginExtraDllPaths && pluginExtraDllPaths[0] != '\0') {
399 __pm->setExtraDllPaths(pluginExtraDllPaths);
402 pluginHasLogControl();
404 std::string libCoreclr(concatPath(__pm->getRuntimePath(), "libcoreclr.so"));
406 __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
407 if (__coreclrLib == nullptr) {
408 char *err = dlerror();
409 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
413 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
415 variable = (type)dlsym(__coreclrLib, name); \
416 if (variable == nullptr) { \
417 _ERR(name " is not found in the libcoreclr.so"); \
422 CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
423 CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
424 CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
425 CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
427 #undef CORELIB_RETURN_IF_NOSYM
429 _INFO("libcoreclr dlopen and dlsym success");
431 // Set environment for System.Environment.SpecialFolder
432 // Below function creates dbus connection by callging storage API.
433 // If dbus connection is created bofere fork(), forked process cannot use dbus.
434 // To avoid gdbus blocking issue, below function should be called after fork()
435 initEnvForSpecialFolder();
438 char* pluginTPA = pluginGetTPA();
439 if (pluginTPA && pluginTPA[0] != '\0') {
440 tpa = std::string(pluginTPA);
442 addAssembliesFromDirectories(__pm->getPlatformAssembliesPaths(), tpa);
445 if (!initializeCoreClr(__pm, tpa)) {
446 _ERR("Failed to initialize coreclr");
450 int st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Environment", "SetEnvironmentVariable", (void**)&setEnvironmentVariable);
451 if (st < 0 || setEnvironmentVariable == nullptr) {
452 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Environment -> SetEnvironmentVariable failed (0x%08x)", st);
456 st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Profiler", "StopProfileAfterDelay", (void**)&stopProfileAfterDelay);
457 if (st < 0 || stopProfileAfterDelay == nullptr) {
458 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Profiler -> StopProfileAfterDelay failed (0x%08x)", st);
462 st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.AppSetting", "SetSwitch", (void**)&setSwitch);
463 if (st < 0 || setSwitch == nullptr) {
464 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.AppSetting -> SetSwitch failed (0x%08x)", st);
468 if (launchMode == LaunchMode::loader) {
470 // preload libraries and manage dlls for optimizing startup time
473 // The debug pipe created in the candidate process has a "User" label.
474 // As a result, smack deny occurs when app process try to access the debug pipe.
475 // Also, since debugging is performed only in standalone mode,
476 // the debug pipe doesnot be used in the candidate process.
477 // So, to avoid smack deny error, delete unused debug pipe files.
481 __initialized = true;
483 _INFO("CoreRuntime initialize success");
488 void CoreRuntime::finalize()
490 // call plugin finalize function to notify finalize to plugin
491 // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
494 // ignore the signal generated by an exception that occurred during shutdown
495 checkOnTerminate = true;
497 // workaround : to prevent crash while process terminate on profiling mode,
498 // kill process immediately.
499 // see https://github.com/dotnet/coreclr/issues/26687
500 if (__isProfileMode) {
501 _INFO("shutdown process immediately.");
505 if (__hostHandle != nullptr) {
506 int st = shutdown(__hostHandle, __domainId);
508 _ERR("shutdown core clr fail! (0x%08x)", st);
509 __hostHandle = nullptr;
512 if (__coreclrLib != nullptr) {
513 if (dlclose(__coreclrLib) != 0) {
514 _ERR("libcoreclr.so close failed");
517 __coreclrLib = nullptr;
520 finalizePluginManager();
527 _INFO("CoreRuntime finalized");
530 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[], bool profile)
532 if (!__initialized) {
533 _ERR("Runtime is not initialized");
537 if (path == nullptr) {
538 _ERR("executable path is null");
543 _ERR("File not exist : %s", path);
547 // VD has their own signal handler.
548 if (!pluginHasLogControl()) {
549 registerSigHandler();
552 pluginSetAppInfo(appId, path);
554 // temporal root path is overrided to real application root path
555 __pm->setAppRootPath(root);
557 // set application data path to coreclr environment.
558 // application data path can be changed by owner. So, we have to set data path just before launching.
559 char* localDataPath = app_get_data_path();
560 if (localDataPath != nullptr) {
561 setEnvironmentVariable("XDG_DATA_HOME", localDataPath);
563 // set profile.data path and collect/use it if it non-exists/exists.
565 char multiCoreJitProfile[strlen(localDataPath) + strlen(PROFILE_BASENAME) + 1];
566 memcpy(multiCoreJitProfile, localDataPath, strlen(localDataPath) + 1);
567 strncat(multiCoreJitProfile, PROFILE_BASENAME, strlen(PROFILE_BASENAME));
569 setEnvironmentVariable("COMPlus_MultiCoreJitProfile", multiCoreJitProfile);
570 setEnvironmentVariable("COMPlus_MultiCoreJitMinNumCpus", "1");
572 if (exist(multiCoreJitProfile)) {
573 setEnvironmentVariable("COMPlus_MultiCoreJitNoProfileGather", "1");
574 _INFO("MCJ playing start for %s", appId);
576 setEnvironmentVariable("COMPlus_MultiCoreJitNoProfileGather", "0");
577 // stop profiling and write collected data after delay if env value is set.
578 char *env = getenv("CLR_MCJ_PROFILE_WRITE_DELAY");
579 if (env != nullptr) {
580 int delay = std::atoi(env);
581 // To avoid undefined behavior by out-of-range input(atoi), set max delay value to 100.
583 if (delay > MAX_DELAY_SEC) delay = MAX_DELAY_SEC;
584 stopProfileAfterDelay(delay);
587 _INFO("MCJ recording start for %s", appId);
593 if (exist(__pm->getAppRootPath() + "/bin/" + DISABLE_IPV6_FILE)) {
594 setSwitch("System.Net.DisableIPv6", true);
597 setSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true);
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