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");
342 // checkInjection checks dotnet-launcher run mode
343 // At the moment, this mechanism is used only when the Memory Profiler is started.
344 int res = checkInjection();
346 _ERR("Failed to initnialize Memory Profiler");
351 // libunwind library is used to unwind stack frame, but libunwind for ARM
352 // does not support ARM vfpv3/NEON registers in DWARF format correctly.
353 // Therefore let's disable stack unwinding using DWARF information
354 // See https://github.com/dotnet/coreclr/issues/6698
356 // libunwind use following methods to unwind stack frame.
357 // UNW_ARM_METHOD_ALL 0xFF
358 // UNW_ARM_METHOD_DWARF 0x01
359 // UNW_ARM_METHOD_FRAME 0x02
360 // UNW_ARM_METHOD_EXIDX 0x04
361 putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
364 // Enable diagnostics.
365 // clr create clr-debug-pipe-xxx and dotnet-diagnostics-xxx file under /tmp dir.
366 putenv(const_cast<char *>("COMPlus_EnableDiagnostics=1"));
368 // Write Debug.WriteLine to stderr
369 putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
371 #ifdef USE_DEFAULT_BASE_ADDR
372 putenv(const_cast<char *>("COMPlus_UseDefaultBaseAddr=1"));
373 #endif // USE_DEFAULT_BASE_ADDR
375 // Disable config cache to set environment after coreclr_initialize()
376 putenv(const_cast<char *>("COMPlus_DisableConfigCache=1"));
378 // read string from external file and set them to environment value.
382 __pm = new PathManager();
383 } catch (const std::exception& e) {
384 _ERR("Failed to create PathManager");
388 char* pluginDllPaths = pluginGetDllPath();
389 if (pluginDllPaths && pluginDllPaths[0] != '\0') {
390 __pm->addPlatformAssembliesPaths(pluginDllPaths, true);
393 char* pluginNativePaths = pluginGetNativeDllSearchingPath();
394 if (pluginNativePaths && pluginNativePaths[0] != '\0') {
395 __pm->addNativeDllSearchingPaths(pluginNativePaths, true);
398 char* pluginExtraDllPaths = pluginGetExtraDllPath();
399 if (pluginExtraDllPaths && pluginExtraDllPaths[0] != '\0') {
400 __pm->setExtraDllPaths(pluginExtraDllPaths);
403 pluginHasLogControl();
405 std::string libCoreclr(concatPath(__pm->getRuntimePath(), "libcoreclr.so"));
407 __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
408 if (__coreclrLib == nullptr) {
409 char *err = dlerror();
410 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
414 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
416 variable = (type)dlsym(__coreclrLib, name); \
417 if (variable == nullptr) { \
418 _ERR(name " is not found in the libcoreclr.so"); \
423 CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
424 CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
425 CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
426 CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
428 #undef CORELIB_RETURN_IF_NOSYM
430 _INFO("libcoreclr dlopen and dlsym success");
432 // Set environment for System.Environment.SpecialFolder
433 // Below function creates dbus connection by callging storage API.
434 // If dbus connection is created bofere fork(), forked process cannot use dbus.
435 // To avoid gdbus blocking issue, below function should be called after fork()
436 initEnvForSpecialFolder();
439 char* pluginTPA = pluginGetTPA();
440 if (pluginTPA && pluginTPA[0] != '\0') {
441 tpa = std::string(pluginTPA);
443 addAssembliesFromDirectories(__pm->getPlatformAssembliesPaths(), tpa);
446 if (!initializeCoreClr(__pm, tpa)) {
447 _ERR("Failed to initialize coreclr");
451 int st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Environment", "SetEnvironmentVariable", (void**)&setEnvironmentVariable);
452 if (st < 0 || setEnvironmentVariable == nullptr) {
453 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Environment -> SetEnvironmentVariable failed (0x%08x)", st);
457 st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Profiler", "StopProfileAfterDelay", (void**)&stopProfileAfterDelay);
458 if (st < 0 || stopProfileAfterDelay == nullptr) {
459 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Profiler -> StopProfileAfterDelay failed (0x%08x)", st);
463 st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.AppSetting", "SetSwitch", (void**)&setSwitch);
464 if (st < 0 || setSwitch == nullptr) {
465 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.AppSetting -> SetSwitch failed (0x%08x)", st);
469 if (launchMode == LaunchMode::loader) {
471 // preload libraries and manage dlls for optimizing startup time
474 // The debug pipe created in the candidate process has a "User" label.
475 // As a result, smack deny occurs when app process try to access the debug pipe.
476 // Also, since debugging is performed only in standalone mode,
477 // the debug pipe doesnot be used in the candidate process.
478 // So, to avoid smack deny error, delete unused debug pipe files.
482 __initialized = true;
484 _INFO("CoreRuntime initialize success");
489 void CoreRuntime::finalize()
491 // call plugin finalize function to notify finalize to plugin
492 // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
495 // ignore the signal generated by an exception that occurred during shutdown
496 checkOnTerminate = true;
498 // workaround : to prevent crash while process terminate on profiling mode,
499 // kill process immediately.
500 // see https://github.com/dotnet/coreclr/issues/26687
501 if (__isProfileMode) {
502 _INFO("shutdown process immediately.");
506 if (__hostHandle != nullptr) {
507 int st = shutdown(__hostHandle, __domainId);
509 _ERR("shutdown core clr fail! (0x%08x)", st);
510 __hostHandle = nullptr;
513 if (__coreclrLib != nullptr) {
514 if (dlclose(__coreclrLib) != 0) {
515 _ERR("libcoreclr.so close failed");
518 __coreclrLib = nullptr;
521 finalizePluginManager();
528 _INFO("CoreRuntime finalized");
531 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[], bool profile)
533 if (!__initialized) {
534 _ERR("Runtime is not initialized");
538 if (path == nullptr) {
539 _ERR("executable path is null");
544 _ERR("File not exist : %s", path);
548 // VD has their own signal handler.
549 if (!pluginHasLogControl()) {
550 registerSigHandler();
553 pluginSetAppInfo(appId, path);
555 // temporal root path is overrided to real application root path
556 __pm->setAppRootPath(root);
558 // set application data path to coreclr environment.
559 // application data path can be changed by owner. So, we have to set data path just before launching.
560 char* localDataPath = app_get_data_path();
561 if (localDataPath != nullptr) {
562 setEnvironmentVariable("XDG_DATA_HOME", localDataPath);
564 // set profile.data path and collect/use it if it non-exists/exists.
566 char multiCoreJitProfile[strlen(localDataPath) + strlen(PROFILE_BASENAME) + 1];
567 memcpy(multiCoreJitProfile, localDataPath, strlen(localDataPath) + 1);
568 strncat(multiCoreJitProfile, PROFILE_BASENAME, strlen(PROFILE_BASENAME));
570 setEnvironmentVariable("COMPlus_MultiCoreJitProfile", multiCoreJitProfile);
571 setEnvironmentVariable("COMPlus_MultiCoreJitMinNumCpus", "1");
573 if (exist(multiCoreJitProfile)) {
574 setEnvironmentVariable("COMPlus_MultiCoreJitNoProfileGather", "1");
575 _INFO("MCJ playing start for %s", appId);
577 setEnvironmentVariable("COMPlus_MultiCoreJitNoProfileGather", "0");
578 // stop profiling and write collected data after delay if env value is set.
579 char *env = getenv("CLR_MCJ_PROFILE_WRITE_DELAY");
580 if (env != nullptr) {
581 int delay = std::atoi(env);
582 // To avoid undefined behavior by out-of-range input(atoi), set max delay value to 100.
584 if (delay > MAX_DELAY_SEC) delay = MAX_DELAY_SEC;
585 stopProfileAfterDelay(delay);
588 _INFO("MCJ recording start for %s", appId);
594 if (exist(__pm->getAppRootPath() + "/bin/" + DISABLE_IPV6_FILE)) {
595 setSwitch("System.Net.DisableIPv6", true);
598 setSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true);
600 pluginBeforeExecute();
602 _INFO("execute assembly : %s", path);
604 unsigned int ret = 0;
605 int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
607 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
611 } // namespace dotnetcore
612 } // namespace runtime