2f1d7d6fa3942ea3e31f1030bb0ecf6d68801935
[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
37 #include <storage.h>
38 #include <vconf.h>
39 #include <app_common.h>
40
41 #include <Ecore.h>
42
43 #include "injection.h"
44 #include "utils.h"
45 #include "log.h"
46 #include "core_runtime.h"
47 #include "plugin_manager.h"
48 #include "path_manager.h"
49
50 namespace tizen {
51 namespace runtime {
52 namespace dotnetcore {
53
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;
67
68 #define MAX_DELAY_SEC 100
69
70 static std::vector<std::string> __envList;
71
72 static void setEnvFromFile()
73 {
74         std::string envList;
75         std::ifstream inFile(ENV_FILE_PATH);
76
77         __envList.clear();
78
79         if (inFile) {
80                 _INFO("coreclr_env.list is found");
81
82                 std::string token;
83                 while (std::getline(inFile, token, '\n')) {
84                         if (!token.empty()) {
85                                 __envList.push_back(token);
86                         }
87                 }
88
89                 for (unsigned int i = 0; i < __envList.size(); i++) {
90                         putenv(const_cast<char *>(__envList[i].c_str()));
91                 }
92         } else {
93                 _INFO("coreclr_env.list file is not found. skip");
94         }
95 }
96
97 #define _unused(x) ((void)(x))
98
99 struct sigaction sig_abrt_new;
100 struct sigaction sig_abrt_old;
101
102 static bool checkOnSigabrt = false;
103 static bool checkOnTerminate = false;
104
105 static void onSigabrt(int signum)
106 {
107         // use unused variable to avoid build warning
108         ssize_t ret = write(STDERR_FILENO, "onSigabrt called\n", 17);
109
110         if (checkOnTerminate) {
111                 ret = write(STDERR_FILENO, "onSigabrt called while terminate. go to exit\n", 45);
112                 _unused(ret);
113                 exit(0);
114         }
115
116         if (checkOnSigabrt) {
117                 ret = write(STDERR_FILENO, "onSigabrt called again. go to exit\n", 35);
118                 _unused(ret);
119                 exit(0);
120         }
121
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);
126                 }
127         } else {
128                 ret = write(STDERR_FILENO, "Fail to set original SIGABRT handler\n", 37);
129         }
130         _unused(ret);
131 }
132
133 static void registerSigHandler()
134 {
135         sig_abrt_new.sa_handler = onSigabrt;
136         if (sigemptyset(&sig_abrt_new.sa_mask) != 0) {
137                 _ERR("Fail to sigemptyset");
138         }
139
140         if (sigaction(SIGABRT, &sig_abrt_new, &sig_abrt_old) < 0) {
141                 _ERR("Fail to add sig handler");
142         }
143 }
144
145 static bool storage_cb(int id, storage_type_e type, storage_state_e state, const char *path, void *user_data)
146 {
147         int* tmp = (int*)user_data;
148         if (type == STORAGE_TYPE_INTERNAL)
149         {
150                 *tmp = id;
151                 return false;
152         }
153
154         return true;
155 }
156
157 static void setSpecialFolder(storage_directory_e type, const char* key)
158 {
159         int error;
160         char* path = NULL;
161         static int __storageId = -1;
162
163         if (__storageId < 0) {
164                 error = storage_foreach_device_supported(storage_cb, &__storageId);
165                 if (error != STORAGE_ERROR_NONE) {
166                         return;
167                 }
168         }
169
170         error = storage_get_directory(__storageId, type, &path);
171         if (error == STORAGE_ERROR_NONE && path != NULL) {
172                 setenv(key, const_cast<char *>(path), 1);
173                 free(path);
174         }
175 }
176
177 static void initEnvForSpecialFolder()
178 {
179         if (getenv("XDG_PICTURES_DIR") == NULL) {
180                 setSpecialFolder(STORAGE_DIRECTORY_IMAGES, "XDG_PICTURES_DIR");
181         }
182
183         if (getenv("XDG_MUSIC_DIR") == NULL) {
184                 setSpecialFolder(STORAGE_DIRECTORY_MUSIC, "XDG_MUSIC_DIR");
185         }
186
187         if (getenv("XDG_VIDEOS_DIR") == NULL) {
188                 setSpecialFolder(STORAGE_DIRECTORY_VIDEOS, "XDG_VIDEOS_DIR");
189         }
190 }
191
192 // terminate candidate process when language changed
193 // icu related data (CultureInfo, etc) should be recreated.
194 static void langChangedCB(keynode_t *key, void* data)
195 {
196         _INFO("terminiate candidate process to update language.");
197         exit(0);
198 }
199
200 static void setLang()
201 {
202         char* lang = vconf_get_str(VCONFKEY_LANGSET);
203         if (!lang) {
204                 _ERR("Fail to get language from vconf");
205                 return;
206         }
207
208         // In order to operate ICU (used for globalization) normally, the following
209         // environment variables must be set before using ICU API.
210         // When running Applicaiton, the following environment variables are set by AppFW.
211         // But when preloading the dll in the candidate process, the following environment variables are not set
212         // As a result, CultureInfo is incorrectly generated and malfunctions.
213         // For example, uloc_getDefault() returns en_US_POSIX, CultureInfo is set to invariant mode.
214         setenv("LANG", const_cast<char *>(lang), 1);
215         setlocale(LC_ALL, const_cast<char *>(lang));
216
217         free(lang);
218 }
219
220 static std::string readSelfPath()
221 {
222         char buff[PATH_MAX];
223         ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
224         if (len != -1) {
225                 buff[len] = '\0';
226                 return std::string(buff);
227         }
228
229         return "";
230 }
231
232 static void removeDebugPipe()
233 {
234         DIR *dir;
235         struct dirent* entry;
236         char debugPipeFiles[PATH_MAX];;
237         sprintf(debugPipeFiles, "/tmp/clr-debug-pipe-%d-", getpid());
238
239         dir = opendir("/tmp");
240         if (dir == nullptr) {
241                 _ERR("Fail to open /tmp directory");
242                 return;
243         }
244
245         while ((entry = readdir(dir)) != nullptr) {
246                 std::string path = concatPath("/tmp", entry->d_name);
247                 if (path.find(debugPipeFiles) != std::string::npos) {
248                         if (!removeFile(path)) {
249                                 _ERR("Fail to remove file (%s)", path.c_str());
250                         }
251                 }
252         }
253
254         closedir(dir);
255 }
256
257 void preload()
258 {
259         typedef void (*PreloadDelegate)();
260         PreloadDelegate preloadDelegate;
261
262         int ret = createDelegate(__hostHandle,
263                 __domainId,
264                 "Tizen.Runtime",
265                 "Tizen.Runtime.Preloader",
266                 "Preload",
267                 (void**)&preloadDelegate);
268
269         if (ret < 0) {
270                 _ERR("Failed to create delegate for Tizen.Runtime Preload (0x%08x)", ret);
271         } else {
272                 preloadDelegate();
273         }
274
275         pluginPreload();
276 }
277
278 bool initializeCoreClr(PathManager* pm, const std::string& tpa)
279 {
280         const char *propertyKeys[] = {
281                 "TRUSTED_PLATFORM_ASSEMBLIES",
282                 "APP_PATHS",
283                 "APP_NI_PATHS",
284                 "NATIVE_DLL_SEARCH_DIRECTORIES",
285                 "AppDomainCompatSwitch"
286         };
287
288         const char *propertyValues[] = {
289                 tpa.c_str(),
290                 pm->getAppPaths().c_str(),
291                 pm->getAppNIPaths().c_str(),
292                 pm->getNativeDllSearchingPaths().c_str(),
293                 "UseLatestBehaviorWhenTFMNotSpecified"
294         };
295
296         std::string selfPath = readSelfPath();
297
298         int st = initializeClr(selfPath.c_str(),
299                                                         "TizenDotnetApp",
300                                                         sizeof(propertyKeys) / sizeof(propertyKeys[0]),
301                                                         propertyKeys,
302                                                         propertyValues,
303                                                         &__hostHandle,
304                                                         &__domainId);
305
306         if (st < 0) {
307                 _ERR("initialize core clr fail! (0x%08x)", st);
308                 return false;
309         }
310
311         pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
312
313         _INFO("Initialize core clr success");
314         return true;
315 }
316
317 int CoreRuntime::initialize(const char* appType, LaunchMode launchMode)
318 {
319         if (__initialized) {
320                 _ERR("CoreRuntime is already initialized");
321                 return -1;
322         }
323
324         // Intiailize ecore first (signal handlers, etc.) before runtime init.
325         ecore_init();
326
327         // set language environment to support ICU
328         setLang();
329
330         char *env = nullptr;
331         env = getenv("CORECLR_ENABLE_PROFILING");
332         if (env != nullptr && !strcmp(env, "1")) {
333                 _INFO("profiling mode on");
334                 __isProfileMode = true;
335         }
336
337         // plugin initialize should be called before creating threads.
338         // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
339         // When attaching to a secure zone, if there is a created thread, it will failed.
340         // So, plugin initialize should be called before creating threads.
341         if (initializePluginManager(appType) < 0) {
342                 _ERR("Failed to initialize PluginManager");
343         }
344
345         // checkInjection checks dotnet-launcher run mode
346         // At the moment, this mechanism is used only when the Memory Profiler is started.
347         int res = checkInjection();
348         if (res != 0) {
349                 _ERR("Failed to initnialize Memory Profiler");
350                 return -1;
351         }
352
353 #ifdef __arm__
354         // libunwind library is used to unwind stack frame, but libunwind for ARM
355         // does not support ARM vfpv3/NEON registers in DWARF format correctly.
356         // Therefore let's disable stack unwinding using DWARF information
357         // See https://github.com/dotnet/coreclr/issues/6698
358         //
359         // libunwind use following methods to unwind stack frame.
360         // UNW_ARM_METHOD_ALL          0xFF
361         // UNW_ARM_METHOD_DWARF        0x01
362         // UNW_ARM_METHOD_FRAME        0x02
363         // UNW_ARM_METHOD_EXIDX        0x04
364         putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
365 #endif // __arm__
366
367         // Enable diagnostics.
368         // clr create clr-debug-pipe-xxx and dotnet-diagnostics-xxx file under /tmp dir.
369         putenv(const_cast<char *>("COMPlus_EnableDiagnostics=1"));
370
371         // Write Debug.WriteLine to stderr
372         putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
373
374 #ifdef USE_DEFAULT_BASE_ADDR
375         putenv(const_cast<char *>("COMPlus_UseDefaultBaseAddr=1"));
376 #endif // USE_DEFAULT_BASE_ADDR
377
378         // Disable config cache to set environment after coreclr_initialize()
379         putenv(const_cast<char *>("COMPlus_DisableConfigCache=1"));
380
381         // read string from external file and set them to environment value.
382         setEnvFromFile();
383
384         try {
385                 __pm = new PathManager();
386         } catch (const std::exception& e) {
387                 _ERR("Failed to create PathManager");
388                 return -1;
389         }
390
391         char* pluginDllPaths = pluginGetDllPath();
392         if (pluginDllPaths && pluginDllPaths[0] != '\0') {
393                 __pm->addPlatformAssembliesPaths(pluginDllPaths, true);
394         }
395
396         char* pluginNativePaths = pluginGetNativeDllSearchingPath();
397         if (pluginNativePaths && pluginNativePaths[0] != '\0') {
398                 __pm->addNativeDllSearchingPaths(pluginNativePaths, true);
399         }
400
401         char* pluginExtraDllPaths = pluginGetExtraDllPath();
402         if (pluginExtraDllPaths && pluginExtraDllPaths[0] != '\0') {
403                 __pm->setExtraDllPaths(pluginExtraDllPaths);
404         }
405
406         pluginHasLogControl();
407
408         std::string libCoreclr(concatPath(__pm->getRuntimePath(), "libcoreclr.so"));
409
410         __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
411         if (__coreclrLib == nullptr) {
412                 char *err = dlerror();
413                 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
414                 return -1;
415         }
416
417 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
418         do { \
419                 variable = (type)dlsym(__coreclrLib, name); \
420                 if (variable == nullptr) { \
421                         _ERR(name " is not found in the libcoreclr.so"); \
422                         return -1; \
423                 } \
424         } while (0)
425
426         CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
427         CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
428         CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
429         CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
430
431 #undef CORELIB_RETURN_IF_NOSYM
432
433         _INFO("libcoreclr dlopen and dlsym success");
434
435         // Set environment for System.Environment.SpecialFolder
436         // Below function creates dbus connection by callging storage API.
437         // If dbus connection is created bofere fork(), forked process cannot use dbus.
438         // To avoid gdbus blocking issue, below function should be called after fork()
439         initEnvForSpecialFolder();
440
441         std::string tpa;
442         char* pluginTPA = pluginGetTPA();
443         if (pluginTPA && pluginTPA[0] != '\0') {
444                 tpa = std::string(pluginTPA);
445         } else {
446                 addAssembliesFromDirectories(__pm->getPlatformAssembliesPaths(), tpa);
447         }
448
449         if (!initializeCoreClr(__pm, tpa)) {
450                 _ERR("Failed to initialize coreclr");
451                 return -1;
452         }
453
454         int st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Environment", "SetEnvironmentVariable", (void**)&setEnvironmentVariable);
455         if (st < 0 || setEnvironmentVariable == nullptr) {
456                 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Environment -> SetEnvironmentVariable failed (0x%08x)", st);
457                 return -1;
458         }
459
460         st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Profiler", "StopProfileAfterDelay", (void**)&stopProfileAfterDelay);
461         if (st < 0 || stopProfileAfterDelay == nullptr) {
462                 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Profiler -> StopProfileAfterDelay failed (0x%08x)", st);
463                 return -1;
464         }
465
466         st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.AppSetting", "SetSwitch", (void**)&setSwitch);
467         if (st < 0 || setSwitch == nullptr) {
468                 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.AppSetting -> SetSwitch failed (0x%08x)", st);
469                 return -1;
470         }
471
472         if (launchMode == LaunchMode::loader) {
473                 // terminate candidate process if language is changed.
474                 // CurrentCulture created for preloaded dlls should be updated.
475                 vconf_notify_key_changed(VCONFKEY_LANGSET, langChangedCB, NULL);
476
477                 // preload libraries and manage dlls for optimizing startup time
478                 preload();
479
480                 // The debug pipe created in the candidate process has a "User" label.
481                 // As a result, smack deny occurs when app process try to access the debug pipe.
482                 // Also, since debugging is performed only in standalone mode,
483                 // the debug pipe doesnot be used in the candidate process.
484                 // So, to avoid smack deny error, delete unused debug pipe files.
485                 removeDebugPipe();
486         }
487
488         __initialized = true;
489
490         _INFO("CoreRuntime initialize success");
491
492         return 0;
493 }
494
495 void CoreRuntime::finalize()
496 {
497         // call plugin finalize function to notify finalize to plugin
498         // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
499         pluginFinalize();
500
501         // ignore the signal generated by an exception that occurred during shutdown
502         checkOnTerminate = true;
503
504         // workaround : to prevent crash while process terminate on profiling mode,
505         //              kill process immediately.
506         // see https://github.com/dotnet/coreclr/issues/26687
507         if (__isProfileMode) {
508                 _INFO("shutdown process immediately.");
509                 _exit(0);
510         }
511
512         if (__hostHandle != nullptr) {
513                 int st = shutdown(__hostHandle, __domainId);
514                 if (st < 0)
515                         _ERR("shutdown core clr fail! (0x%08x)", st);
516                 __hostHandle = nullptr;
517         }
518
519         if (__coreclrLib != nullptr) {
520                 if (dlclose(__coreclrLib) != 0) {
521                         _ERR("libcoreclr.so close failed");
522                 }
523
524                 __coreclrLib = nullptr;
525         }
526
527         finalizePluginManager();
528
529         delete __pm;
530         __pm = NULL;
531
532         __envList.clear();
533
534         _INFO("CoreRuntime finalized");
535 }
536
537 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[], bool profile)
538 {
539         if (!__initialized) {
540                 _ERR("Runtime is not initialized");
541                 return -1;
542         }
543
544         if (path == nullptr) {
545                 _ERR("executable path is null");
546                 return -1;
547         }
548
549         if (!isFile(path)) {
550                 _ERR("File not exist : %s", path);
551                 return -1;
552         }
553
554         // VD has their own signal handler.
555         if (!pluginHasLogControl()) {
556                 registerSigHandler();
557         }
558
559         pluginSetAppInfo(appId, path);
560
561         // temporal root path is overrided to real application root path
562         __pm->setAppRootPath(root);
563
564         // set application data path to coreclr environment.
565         // application data path can be changed by owner. So, we have to set data path just before launching.
566         char* localDataPath = app_get_data_path();
567         if (localDataPath != nullptr) {
568                 setEnvironmentVariable("XDG_DATA_HOME", localDataPath);
569
570                 // set profile.data path and collect/use it if it non-exists/exists.
571                 if (profile) {
572                         char multiCoreJitProfile[strlen(localDataPath) + strlen(PROFILE_BASENAME) + 1];
573                         memcpy(multiCoreJitProfile, localDataPath, strlen(localDataPath) + 1);
574                         strncat(multiCoreJitProfile, PROFILE_BASENAME, strlen(PROFILE_BASENAME));
575
576                         setEnvironmentVariable("COMPlus_MultiCoreJitProfile", multiCoreJitProfile);
577                         setEnvironmentVariable("COMPlus_MultiCoreJitMinNumCpus", "1");
578
579                         if (exist(multiCoreJitProfile)) {
580                                 setEnvironmentVariable("COMPlus_MultiCoreJitNoProfileGather", "1");
581                         } else {
582                                 setEnvironmentVariable("COMPlus_MultiCoreJitNoProfileGather", "0");
583                                 // stop profiling and write collected data after delay if env value is set.
584                                 char *env = getenv("CLR_MCJ_PROFILE_WRITE_DELAY");
585                                 if (env != nullptr) {
586                                         int delay = std::atoi(env);
587                                         // To avoid undefined behavior by out-of-range input(atoi), set max delay value to 100.
588                                         if (delay > 0) {
589                                                 if (delay > MAX_DELAY_SEC) delay = MAX_DELAY_SEC;
590                                                 stopProfileAfterDelay(delay);
591                                         }
592                                 }
593                         }
594                 }
595                 free(localDataPath);
596         }
597
598         if (exist(__pm->getAppRootPath() + "/bin/" + DISABLE_IPV6_FILE)) {
599                 setSwitch("System.Net.DisableIPv6", true);
600         }
601
602         setSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true);
603
604         vconf_ignore_key_changed(VCONFKEY_LANGSET, langChangedCB);
605
606         pluginBeforeExecute();
607
608         _INFO("execute assembly : %s", path);
609
610         unsigned int ret = 0;
611         int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
612         if (st < 0)
613                 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
614         return ret;
615 }
616
617 }  // namespace dotnetcore
618 }  // namespace runtime
619 }  // namespace tizen