af6ddaddfa510da38db8a9cf1d52a7e555c51e43
[platform/core/dotnet/launcher.git] / NativeLauncher / launcher / lib / core_runtime.cc
1 /*
2  * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17
18 #include <dlfcn.h>
19 #include <signal.h>
20 #include <dirent.h>
21
22 #include <string>
23 #include <fstream>
24 #include <vector>
25 #include <sstream>
26
27 #include <locale>
28 #include <codecvt>
29
30 #include <fcntl.h>
31 #include <sys/stat.h>
32 #include <sys/types.h>
33 #include <sys/wait.h>
34 #include <unistd.h>
35 #include <linux/limits.h>
36 #include <pthread.h>
37
38 #include <vconf.h>
39 #include <app_common.h>
40 #include <tzplatform_config.h>
41
42 #include <Ecore.h>
43
44 #include "injection.h"
45 #include "utils.h"
46 #include "log.h"
47 #include "core_runtime.h"
48 #include "plugin_manager.h"
49 #include "path_manager.h"
50
51 namespace tizen {
52 namespace runtime {
53 namespace dotnetcore {
54
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;
68
69 #define MAX_DELAY_SEC 100
70
71 static std::vector<std::string> __envList;
72
73 static void setEnvFromFile()
74 {
75         std::string envList;
76         std::ifstream inFile(ENV_FILE_PATH);
77
78         __envList.clear();
79
80         if (inFile) {
81                 _INFO("coreclr_env.list is found");
82
83                 std::string token;
84                 while (std::getline(inFile, token, '\n')) {
85                         if (!token.empty()) {
86                                 __envList.push_back(token);
87                         }
88                 }
89
90                 for (unsigned int i = 0; i < __envList.size(); i++) {
91                         putenv(const_cast<char *>(__envList[i].c_str()));
92                 }
93         } else {
94                 _INFO("coreclr_env.list file is not found. skip");
95         }
96 }
97
98 #define _unused(x) ((void)(x))
99
100 struct sigaction sig_abrt_new;
101 struct sigaction sig_abrt_old;
102
103 static bool checkOnSigabrt = false;
104 static bool checkOnTerminate = false;
105
106 static void onSigabrt(int signum)
107 {
108         // use unused variable to avoid build warning
109         ssize_t ret = write(STDERR_FILENO, "onSigabrt called\n", 17);
110
111         if (checkOnTerminate) {
112                 ret = write(STDERR_FILENO, "onSigabrt called while terminate. go to exit\n", 45);
113                 _unused(ret);
114                 exit(0);
115         }
116
117         if (checkOnSigabrt) {
118                 ret = write(STDERR_FILENO, "onSigabrt called again. go to exit\n", 35);
119                 _unused(ret);
120                 exit(0);
121         }
122
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);
127                 }
128         } else {
129                 ret = write(STDERR_FILENO, "Fail to set original SIGABRT handler\n", 37);
130         }
131         _unused(ret);
132 }
133
134 static void registerSigHandler()
135 {
136         sig_abrt_new.sa_handler = onSigabrt;
137         if (sigemptyset(&sig_abrt_new.sa_mask) != 0) {
138                 _ERR("Fail to sigemptyset");
139         }
140
141         if (sigaction(SIGABRT, &sig_abrt_new, &sig_abrt_old) < 0) {
142                 _ERR("Fail to add sig handler");
143         }
144 }
145
146 static void initEnvForSpecialFolder()
147 {
148         const char* path = NULL;
149         if (getenv("XDG_PICTURES_DIR") == NULL) {
150                 path = tzplatform_getenv(TZ_USER_IMAGES);
151                 if (path) {
152                         setenv("XDG_PICTURES_DIR", path, 1);
153                 }
154         }
155
156         if (getenv("XDG_MUSIC_DIR") == NULL) {
157                 path = tzplatform_getenv(TZ_USER_MUSIC);
158                 if (path) {
159                         setenv("XDG_MUSIC_DIR", path, 1);
160                 }
161         }
162
163         if (getenv("XDG_VIDEOS_DIR") == NULL) {
164                 path = tzplatform_getenv(TZ_USER_VIDEOS);
165                 if (path) {
166                         setenv("XDG_VIDEOS_DIR", path, 1);
167                 }
168         }
169 }
170
171 static void setLang()
172 {
173         //To reduce search overhead of libicuuc.so.xx
174         setenv("CLR_ICU_VERSION_OVERRIDE", "build", 1);
175
176         char* lang = vconf_get_str(VCONFKEY_LANGSET);
177         if (!lang) {
178                 _ERR("Fail to get language from vconf");
179                 return;
180         }
181
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));
190
191         free(lang);
192 }
193
194 static std::string readSelfPath()
195 {
196         char buff[PATH_MAX];
197         ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
198         if (len != -1) {
199                 buff[len] = '\0';
200                 return std::string(buff);
201         }
202
203         return "";
204 }
205
206 static void removeDebugPipe()
207 {
208         DIR *dir;
209         struct dirent* entry;
210         char debugPipeFiles[PATH_MAX];;
211         sprintf(debugPipeFiles, "/tmp/clr-debug-pipe-%d-", getpid());
212
213         dir = opendir("/tmp");
214         if (dir == nullptr) {
215                 _ERR("Fail to open /tmp directory");
216                 return;
217         }
218
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());
224                         }
225                 }
226         }
227
228         closedir(dir);
229 }
230
231 void preload()
232 {
233         typedef void (*PreloadDelegate)();
234         PreloadDelegate preloadDelegate;
235
236         int ret = createDelegate(__hostHandle,
237                 __domainId,
238                 "Tizen.Runtime",
239                 "Tizen.Runtime.Preloader",
240                 "Preload",
241                 (void**)&preloadDelegate);
242
243         if (ret < 0) {
244                 _ERR("Failed to create delegate for Tizen.Runtime Preload (0x%08x)", ret);
245         } else {
246                 preloadDelegate();
247         }
248
249         pluginPreload();
250 }
251
252 bool initializeCoreClr(PathManager* pm, const std::string& tpa)
253 {
254         bool ncdbStartupHook = isNCDBStartupHookProvided();
255
256         const char *propertyKeys[] = {
257                 "TRUSTED_PLATFORM_ASSEMBLIES",
258                 "APP_PATHS",
259                 "APP_NI_PATHS",
260                 "NATIVE_DLL_SEARCH_DIRECTORIES",
261                 "AppDomainCompatSwitch",
262                 ncdbStartupHook ? "STARTUP_HOOKS" : "" // must be the last one
263         };
264
265         const char *propertyValues[] = {
266                 tpa.c_str(),
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
272         };
273
274         std::string selfPath = readSelfPath();
275
276         int st = initializeClr(selfPath.c_str(),
277                                                         "TizenDotnetApp",
278                                                         sizeof(propertyKeys) / sizeof(propertyKeys[0]) - (ncdbStartupHook ? 0 : 1),
279                                                         propertyKeys,
280                                                         propertyValues,
281                                                         &__hostHandle,
282                                                         &__domainId);
283
284         if (st < 0) {
285                 _ERR("initialize core clr fail! (0x%08x)", st);
286                 return false;
287         }
288
289         pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
290
291         _INFO("Initialize core clr success");
292         return true;
293 }
294
295 int CoreRuntime::initialize(const char* appType, LaunchMode launchMode)
296 {
297         if (__initialized) {
298                 _ERR("CoreRuntime is already initialized");
299                 return -1;
300         }
301
302         // set language environment to support ICU
303         setLang();
304
305         char *env = nullptr;
306         env = getenv("CORECLR_ENABLE_PROFILING");
307         if (env != nullptr && !strcmp(env, "1")) {
308                 _INFO("profiling mode on");
309                 __isProfileMode = true;
310         }
311
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");
318                 return -1;
319         }
320
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();
324         if (res != 0) {
325                 _ERR("Failed to initnialize Memory Profiler");
326                 return -1;
327         }
328
329 #ifdef __arm__
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
334         //
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"));
341 #endif // __arm__
342
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"));
346
347         // Write Debug.WriteLine to stderr
348         putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
349
350 #ifdef USE_DEFAULT_BASE_ADDR
351         putenv(const_cast<char *>("COMPlus_UseDefaultBaseAddr=1"));
352 #endif // USE_DEFAULT_BASE_ADDR
353
354         // Disable config cache to set environment after coreclr_initialize()
355         putenv(const_cast<char *>("COMPlus_DisableConfigCache=1"));
356
357         // Set environment variable for System.Environment.SpecialFolder
358         initEnvForSpecialFolder();
359
360         // read string from external file and set them to environment value.
361         setEnvFromFile();
362
363         try {
364                 __pm = new PathManager();
365         } catch (const std::exception& e) {
366                 _ERR("Failed to create PathManager");
367                 return -1;
368         }
369
370         char* pluginDllPaths = pluginGetDllPath();
371         if (pluginDllPaths && pluginDllPaths[0] != '\0') {
372                 __pm->addPlatformAssembliesPaths(pluginDllPaths, true);
373         }
374
375         char* pluginNativePaths = pluginGetNativeDllSearchingPath();
376         if (pluginNativePaths && pluginNativePaths[0] != '\0') {
377                 __pm->addNativeDllSearchingPaths(pluginNativePaths, true);
378         }
379
380         char* pluginExtraDllPaths = pluginGetExtraDllPath();
381         if (pluginExtraDllPaths && pluginExtraDllPaths[0] != '\0') {
382                 __pm->setExtraDllPaths(pluginExtraDllPaths);
383         }
384
385         std::string libCoreclr(concatPath(__pm->getRuntimePath(), "libcoreclr.so"));
386
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);
391                 return -1;
392         }
393
394 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
395         do { \
396                 variable = (type)dlsym(__coreclrLib, name); \
397                 if (variable == nullptr) { \
398                         _ERR(name " is not found in the libcoreclr.so"); \
399                         return -1; \
400                 } \
401         } while (0)
402
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");
407
408 #undef CORELIB_RETURN_IF_NOSYM
409
410         _INFO("libcoreclr dlopen and dlsym success");
411
412         std::string tpa;
413         char* pluginTPA = pluginGetTPA();
414         if (pluginTPA && pluginTPA[0] != '\0') {
415                 tpa = std::string(pluginTPA);
416         } else {
417                 addAssembliesFromDirectories(__pm->getPlatformAssembliesPaths(), tpa);
418         }
419
420         if (!initializeCoreClr(__pm, tpa)) {
421                 _ERR("Failed to initialize coreclr");
422                 return -1;
423         }
424
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);
428                 return -1;
429         }
430
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);
434                 return -1;
435         }
436
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);
440                 return -1;
441         }
442
443         if (launchMode == LaunchMode::loader) {
444                 // preload libraries and manage dlls for optimizing startup time
445                 preload();
446
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.
452                 removeDebugPipe();
453         }
454
455         // VD has their own signal handler.
456         if (!pluginHasLogControl()) {
457                 registerSigHandler();
458         }
459
460         __initialized = true;
461
462         _INFO("CoreRuntime initialize success");
463
464         return 0;
465 }
466
467 void CoreRuntime::finalize()
468 {
469         // call plugin finalize function to notify finalize to plugin
470         // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
471         pluginFinalize();
472
473         // ignore the signal generated by an exception that occurred during shutdown
474         checkOnTerminate = true;
475
476         // workaround : to prevent crash while process terminate on profiling mode,
477         //                              kill process immediately.
478         // see https://github.com/dotnet/coreclr/issues/26687
479         if (__isProfileMode) {
480                 _INFO("shutdown process immediately.");
481                 _exit(0);
482         }
483
484         if (__hostHandle != nullptr) {
485                 int st = shutdown(__hostHandle, __domainId);
486                 if (st < 0)
487                         _ERR("shutdown core clr fail! (0x%08x)", st);
488                 __hostHandle = nullptr;
489         }
490
491         if (__coreclrLib != nullptr) {
492                 if (dlclose(__coreclrLib) != 0) {
493                         _ERR("libcoreclr.so close failed");
494                 }
495
496                 __coreclrLib = nullptr;
497         }
498
499         finalizePluginManager();
500
501         delete __pm;
502         __pm = NULL;
503
504         __envList.clear();
505
506         _INFO("CoreRuntime finalized");
507 }
508
509 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[], bool profile)
510 {
511         if (!__initialized) {
512                 _ERR("Runtime is not initialized");
513                 return -1;
514         }
515
516         if (path == nullptr) {
517                 _ERR("executable path is null");
518                 return -1;
519         }
520
521         if (!isFile(path)) {
522                 _ERR("File not exist : %s", path);
523                 return -1;
524         }
525
526         pluginSetAppInfo(appId, path);
527
528         // temporal root path is overrided to real application root path
529         __pm->setAppRootPath(root);
530
531         // set application data path to coreclr environment.
532         // application data path can be changed by owner. So, we have to set data path just before launching.
533         char* localDataPath = app_get_data_path();
534         if (localDataPath != nullptr) {
535                 setEnvironmentVariable("XDG_DATA_HOME", localDataPath);
536
537                 // set profile.data path and collect/use it if it non-exists/exists.
538                 if (profile) {
539                         char multiCoreJitProfile[strlen(localDataPath) + strlen(PROFILE_BASENAME) + 1];
540                         memcpy(multiCoreJitProfile, localDataPath, strlen(localDataPath) + 1);
541                         strncat(multiCoreJitProfile, PROFILE_BASENAME, strlen(PROFILE_BASENAME));
542
543                         setEnvironmentVariable("COMPlus_MultiCoreJitProfile", multiCoreJitProfile);
544                         setEnvironmentVariable("COMPlus_MultiCoreJitMinNumCpus", "1");
545
546                         if (exist(multiCoreJitProfile)) {
547                                 setEnvironmentVariable("COMPlus_MultiCoreJitNoProfileGather", "1");
548                                 _INFO("MCJ playing start for %s", appId);
549                         } else {
550                                 setEnvironmentVariable("COMPlus_MultiCoreJitNoProfileGather", "0");
551                                 // stop profiling and write collected data after delay if env value is set.
552                                 char *env = getenv("CLR_MCJ_PROFILE_WRITE_DELAY");
553                                 if (env != nullptr) {
554                                         int delay = std::atoi(env);
555                                         // To avoid undefined behavior by out-of-range input(atoi), set max delay value to 100.
556                                         if (delay > 0) {
557                                                 if (delay > MAX_DELAY_SEC) delay = MAX_DELAY_SEC;
558                                                 stopProfileAfterDelay(delay);
559                                         }
560                                 }
561                                 _INFO("MCJ recording start for %s", appId);
562                         }
563                 }
564                 free(localDataPath);
565         }
566
567         if (exist(__pm->getAppRootPath() + "/bin/" + DISABLE_IPV6_FILE)) {
568                 setSwitch("System.Net.DisableIPv6", true);
569         }
570
571         setSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true);
572
573         pluginBeforeExecute();
574
575         _INFO("execute assembly : %s", path);
576
577         unsigned int ret = 0;
578         int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
579         if (st < 0)
580                 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
581         return ret;
582 }
583
584 }  // namespace dotnetcore
585 }  // namespace runtime
586 }  // namespace tizen