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 initEnvForSpecialFolder()
163 error = storage_foreach_device_supported(storage_cb, &storageId);
164 if (error != STORAGE_ERROR_NONE) {
168 error = storage_get_directory(storageId, STORAGE_DIRECTORY_IMAGES, &path);
169 if (error == STORAGE_ERROR_NONE && path != NULL) {
170 setenv("XDG_PICTURES_DIR", const_cast<char *>(path), 1);
175 error = storage_get_directory(storageId, STORAGE_DIRECTORY_MUSIC, &path);
176 if (error == STORAGE_ERROR_NONE && path != NULL) {
177 setenv("XDG_MUSIC_DIR", const_cast<char *>(path), 1);
182 error = storage_get_directory(storageId, STORAGE_DIRECTORY_VIDEOS, &path);
183 if (error == STORAGE_ERROR_NONE && path != NULL) {
184 setenv("XDG_VIDEOS_DIR", const_cast<char *>(path), 1);
190 // terminate candidate process when language changed
191 // icu related data (CultureInfo, etc) should be recreated.
192 static void langChangedCB(keynode_t *key, void* data)
194 _INFO("terminiate candidate process to update language.");
198 static void setLang()
200 char* lang = vconf_get_str(VCONFKEY_LANGSET);
202 _ERR("Fail to get language from vconf");
206 // In order to operate ICU (used for globalization) normally, the following
207 // environment variables must be set before using ICU API.
208 // When running Applicaiton, the following environment variables are set by AppFW.
209 // But when preloading the dll in the candidate process, the following environment variables are not set
210 // As a result, CultureInfo is incorrectly generated and malfunctions.
211 // For example, uloc_getDefault() returns en_US_POSIX, CultureInfo is set to invariant mode.
212 setenv("LANG", const_cast<char *>(lang), 1);
213 setlocale(LC_ALL, const_cast<char *>(lang));
218 static std::string readSelfPath()
221 ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
224 return std::string(buff);
230 static void removeDebugPipe()
233 struct dirent* entry;
234 char debugPipeFiles[PATH_MAX];;
235 sprintf(debugPipeFiles, "/tmp/clr-debug-pipe-%d-", getpid());
237 dir = opendir("/tmp");
238 if (dir == nullptr) {
239 _ERR("Fail to open /tmp directory");
243 while ((entry = readdir(dir)) != nullptr) {
244 std::string path = concatPath("/tmp", entry->d_name);
245 if (path.find(debugPipeFiles) != std::string::npos) {
246 if (!removeFile(path)) {
247 _ERR("Fail to remove file (%s)", path.c_str());
257 typedef void (*PreloadDelegate)();
258 PreloadDelegate preloadDelegate;
260 int ret = createDelegate(__hostHandle,
263 "Tizen.Runtime.Preloader",
265 (void**)&preloadDelegate);
268 _ERR("Failed to create delegate for Tizen.Runtime Preload (0x%08x)", ret);
276 bool initializeCoreClr(PathManager* pm, const std::string& tpa)
278 const char *propertyKeys[] = {
279 "TRUSTED_PLATFORM_ASSEMBLIES",
282 "NATIVE_DLL_SEARCH_DIRECTORIES",
283 "AppDomainCompatSwitch"
286 const char *propertyValues[] = {
288 pm->getAppPaths().c_str(),
289 pm->getAppNIPaths().c_str(),
290 pm->getNativeDllSearchingPaths().c_str(),
291 "UseLatestBehaviorWhenTFMNotSpecified"
294 std::string selfPath = readSelfPath();
296 int st = initializeClr(selfPath.c_str(),
298 sizeof(propertyKeys) / sizeof(propertyKeys[0]),
305 _ERR("initialize core clr fail! (0x%08x)", st);
309 pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
311 _INFO("Initialize core clr success");
315 int CoreRuntime::initialize(const char* appType, LaunchMode launchMode)
318 _ERR("CoreRuntime is already initialized");
322 // Intiailize ecore first (signal handlers, etc.) before runtime init.
325 // set language environment to support ICU
329 env = getenv("CORECLR_ENABLE_PROFILING");
330 if (env != nullptr && !strcmp(env, "1")) {
331 _INFO("profiling mode on");
332 __isProfileMode = true;
335 // plugin initialize should be called before creating threads.
336 // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
337 // When attaching to a secure zone, if there is a created thread, it will failed.
338 // So, plugin initialize should be called before creating threads.
339 if (initializePluginManager(appType) < 0) {
340 _ERR("Failed to initialize PluginManager");
343 // checkInjection checks dotnet-launcher run mode
344 // At the moment, this mechanism is used only when the Memory Profiler is started.
345 int res = checkInjection();
347 _ERR("Failed to initnialize Memory Profiler");
352 // libunwind library is used to unwind stack frame, but libunwind for ARM
353 // does not support ARM vfpv3/NEON registers in DWARF format correctly.
354 // Therefore let's disable stack unwinding using DWARF information
355 // See https://github.com/dotnet/coreclr/issues/6698
357 // libunwind use following methods to unwind stack frame.
358 // UNW_ARM_METHOD_ALL 0xFF
359 // UNW_ARM_METHOD_DWARF 0x01
360 // UNW_ARM_METHOD_FRAME 0x02
361 // UNW_ARM_METHOD_EXIDX 0x04
362 putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
365 // Enable diagnostics.
366 // clr create clr-debug-pipe-xxx and dotnet-diagnostics-xxx file under /tmp dir.
367 putenv(const_cast<char *>("COMPlus_EnableDiagnostics=1"));
369 // Write Debug.WriteLine to stderr
370 putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
372 #ifdef USE_DEFAULT_BASE_ADDR
373 putenv(const_cast<char *>("COMPlus_UseDefaultBaseAddr=1"));
374 #endif // USE_DEFAULT_BASE_ADDR
376 // read string from external file and set them to environment value.
380 __pm = new PathManager();
381 } catch (const std::exception& e) {
382 _ERR("Failed to create PathManager");
386 char* pluginDllPaths = pluginGetDllPath();
387 if (pluginDllPaths && pluginDllPaths[0] != '\0') {
388 __pm->addPlatformAssembliesPaths(pluginDllPaths, true);
391 char* pluginNativePaths = pluginGetNativeDllSearchingPath();
392 if (pluginNativePaths && pluginNativePaths[0] != '\0') {
393 __pm->addNativeDllSearchingPaths(pluginNativePaths, true);
396 pluginHasLogControl();
398 std::string libCoreclr(concatPath(__pm->getRuntimePath(), "libcoreclr.so"));
400 __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
401 if (__coreclrLib == nullptr) {
402 char *err = dlerror();
403 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
407 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
409 variable = (type)dlsym(__coreclrLib, name); \
410 if (variable == nullptr) { \
411 _ERR(name " is not found in the libcoreclr.so"); \
416 CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
417 CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
418 CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
419 CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
421 #undef CORELIB_RETURN_IF_NOSYM
423 _INFO("libcoreclr dlopen and dlsym success");
425 // Set environment for System.Environment.SpecialFolder
426 // Below function creates dbus connection by callging storage API.
427 // If dbus connection is created bofere fork(), forked process cannot use dbus.
428 // To avoid gdbus blocking issue, below function should be called after fork()
429 initEnvForSpecialFolder();
432 char* pluginTPA = pluginGetTPA();
433 if (pluginTPA && pluginTPA[0] != '\0') {
434 tpa = std::string(pluginTPA);
436 addAssembliesFromDirectories(__pm->getPlatformAssembliesPaths(), tpa);
439 if (!initializeCoreClr(__pm, tpa)) {
440 _ERR("Failed to initialize coreclr");
444 int st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Environment", "SetEnvironmentVariable", (void**)&setEnvironmentVariable);
445 if (st < 0 || setEnvironmentVariable == nullptr) {
446 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Environment -> SetEnvironmentVariable failed (0x%08x)", st);
450 st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Profiler", "StopProfileAfterDelay", (void**)&stopProfileAfterDelay);
451 if (st < 0 || stopProfileAfterDelay == nullptr) {
452 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Profiler -> StopProfileAfterDelay failed (0x%08x)", st);
456 st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.AppSetting", "SetSwitch", (void**)&setSwitch);
457 if (st < 0 || setSwitch == nullptr) {
458 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.AppSetting -> SetSwitch failed (0x%08x)", st);
462 if (launchMode == LaunchMode::loader) {
463 // terminate candidate process if language is changed.
464 // CurrentCulture created for preloaded dlls should be updated.
465 vconf_notify_key_changed(VCONFKEY_LANGSET, langChangedCB, NULL);
467 // preload libraries and manage dlls for optimizing startup time
470 // The debug pipe created in the candidate process has a "User" label.
471 // As a result, smack deny occurs when app process try to access the debug pipe.
472 // Also, since debugging is performed only in standalone mode,
473 // the debug pipe doesnot be used in the candidate process.
474 // So, to avoid smack deny error, delete unused debug pipe files.
478 __initialized = true;
480 _INFO("CoreRuntime initialize success");
485 void CoreRuntime::finalize()
487 // call plugin finalize function to notify finalize to plugin
488 // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
491 // ignore the signal generated by an exception that occurred during shutdown
492 checkOnTerminate = true;
494 // workaround : to prevent crash while process terminate on profiling mode,
495 // kill process immediately.
496 // see https://github.com/dotnet/coreclr/issues/26687
497 if (__isProfileMode) {
498 _INFO("shutdown process immediately.");
502 if (__hostHandle != nullptr) {
503 int st = shutdown(__hostHandle, __domainId);
505 _ERR("shutdown core clr fail! (0x%08x)", st);
506 __hostHandle = nullptr;
509 if (__coreclrLib != nullptr) {
510 if (dlclose(__coreclrLib) != 0) {
511 _ERR("libcoreclr.so close failed");
514 __coreclrLib = nullptr;
517 finalizePluginManager();
524 _INFO("CoreRuntime finalized");
527 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[], bool profile)
529 if (!__initialized) {
530 _ERR("Runtime is not initialized");
534 if (path == nullptr) {
535 _ERR("executable path is null");
540 _ERR("File not exist : %s", path);
544 // VD has their own signal handler.
545 if (!pluginHasLogControl()) {
546 registerSigHandler();
549 pluginSetAppInfo(appId, path);
551 // temporal root path is overrided to real application root path
552 __pm->setAppRootPath(root);
554 // set application data path to coreclr environment.
555 // application data path can be changed by owner. So, we have to set data path just before launching.
556 char* localDataPath = app_get_data_path();
557 if (localDataPath != nullptr) {
558 setEnvironmentVariable("XDG_DATA_HOME", localDataPath);
560 // set profile.data path and collect/use it if it non-exists/exists.
562 char multiCoreJitProfile[strlen(localDataPath) + strlen(PROFILE_BASENAME) + 1];
563 memcpy(multiCoreJitProfile, localDataPath, strlen(localDataPath) + 1);
564 strncat(multiCoreJitProfile, PROFILE_BASENAME, strlen(PROFILE_BASENAME));
566 setEnvironmentVariable("COMPlus_MultiCoreJitProfile", multiCoreJitProfile);
567 setEnvironmentVariable("COMPlus_MultiCoreJitMinNumCpus", "1");
569 // stop profiling and write collected data after delay if env value is set.
570 char *env = getenv("CLR_MCJ_PROFILE_WRITE_DELAY");
571 if (env != nullptr) {
572 int delay = std::atoi(env);
573 // To avoid undefined behavior by out-of-range input(atoi), set max delay value to 100.
575 if (delay > MAX_DELAY_SEC) delay = MAX_DELAY_SEC;
576 stopProfileAfterDelay(delay);
580 if (exist(multiCoreJitProfile)) {
581 setEnvironmentVariable("COMPlus_MultiCoreJitNoProfileGather", "1");
587 setSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true);
589 vconf_ignore_key_changed(VCONFKEY_LANGSET, langChangedCB);
591 pluginBeforeExecute();
593 _INFO("execute assembly : %s", path);
595 unsigned int ret = 0;
596 int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
598 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
602 } // namespace dotnetcore
603 } // namespace runtime