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 void* __coreclrLib = nullptr;
60 static void* __hostHandle = nullptr;
61 static unsigned int __domainId = -1;
62 static bool __initialized = false;
63 static bool __isProfileMode = false;
64 PathManager* CoreRuntime::__pm = nullptr;
66 static std::vector<std::string> __envList;
68 static void setEnvFromFile()
71 std::ifstream inFile(ENV_FILE_PATH);
76 _INFO("coreclr_env.list is found");
79 while (std::getline(inFile, token, '\n')) {
81 __envList.push_back(token);
85 for (unsigned int i = 0; i < __envList.size(); i++) {
86 putenv(const_cast<char *>(__envList[i].c_str()));
89 _INFO("coreclr_env.list file is not found. skip");
93 #define _unused(x) ((void)(x))
95 struct sigaction sig_abrt_new;
96 struct sigaction sig_abrt_old;
98 static bool checkOnSigabrt = false;
99 static bool checkOnTerminate = false;
101 static void onSigabrt(int signum)
103 // use unused variable to avoid build warning
104 ssize_t ret = write(STDERR_FILENO, "onSigabrt called\n", 17);
106 if (checkOnTerminate) {
107 ret = write(STDERR_FILENO, "onSigabrt called while terminate. go to exit\n", 45);
112 if (checkOnSigabrt) {
113 ret = write(STDERR_FILENO, "onSigabrt called again. go to exit\n", 35);
118 checkOnSigabrt = true;
119 if (sigaction(SIGABRT, &sig_abrt_old, NULL) == 0) {
120 if (raise(signum) < 0) {
121 ret = write(STDERR_FILENO, "Fail to raise SIGABRT\n", 22);
124 ret = write(STDERR_FILENO, "Fail to set original SIGABRT handler\n", 37);
129 static void registerSigHandler()
131 sig_abrt_new.sa_handler = onSigabrt;
132 if (sigemptyset(&sig_abrt_new.sa_mask) != 0) {
133 _ERR("Fail to sigemptyset");
136 if (sigaction(SIGABRT, &sig_abrt_new, &sig_abrt_old) < 0) {
137 _ERR("Fail to add sig handler");
141 static bool storage_cb(int id, storage_type_e type, storage_state_e state, const char *path, void *user_data)
143 int* tmp = (int*)user_data;
144 if (type == STORAGE_TYPE_INTERNAL)
153 static void initEnvForSpecialFolder()
159 error = storage_foreach_device_supported(storage_cb, &storageId);
160 if (error != STORAGE_ERROR_NONE) {
164 error = storage_get_directory(storageId, STORAGE_DIRECTORY_IMAGES, &path);
165 if (error == STORAGE_ERROR_NONE && path != NULL) {
166 setenv("XDG_PICTURES_DIR", const_cast<char *>(path), 1);
171 error = storage_get_directory(storageId, STORAGE_DIRECTORY_MUSIC, &path);
172 if (error == STORAGE_ERROR_NONE && path != NULL) {
173 setenv("XDG_MUSIC_DIR", const_cast<char *>(path), 1);
178 error = storage_get_directory(storageId, STORAGE_DIRECTORY_VIDEOS, &path);
179 if (error == STORAGE_ERROR_NONE && path != NULL) {
180 setenv("XDG_VIDEOS_DIR", const_cast<char *>(path), 1);
186 // terminate candidate process when language changed
187 // icu related data (CultureInfo, etc) should be recreated.
188 static void langChangedCB(keynode_t *key, void* data)
190 _INFO("terminiate candidate process to update language.");
194 static void setLang()
196 char* lang = vconf_get_str(VCONFKEY_LANGSET);
198 _ERR("Fail to get language from vconf");
202 // In order to operate ICU (used for globalization) normally, the following
203 // environment variables must be set before using ICU API.
204 // When running Applicaiton, the following environment variables are set by AppFW.
205 // But when preloading the dll in the candidate process, the following environment variables are not set
206 // As a result, CultureInfo is incorrectly generated and malfunctions.
207 // For example, uloc_getDefault() returns en_US_POSIX, CultureInfo is set to invariant mode.
208 setenv("LANG", const_cast<char *>(lang), 1);
209 setlocale(LC_ALL, const_cast<char *>(lang));
214 static std::string readSelfPath()
217 ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
220 return std::string(buff);
226 static void removeDebugPipe()
229 struct dirent* entry;
230 char debugPipeFiles[PATH_MAX];;
231 sprintf(debugPipeFiles, "/tmp/clr-debug-pipe-%d-", getpid());
233 dir = opendir("/tmp");
234 if (dir == nullptr) {
235 _ERR("Fail to open /tmp directory");
239 while ((entry = readdir(dir)) != nullptr) {
240 std::string path = concatPath("/tmp", entry->d_name);
241 if (path.find(debugPipeFiles) != std::string::npos) {
242 if (!removeFile(path)) {
243 _ERR("Fail to remove file (%s)", path.c_str());
253 typedef void (*PreloadDelegate)();
254 PreloadDelegate preloadDelegate;
256 int ret = createDelegate(__hostHandle,
259 "Tizen.Runtime.Preloader",
261 (void**)&preloadDelegate);
264 _ERR("Failed to create delegate for Tizen.Runtime Preload (0x%08x)", ret);
272 bool initializeCoreClr(PathManager* pm, const std::string& tpa)
274 const char *propertyKeys[] = {
275 "TRUSTED_PLATFORM_ASSEMBLIES",
278 "NATIVE_DLL_SEARCH_DIRECTORIES",
279 "AppDomainCompatSwitch"
282 const char *propertyValues[] = {
284 pm->getAppPaths().c_str(),
285 pm->getAppNIPaths().c_str(),
286 pm->getNativeDllSearchingPaths().c_str(),
287 "UseLatestBehaviorWhenTFMNotSpecified"
290 std::string selfPath = readSelfPath();
292 int st = initializeClr(selfPath.c_str(),
294 sizeof(propertyKeys) / sizeof(propertyKeys[0]),
301 _ERR("initialize core clr fail! (0x%08x)", st);
305 pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
307 _INFO("Initialize core clr success");
311 int CoreRuntime::initialize(const char* appType, LaunchMode launchMode)
314 _ERR("CoreRuntime is already initialized");
318 // Intiailize ecore first (signal handlers, etc.) before runtime init.
321 // set language environment to support ICU
325 env = getenv("CORECLR_ENABLE_PROFILING");
326 if (env != nullptr && !strcmp(env, "1")) {
327 _INFO("profiling mode on");
328 __isProfileMode = true;
331 // plugin initialize should be called before creating threads.
332 // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
333 // When attaching to a secure zone, if there is a created thread, it will failed.
334 // So, plugin initialize should be called before creating threads.
335 if (initializePluginManager(appType) < 0) {
336 _ERR("Failed to initialize PluginManager");
339 // checkInjection checks dotnet-launcher run mode
340 // At the moment, this mechanism is used only when the Memory Profiler is started.
341 int res = checkInjection();
343 _ERR("Failed to initnialize Memory Profiler");
348 // libunwind library is used to unwind stack frame, but libunwind for ARM
349 // does not support ARM vfpv3/NEON registers in DWARF format correctly.
350 // Therefore let's disable stack unwinding using DWARF information
351 // See https://github.com/dotnet/coreclr/issues/6698
353 // libunwind use following methods to unwind stack frame.
354 // UNW_ARM_METHOD_ALL 0xFF
355 // UNW_ARM_METHOD_DWARF 0x01
356 // UNW_ARM_METHOD_FRAME 0x02
357 // UNW_ARM_METHOD_EXIDX 0x04
358 putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
361 // Enable diagnostics.
362 // clr create clr-debug-pipe-xxx and dotnet-diagnostics-xxx file under /tmp dir.
363 putenv(const_cast<char *>("COMPlus_EnableDiagnostics=1"));
365 // Write Debug.WriteLine to stderr
366 putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
368 #ifdef USE_DEFAULT_BASE_ADDR
369 putenv(const_cast<char *>("COMPlus_UseDefaultBaseAddr=1"));
370 #endif // USE_DEFAULT_BASE_ADDR
372 // read string from external file and set them to environment value.
376 __pm = new PathManager();
377 } catch (const std::exception& e) {
378 _ERR("Failed to create PathManager");
382 char* pluginPath = pluginGetDllPath();
384 __pm->addPlatformAssembliesPaths(pluginPath);
387 pluginHasLogControl();
389 std::string libCoreclr(concatPath(__pm->getRuntimePath(), "libcoreclr.so"));
391 __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
392 if (__coreclrLib == nullptr) {
393 char *err = dlerror();
394 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
398 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
400 variable = (type)dlsym(__coreclrLib, name); \
401 if (variable == nullptr) { \
402 _ERR(name " is not found in the libcoreclr.so"); \
407 CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
408 CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
409 CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
410 CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
412 #undef CORELIB_RETURN_IF_NOSYM
414 _INFO("libcoreclr dlopen and dlsym success");
416 // Set environment for System.Environment.SpecialFolder
417 // Below function creates dbus connection by callging storage API.
418 // If dbus connection is created bofere fork(), forked process cannot use dbus.
419 // To avoid gdbus blocking issue, below function should be called after fork()
420 initEnvForSpecialFolder();
423 char* pluginTPA = pluginGetTPA();
425 tpa = std::string(pluginTPA);
427 addAssembliesFromDirectories(__pm->getPlatformAssembliesPaths(), tpa);
430 if (!initializeCoreClr(__pm, tpa)) {
431 _ERR("Failed to initialize coreclr");
435 int st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Environment", "SetEnvironmentVariable", (void**)&setEnvironmentVariable);
436 if (st < 0 || setEnvironmentVariable == nullptr) {
437 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Environment -> SetEnvironmentVariable failed (0x%08x)", st);
441 if (launchMode == LaunchMode::loader) {
442 // terminate candidate process if language is changed.
443 // CurrentCulture created for preloaded dlls should be updated.
444 vconf_notify_key_changed(VCONFKEY_LANGSET, langChangedCB, NULL);
446 // preload libraries and manage dlls for optimizing startup time
449 // The debug pipe created in the candidate process has a "User" label.
450 // As a result, smack deny occurs when app process try to access the debug pipe.
451 // Also, since debugging is performed only in standalone mode,
452 // the debug pipe doesnot be used in the candidate process.
453 // 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[])
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);
541 vconf_ignore_key_changed(VCONFKEY_LANGSET, langChangedCB);
543 pluginBeforeExecute();
545 _INFO("execute assembly : %s", path);
547 unsigned int ret = 0;
548 int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
550 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
554 } // namespace dotnetcore
555 } // namespace runtime