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>
40 #include <tzplatform_config.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 void initEnvForSpecialFolder()
148 const char* path = NULL;
149 if (getenv("XDG_PICTURES_DIR") == NULL) {
150 path = tzplatform_getenv(TZ_USER_IMAGES);
152 setenv("XDG_PICTURES_DIR", path, 1);
156 if (getenv("XDG_MUSIC_DIR") == NULL) {
157 path = tzplatform_getenv(TZ_USER_MUSIC);
159 setenv("XDG_MUSIC_DIR", path, 1);
163 if (getenv("XDG_VIDEOS_DIR") == NULL) {
164 path = tzplatform_getenv(TZ_USER_VIDEOS);
166 setenv("XDG_VIDEOS_DIR", path, 1);
171 static void setLang()
173 //To reduce search overhead of libicuuc.so.xx
174 setenv("CLR_ICU_VERSION_OVERRIDE", "build", 1);
176 char* lang = vconf_get_str(VCONFKEY_LANGSET);
178 _ERR("Fail to get language from vconf");
182 // In order to operate ICU (used for globalization) normally, the following
183 // environment variables must be set before using ICU API.
184 // When running Applicaiton, the following environment variables are set by AppFW.
185 // But when preloading the dll in the candidate process, the following environment variables are not set
186 // As a result, CultureInfo is incorrectly generated and malfunctions.
187 // For example, uloc_getDefault() returns en_US_POSIX, CultureInfo is set to invariant mode.
188 setenv("LANG", const_cast<char *>(lang), 1);
189 setlocale(LC_ALL, const_cast<char *>(lang));
194 static std::string readSelfPath()
197 ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
200 return std::string(buff);
206 static void removeDebugPipe()
209 struct dirent* entry;
210 char debugPipeFiles[PATH_MAX];;
211 sprintf(debugPipeFiles, "/tmp/clr-debug-pipe-%d-", getpid());
213 dir = opendir("/tmp");
214 if (dir == nullptr) {
215 _ERR("Fail to open /tmp directory");
219 while ((entry = readdir(dir)) != nullptr) {
220 std::string path = concatPath("/tmp", entry->d_name);
221 if (path.find(debugPipeFiles) != std::string::npos) {
222 if (!removeFile(path)) {
223 _ERR("Fail to remove file (%s)", path.c_str());
233 typedef void (*PreloadDelegate)();
234 PreloadDelegate preloadDelegate;
236 int ret = createDelegate(__hostHandle,
239 "Tizen.Runtime.Preloader",
241 (void**)&preloadDelegate);
244 _ERR("Failed to create delegate for Tizen.Runtime Preload (0x%08x)", ret);
252 bool initializeCoreClr(PathManager* pm, const std::string& tpa)
254 bool ncdbStartupHook = isNCDBStartupHookProvided();
256 const char *propertyKeys[] = {
257 "TRUSTED_PLATFORM_ASSEMBLIES",
260 "NATIVE_DLL_SEARCH_DIRECTORIES",
261 "AppDomainCompatSwitch",
262 ncdbStartupHook ? "STARTUP_HOOKS" : "" // must be the last one
265 const char *propertyValues[] = {
267 pm->getAppPaths().c_str(),
268 pm->getAppNIPaths().c_str(),
269 pm->getNativeDllSearchingPaths().c_str(),
270 "UseLatestBehaviorWhenTFMNotSpecified",
271 ncdbStartupHook ? getNCDBStartupHook() : "" // must be the last one
274 std::string selfPath = readSelfPath();
276 int st = initializeClr(selfPath.c_str(),
278 sizeof(propertyKeys) / sizeof(propertyKeys[0]) - (ncdbStartupHook ? 0 : 1),
285 _ERR("initialize core clr fail! (0x%08x)", st);
289 pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
291 _INFO("Initialize core clr success");
295 int CoreRuntime::initialize(const char* appType, LaunchMode launchMode)
298 _ERR("CoreRuntime is already initialized");
302 // set language environment to support ICU
306 env = getenv("CORECLR_ENABLE_PROFILING");
307 if (env != nullptr && !strcmp(env, "1")) {
308 _INFO("profiling mode on");
309 __isProfileMode = true;
312 // plugin initialize should be called before creating threads.
313 // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
314 // When attaching to a secure zone, if there is a created thread, it will failed.
315 // So, plugin initialize should be called before creating threads.
316 if (initializePluginManager(appType) < 0) {
317 _ERR("Failed to initialize PluginManager");
321 // checkInjection checks dotnet-launcher run mode
322 // At the moment, this mechanism is used only when the Memory Profiler is started.
323 int res = checkInjection();
325 _ERR("Failed to initnialize Memory Profiler");
330 // libunwind library is used to unwind stack frame, but libunwind for ARM
331 // does not support ARM vfpv3/NEON registers in DWARF format correctly.
332 // Therefore let's disable stack unwinding using DWARF information
333 // See https://github.com/dotnet/coreclr/issues/6698
335 // libunwind use following methods to unwind stack frame.
336 // UNW_ARM_METHOD_ALL 0xFF
337 // UNW_ARM_METHOD_DWARF 0x01
338 // UNW_ARM_METHOD_FRAME 0x02
339 // UNW_ARM_METHOD_EXIDX 0x04
340 putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
343 // Enable diagnostics.
344 // clr create clr-debug-pipe-xxx and dotnet-diagnostics-xxx file under /tmp dir.
345 putenv(const_cast<char *>("COMPlus_EnableDiagnostics=1"));
347 // Write Debug.WriteLine to stderr
348 putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
350 #ifdef USE_DEFAULT_BASE_ADDR
351 putenv(const_cast<char *>("COMPlus_UseDefaultBaseAddr=1"));
352 #endif // USE_DEFAULT_BASE_ADDR
354 // Disable config cache to set environment after coreclr_initialize()
355 putenv(const_cast<char *>("COMPlus_DisableConfigCache=1"));
357 // Set environment variable for System.Environment.SpecialFolder
358 initEnvForSpecialFolder();
360 // read string from external file and set them to environment value.
364 __pm = new PathManager();
365 } catch (const std::exception& e) {
366 _ERR("Failed to create PathManager");
370 char* pluginDllPaths = pluginGetDllPath();
371 if (pluginDllPaths && pluginDllPaths[0] != '\0') {
372 __pm->addPlatformAssembliesPaths(pluginDllPaths, true);
375 char* pluginNativePaths = pluginGetNativeDllSearchingPath();
376 if (pluginNativePaths && pluginNativePaths[0] != '\0') {
377 __pm->addNativeDllSearchingPaths(pluginNativePaths, true);
380 char* pluginExtraDllPaths = pluginGetExtraDllPath();
381 if (pluginExtraDllPaths && pluginExtraDllPaths[0] != '\0') {
382 __pm->setExtraDllPaths(pluginExtraDllPaths);
385 std::string libCoreclr(concatPath(__pm->getRuntimePath(), "libcoreclr.so"));
387 __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
388 if (__coreclrLib == nullptr) {
389 char *err = dlerror();
390 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
394 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
396 variable = (type)dlsym(__coreclrLib, name); \
397 if (variable == nullptr) { \
398 _ERR(name " is not found in the libcoreclr.so"); \
403 CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
404 CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
405 CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
406 CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
408 #undef CORELIB_RETURN_IF_NOSYM
410 _INFO("libcoreclr dlopen and dlsym success");
413 char* pluginTPA = pluginGetTPA();
414 if (pluginTPA && pluginTPA[0] != '\0') {
415 tpa = std::string(pluginTPA);
417 addAssembliesFromDirectories(__pm->getPlatformAssembliesPaths(), tpa);
420 if (!initializeCoreClr(__pm, tpa)) {
421 _ERR("Failed to initialize coreclr");
425 int st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Environment", "SetEnvironmentVariable", (void**)&setEnvironmentVariable);
426 if (st < 0 || setEnvironmentVariable == nullptr) {
427 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Environment -> SetEnvironmentVariable failed (0x%08x)", st);
431 st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Profiler", "StopProfileAfterDelay", (void**)&stopProfileAfterDelay);
432 if (st < 0 || stopProfileAfterDelay == nullptr) {
433 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Profiler -> StopProfileAfterDelay failed (0x%08x)", st);
437 st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.AppSetting", "SetSwitch", (void**)&setSwitch);
438 if (st < 0 || setSwitch == nullptr) {
439 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.AppSetting -> SetSwitch failed (0x%08x)", st);
443 if (launchMode == LaunchMode::loader) {
444 // preload libraries and manage dlls for optimizing startup time
447 // The debug pipe created in the candidate process has a "User" label.
448 // As a result, smack deny occurs when app process try to access the debug pipe.
449 // Also, since debugging is performed only in standalone mode,
450 // the debug pipe doesnot be used in the candidate process.
451 // So, to avoid smack deny error, delete unused debug pipe files.
457 __initialized = true;
459 _INFO("CoreRuntime initialize success");
464 void CoreRuntime::finalize()
466 // call plugin finalize function to notify finalize to plugin
467 // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
470 // ignore the signal generated by an exception that occurred during shutdown
471 checkOnTerminate = true;
473 // workaround : to prevent crash while process terminate on profiling mode,
474 // kill process immediately.
475 // see https://github.com/dotnet/coreclr/issues/26687
476 if (__isProfileMode) {
477 _INFO("shutdown process immediately.");
481 if (__hostHandle != nullptr) {
482 int st = shutdown(__hostHandle, __domainId);
484 _ERR("shutdown core clr fail! (0x%08x)", st);
485 __hostHandle = nullptr;
488 if (__coreclrLib != nullptr) {
489 if (dlclose(__coreclrLib) != 0) {
490 _ERR("libcoreclr.so close failed");
493 __coreclrLib = nullptr;
496 finalizePluginManager();
503 _INFO("CoreRuntime finalized");
506 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[], bool profile)
508 if (!__initialized) {
509 _ERR("Runtime is not initialized");
513 if (path == nullptr) {
514 _ERR("executable path is null");
519 _ERR("File not exist : %s", path);
523 // VD has their own signal handler.
524 if (!pluginHasLogControl()) {
525 registerSigHandler();
528 pluginSetAppInfo(appId, path);
530 // temporal root path is overrided to real application root path
531 __pm->setAppRootPath(root);
533 // set application data path to coreclr environment.
534 // application data path can be changed by owner. So, we have to set data path just before launching.
535 char* localDataPath = app_get_data_path();
536 if (localDataPath != nullptr) {
537 setEnvironmentVariable("XDG_DATA_HOME", localDataPath);
539 // set profile.data path and collect/use it if it non-exists/exists.
541 char multiCoreJitProfile[strlen(localDataPath) + strlen(PROFILE_BASENAME) + 1];
542 memcpy(multiCoreJitProfile, localDataPath, strlen(localDataPath) + 1);
543 strncat(multiCoreJitProfile, PROFILE_BASENAME, strlen(PROFILE_BASENAME));
545 setEnvironmentVariable("COMPlus_MultiCoreJitProfile", multiCoreJitProfile);
546 setEnvironmentVariable("COMPlus_MultiCoreJitMinNumCpus", "1");
548 if (exist(multiCoreJitProfile)) {
549 setEnvironmentVariable("COMPlus_MultiCoreJitNoProfileGather", "1");
550 _INFO("MCJ playing start for %s", appId);
552 setEnvironmentVariable("COMPlus_MultiCoreJitNoProfileGather", "0");
553 // stop profiling and write collected data after delay if env value is set.
554 char *env = getenv("CLR_MCJ_PROFILE_WRITE_DELAY");
555 if (env != nullptr) {
556 int delay = std::atoi(env);
557 // To avoid undefined behavior by out-of-range input(atoi), set max delay value to 100.
559 if (delay > MAX_DELAY_SEC) delay = MAX_DELAY_SEC;
560 stopProfileAfterDelay(delay);
563 _INFO("MCJ recording start for %s", appId);
569 if (exist(__pm->getAppRootPath() + "/bin/" + DISABLE_IPV6_FILE)) {
570 setSwitch("System.Net.DisableIPv6", true);
573 setSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true);
575 pluginBeforeExecute();
577 _INFO("execute assembly : %s", path);
579 unsigned int ret = 0;
580 int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
582 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
586 } // namespace dotnetcore
587 } // namespace runtime