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>
40 #include <app_common.h>
44 #include "injection.h"
47 #include "core_runtime.h"
48 #include "plugin_manager.h"
49 #include "path_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 stop_profile_after_delay_ptr stopProfileAfterDelay = nullptr;
61 static set_switch_ptr setSwitch = nullptr;
62 static void* __coreclrLib = nullptr;
63 static void* __hostHandle = nullptr;
64 static unsigned int __domainId = -1;
65 static bool __initialized = false;
66 static bool __isProfileMode = false;
67 PathManager* CoreRuntime::__pm = nullptr;
69 #define MAX_DELAY_SEC 100
71 static std::vector<std::string> __envList;
73 static void setEnvFromFile()
76 std::ifstream inFile(ENV_FILE_PATH);
81 _INFO("coreclr_env.list is found");
84 while (std::getline(inFile, token, '\n')) {
86 __envList.push_back(token);
90 for (unsigned int i = 0; i < __envList.size(); i++) {
91 putenv(const_cast<char *>(__envList[i].c_str()));
94 _INFO("coreclr_env.list file is not found. skip");
98 #define _unused(x) ((void)(x))
100 struct sigaction sig_abrt_new;
101 struct sigaction sig_abrt_old;
103 static bool checkOnSigabrt = false;
104 static bool checkOnTerminate = false;
106 static void onSigabrt(int signum)
108 // use unused variable to avoid build warning
109 ssize_t ret = write(STDERR_FILENO, "onSigabrt called\n", 17);
111 if (checkOnTerminate) {
112 ret = write(STDERR_FILENO, "onSigabrt called while terminate. go to exit\n", 45);
117 if (checkOnSigabrt) {
118 ret = write(STDERR_FILENO, "onSigabrt called again. go to exit\n", 35);
123 checkOnSigabrt = true;
124 if (sigaction(SIGABRT, &sig_abrt_old, NULL) == 0) {
125 if (raise(signum) < 0) {
126 ret = write(STDERR_FILENO, "Fail to raise SIGABRT\n", 22);
129 ret = write(STDERR_FILENO, "Fail to set original SIGABRT handler\n", 37);
134 static void registerSigHandler()
136 sig_abrt_new.sa_handler = onSigabrt;
137 if (sigemptyset(&sig_abrt_new.sa_mask) != 0) {
138 _ERR("Fail to sigemptyset");
141 if (sigaction(SIGABRT, &sig_abrt_new, &sig_abrt_old) < 0) {
142 _ERR("Fail to add sig handler");
146 static bool storage_cb(int id, storage_type_e type, storage_state_e state, const char *path, void *user_data)
148 int* tmp = (int*)user_data;
149 if (type == STORAGE_TYPE_INTERNAL)
158 static void setSpecialFolder(storage_directory_e type, const char* key)
162 static int __storageId = -1;
164 if (__storageId < 0) {
165 error = storage_foreach_device_supported(storage_cb, &__storageId);
166 if (error != STORAGE_ERROR_NONE) {
171 error = storage_get_directory(__storageId, type, &path);
172 if (error == STORAGE_ERROR_NONE && path != NULL) {
173 setenv(key, const_cast<char *>(path), 1);
178 static void initEnvForSpecialFolder()
180 if (getenv("XDG_PICTURES_DIR") == NULL) {
181 setSpecialFolder(STORAGE_DIRECTORY_IMAGES, "XDG_PICTURES_DIR");
184 if (getenv("XDG_MUSIC_DIR") == NULL) {
185 setSpecialFolder(STORAGE_DIRECTORY_MUSIC, "XDG_MUSIC_DIR");
188 if (getenv("XDG_VIDEOS_DIR") == NULL) {
189 setSpecialFolder(STORAGE_DIRECTORY_VIDEOS, "XDG_VIDEOS_DIR");
193 static void setLang()
195 //To reduce search overhead of libicuuc.so.xx
196 setenv("CLR_ICU_VERSION_OVERRIDE", "build", 1);
198 char* lang = vconf_get_str(VCONFKEY_LANGSET);
200 _ERR("Fail to get language from vconf");
204 // In order to operate ICU (used for globalization) normally, the following
205 // environment variables must be set before using ICU API.
206 // When running Applicaiton, the following environment variables are set by AppFW.
207 // But when preloading the dll in the candidate process, the following environment variables are not set
208 // As a result, CultureInfo is incorrectly generated and malfunctions.
209 // For example, uloc_getDefault() returns en_US_POSIX, CultureInfo is set to invariant mode.
210 setenv("LANG", const_cast<char *>(lang), 1);
211 setlocale(LC_ALL, const_cast<char *>(lang));
216 static std::string readSelfPath()
219 ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
222 return std::string(buff);
228 static void removeDebugPipe()
231 struct dirent* entry;
232 char debugPipeFiles[PATH_MAX];;
233 sprintf(debugPipeFiles, "/tmp/clr-debug-pipe-%d-", getpid());
235 dir = opendir("/tmp");
236 if (dir == nullptr) {
237 _ERR("Fail to open /tmp directory");
241 while ((entry = readdir(dir)) != nullptr) {
242 std::string path = concatPath("/tmp", entry->d_name);
243 if (path.find(debugPipeFiles) != std::string::npos) {
244 if (!removeFile(path)) {
245 _ERR("Fail to remove file (%s)", path.c_str());
255 typedef void (*PreloadDelegate)();
256 PreloadDelegate preloadDelegate;
258 int ret = createDelegate(__hostHandle,
261 "Tizen.Runtime.Preloader",
263 (void**)&preloadDelegate);
266 _ERR("Failed to create delegate for Tizen.Runtime Preload (0x%08x)", ret);
274 bool initializeCoreClr(PathManager* pm, const std::string& tpa)
276 bool ncdbStartupHook = isNCDBStartupHookProvided();
278 const char *propertyKeys[] = {
279 "TRUSTED_PLATFORM_ASSEMBLIES",
282 "NATIVE_DLL_SEARCH_DIRECTORIES",
283 "AppDomainCompatSwitch",
284 ncdbStartupHook ? "STARTUP_HOOKS" : "" // must be the last one
287 const char *propertyValues[] = {
289 pm->getAppPaths().c_str(),
290 pm->getAppNIPaths().c_str(),
291 pm->getNativeDllSearchingPaths().c_str(),
292 "UseLatestBehaviorWhenTFMNotSpecified",
293 ncdbStartupHook ? getNCDBStartupHook() : "" // must be the last one
296 std::string selfPath = readSelfPath();
298 int st = initializeClr(selfPath.c_str(),
300 sizeof(propertyKeys) / sizeof(propertyKeys[0]) - (ncdbStartupHook ? 0 : 1),
307 _ERR("initialize core clr fail! (0x%08x)", st);
311 pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
313 _INFO("Initialize core clr success");
317 int CoreRuntime::initialize(const char* appType, LaunchMode launchMode)
320 _ERR("CoreRuntime is already initialized");
324 // Intiailize ecore first (signal handlers, etc.) before runtime init.
327 // set language environment to support ICU
331 env = getenv("CORECLR_ENABLE_PROFILING");
332 if (env != nullptr && !strcmp(env, "1")) {
333 _INFO("profiling mode on");
334 __isProfileMode = true;
337 // plugin initialize should be called before creating threads.
338 // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
339 // When attaching to a secure zone, if there is a created thread, it will failed.
340 // So, plugin initialize should be called before creating threads.
341 if (initializePluginManager(appType) < 0) {
342 _ERR("Failed to initialize PluginManager");
346 // checkInjection checks dotnet-launcher run mode
347 // At the moment, this mechanism is used only when the Memory Profiler is started.
348 int res = checkInjection();
350 _ERR("Failed to initnialize Memory Profiler");
355 // libunwind library is used to unwind stack frame, but libunwind for ARM
356 // does not support ARM vfpv3/NEON registers in DWARF format correctly.
357 // Therefore let's disable stack unwinding using DWARF information
358 // See https://github.com/dotnet/coreclr/issues/6698
360 // libunwind use following methods to unwind stack frame.
361 // UNW_ARM_METHOD_ALL 0xFF
362 // UNW_ARM_METHOD_DWARF 0x01
363 // UNW_ARM_METHOD_FRAME 0x02
364 // UNW_ARM_METHOD_EXIDX 0x04
365 putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
368 // Enable diagnostics.
369 // clr create clr-debug-pipe-xxx and dotnet-diagnostics-xxx file under /tmp dir.
370 putenv(const_cast<char *>("COMPlus_EnableDiagnostics=1"));
372 // Write Debug.WriteLine to stderr
373 putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
375 #ifdef USE_DEFAULT_BASE_ADDR
376 putenv(const_cast<char *>("COMPlus_UseDefaultBaseAddr=1"));
377 #endif // USE_DEFAULT_BASE_ADDR
379 // Disable config cache to set environment after coreclr_initialize()
380 putenv(const_cast<char *>("COMPlus_DisableConfigCache=1"));
382 // read string from external file and set them to environment value.
386 __pm = new PathManager();
387 } catch (const std::exception& e) {
388 _ERR("Failed to create PathManager");
392 char* pluginDllPaths = pluginGetDllPath();
393 if (pluginDllPaths && pluginDllPaths[0] != '\0') {
394 __pm->addPlatformAssembliesPaths(pluginDllPaths, true);
397 char* pluginNativePaths = pluginGetNativeDllSearchingPath();
398 if (pluginNativePaths && pluginNativePaths[0] != '\0') {
399 __pm->addNativeDllSearchingPaths(pluginNativePaths, true);
402 char* pluginExtraDllPaths = pluginGetExtraDllPath();
403 if (pluginExtraDllPaths && pluginExtraDllPaths[0] != '\0') {
404 __pm->setExtraDllPaths(pluginExtraDllPaths);
407 pluginHasLogControl();
409 std::string libCoreclr(concatPath(__pm->getRuntimePath(), "libcoreclr.so"));
411 __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
412 if (__coreclrLib == nullptr) {
413 char *err = dlerror();
414 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
418 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
420 variable = (type)dlsym(__coreclrLib, name); \
421 if (variable == nullptr) { \
422 _ERR(name " is not found in the libcoreclr.so"); \
427 CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
428 CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
429 CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
430 CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
432 #undef CORELIB_RETURN_IF_NOSYM
434 _INFO("libcoreclr dlopen and dlsym success");
436 // Set environment for System.Environment.SpecialFolder
437 // Below function creates dbus connection by callging storage API.
438 // If dbus connection is created bofere fork(), forked process cannot use dbus.
439 // To avoid gdbus blocking issue, below function should be called after fork()
440 initEnvForSpecialFolder();
443 char* pluginTPA = pluginGetTPA();
444 if (pluginTPA && pluginTPA[0] != '\0') {
445 tpa = std::string(pluginTPA);
447 addAssembliesFromDirectories(__pm->getPlatformAssembliesPaths(), tpa);
450 if (!initializeCoreClr(__pm, tpa)) {
451 _ERR("Failed to initialize coreclr");
455 int st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Environment", "SetEnvironmentVariable", (void**)&setEnvironmentVariable);
456 if (st < 0 || setEnvironmentVariable == nullptr) {
457 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Environment -> SetEnvironmentVariable failed (0x%08x)", st);
461 st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Profiler", "StopProfileAfterDelay", (void**)&stopProfileAfterDelay);
462 if (st < 0 || stopProfileAfterDelay == nullptr) {
463 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Profiler -> StopProfileAfterDelay failed (0x%08x)", st);
467 st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.AppSetting", "SetSwitch", (void**)&setSwitch);
468 if (st < 0 || setSwitch == nullptr) {
469 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.AppSetting -> SetSwitch failed (0x%08x)", st);
473 if (launchMode == LaunchMode::loader) {
474 // preload libraries and manage dlls for optimizing startup time
477 // The debug pipe created in the candidate process has a "User" label.
478 // As a result, smack deny occurs when app process try to access the debug pipe.
479 // Also, since debugging is performed only in standalone mode,
480 // the debug pipe doesnot be used in the candidate process.
481 // So, to avoid smack deny error, delete unused debug pipe files.
485 __initialized = true;
487 _INFO("CoreRuntime initialize success");
492 void CoreRuntime::finalize()
494 // call plugin finalize function to notify finalize to plugin
495 // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
498 // ignore the signal generated by an exception that occurred during shutdown
499 checkOnTerminate = true;
501 // workaround : to prevent crash while process terminate on profiling mode,
502 // kill process immediately.
503 // see https://github.com/dotnet/coreclr/issues/26687
504 if (__isProfileMode) {
505 _INFO("shutdown process immediately.");
509 if (__hostHandle != nullptr) {
510 int st = shutdown(__hostHandle, __domainId);
512 _ERR("shutdown core clr fail! (0x%08x)", st);
513 __hostHandle = nullptr;
516 if (__coreclrLib != nullptr) {
517 if (dlclose(__coreclrLib) != 0) {
518 _ERR("libcoreclr.so close failed");
521 __coreclrLib = nullptr;
524 finalizePluginManager();
531 _INFO("CoreRuntime finalized");
534 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[], bool profile)
536 if (!__initialized) {
537 _ERR("Runtime is not initialized");
541 if (path == nullptr) {
542 _ERR("executable path is null");
547 _ERR("File not exist : %s", path);
551 // VD has their own signal handler.
552 if (!pluginHasLogControl()) {
553 registerSigHandler();
556 pluginSetAppInfo(appId, path);
558 // temporal root path is overrided to real application root path
559 __pm->setAppRootPath(root);
561 // set application data path to coreclr environment.
562 // application data path can be changed by owner. So, we have to set data path just before launching.
563 char* localDataPath = app_get_data_path();
564 if (localDataPath != nullptr) {
565 setEnvironmentVariable("XDG_DATA_HOME", localDataPath);
567 // set profile.data path and collect/use it if it non-exists/exists.
569 char multiCoreJitProfile[strlen(localDataPath) + strlen(PROFILE_BASENAME) + 1];
570 memcpy(multiCoreJitProfile, localDataPath, strlen(localDataPath) + 1);
571 strncat(multiCoreJitProfile, PROFILE_BASENAME, strlen(PROFILE_BASENAME));
573 setEnvironmentVariable("COMPlus_MultiCoreJitProfile", multiCoreJitProfile);
574 setEnvironmentVariable("COMPlus_MultiCoreJitMinNumCpus", "1");
576 if (exist(multiCoreJitProfile)) {
577 setEnvironmentVariable("COMPlus_MultiCoreJitNoProfileGather", "1");
578 _INFO("MCJ playing start for %s", appId);
580 setEnvironmentVariable("COMPlus_MultiCoreJitNoProfileGather", "0");
581 // stop profiling and write collected data after delay if env value is set.
582 char *env = getenv("CLR_MCJ_PROFILE_WRITE_DELAY");
583 if (env != nullptr) {
584 int delay = std::atoi(env);
585 // To avoid undefined behavior by out-of-range input(atoi), set max delay value to 100.
587 if (delay > MAX_DELAY_SEC) delay = MAX_DELAY_SEC;
588 stopProfileAfterDelay(delay);
591 _INFO("MCJ recording start for %s", appId);
597 if (exist(__pm->getAppRootPath() + "/bin/" + DISABLE_IPV6_FILE)) {
598 setSwitch("System.Net.DisableIPv6", true);
601 setSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true);
603 pluginBeforeExecute();
605 _INFO("execute assembly : %s", path);
607 unsigned int ret = 0;
608 int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
610 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
614 } // namespace dotnetcore
615 } // namespace runtime