5f1be89cfe28738c050c6cb9a411acfbcf41e283
[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 static void setLang()
193 {
194         char* lang = vconf_get_str(VCONFKEY_LANGSET);
195         if (!lang) {
196                 _ERR("Fail to get language from vconf");
197                 return;
198         }
199
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));
208
209         free(lang);
210 }
211
212 static std::string readSelfPath()
213 {
214         char buff[PATH_MAX];
215         ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
216         if (len != -1) {
217                 buff[len] = '\0';
218                 return std::string(buff);
219         }
220
221         return "";
222 }
223
224 static void removeDebugPipe()
225 {
226         DIR *dir;
227         struct dirent* entry;
228         char debugPipeFiles[PATH_MAX];;
229         sprintf(debugPipeFiles, "/tmp/clr-debug-pipe-%d-", getpid());
230
231         dir = opendir("/tmp");
232         if (dir == nullptr) {
233                 _ERR("Fail to open /tmp directory");
234                 return;
235         }
236
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());
242                         }
243                 }
244         }
245
246         closedir(dir);
247 }
248
249 void preload()
250 {
251         typedef void (*PreloadDelegate)();
252         PreloadDelegate preloadDelegate;
253
254         int ret = createDelegate(__hostHandle,
255                 __domainId,
256                 "Tizen.Runtime",
257                 "Tizen.Runtime.Preloader",
258                 "Preload",
259                 (void**)&preloadDelegate);
260
261         if (ret < 0) {
262                 _ERR("Failed to create delegate for Tizen.Runtime Preload (0x%08x)", ret);
263         } else {
264                 preloadDelegate();
265         }
266
267         pluginPreload();
268 }
269
270 bool initializeCoreClr(PathManager* pm, const std::string& tpa)
271 {
272         bool ncdbStartupHook = isNCDBStartupHookProvided();
273
274         const char *propertyKeys[] = {
275                 "TRUSTED_PLATFORM_ASSEMBLIES",
276                 "APP_PATHS",
277                 "APP_NI_PATHS",
278                 "NATIVE_DLL_SEARCH_DIRECTORIES",
279                 "AppDomainCompatSwitch",
280                 ncdbStartupHook ? "STARTUP_HOOKS" : "" // must be the last one
281         };
282
283         const char *propertyValues[] = {
284                 tpa.c_str(),
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
290         };
291
292         std::string selfPath = readSelfPath();
293
294         int st = initializeClr(selfPath.c_str(),
295                                                         "TizenDotnetApp",
296                                                         sizeof(propertyKeys) / sizeof(propertyKeys[0]) - (ncdbStartupHook ? 0 : 1),
297                                                         propertyKeys,
298                                                         propertyValues,
299                                                         &__hostHandle,
300                                                         &__domainId);
301
302         if (st < 0) {
303                 _ERR("initialize core clr fail! (0x%08x)", st);
304                 return false;
305         }
306
307         pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
308
309         _INFO("Initialize core clr success");
310         return true;
311 }
312
313 int CoreRuntime::initialize(const char* appType, LaunchMode launchMode)
314 {
315         if (__initialized) {
316                 _ERR("CoreRuntime is already initialized");
317                 return -1;
318         }
319
320         // Intiailize ecore first (signal handlers, etc.) before runtime init.
321         ecore_init();
322
323         // set language environment to support ICU
324         setLang();
325
326         char *env = nullptr;
327         env = getenv("CORECLR_ENABLE_PROFILING");
328         if (env != nullptr && !strcmp(env, "1")) {
329                 _INFO("profiling mode on");
330                 __isProfileMode = true;
331         }
332
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");
339                 return -1;
340         }
341
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();
345         if (res != 0) {
346                 _ERR("Failed to initnialize Memory Profiler");
347                 return -1;
348         }
349
350 #ifdef __arm__
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
355         //
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"));
362 #endif // __arm__
363
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"));
367
368         // Write Debug.WriteLine to stderr
369         putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
370
371 #ifdef USE_DEFAULT_BASE_ADDR
372         putenv(const_cast<char *>("COMPlus_UseDefaultBaseAddr=1"));
373 #endif // USE_DEFAULT_BASE_ADDR
374
375         // Disable config cache to set environment after coreclr_initialize()
376         putenv(const_cast<char *>("COMPlus_DisableConfigCache=1"));
377
378         // read string from external file and set them to environment value.
379         setEnvFromFile();
380
381         try {
382                 __pm = new PathManager();
383         } catch (const std::exception& e) {
384                 _ERR("Failed to create PathManager");
385                 return -1;
386         }
387
388         char* pluginDllPaths = pluginGetDllPath();
389         if (pluginDllPaths && pluginDllPaths[0] != '\0') {
390                 __pm->addPlatformAssembliesPaths(pluginDllPaths, true);
391         }
392
393         char* pluginNativePaths = pluginGetNativeDllSearchingPath();
394         if (pluginNativePaths && pluginNativePaths[0] != '\0') {
395                 __pm->addNativeDllSearchingPaths(pluginNativePaths, true);
396         }
397
398         char* pluginExtraDllPaths = pluginGetExtraDllPath();
399         if (pluginExtraDllPaths && pluginExtraDllPaths[0] != '\0') {
400                 __pm->setExtraDllPaths(pluginExtraDllPaths);
401         }
402
403         pluginHasLogControl();
404
405         std::string libCoreclr(concatPath(__pm->getRuntimePath(), "libcoreclr.so"));
406
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);
411                 return -1;
412         }
413
414 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
415         do { \
416                 variable = (type)dlsym(__coreclrLib, name); \
417                 if (variable == nullptr) { \
418                         _ERR(name " is not found in the libcoreclr.so"); \
419                         return -1; \
420                 } \
421         } while (0)
422
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");
427
428 #undef CORELIB_RETURN_IF_NOSYM
429
430         _INFO("libcoreclr dlopen and dlsym success");
431
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();
437
438         std::string tpa;
439         char* pluginTPA = pluginGetTPA();
440         if (pluginTPA && pluginTPA[0] != '\0') {
441                 tpa = std::string(pluginTPA);
442         } else {
443                 addAssembliesFromDirectories(__pm->getPlatformAssembliesPaths(), tpa);
444         }
445
446         if (!initializeCoreClr(__pm, tpa)) {
447                 _ERR("Failed to initialize coreclr");
448                 return -1;
449         }
450
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);
454                 return -1;
455         }
456
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);
460                 return -1;
461         }
462
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);
466                 return -1;
467         }
468
469         if (launchMode == LaunchMode::loader) {
470
471                 // preload libraries and manage dlls for optimizing startup time
472                 preload();
473
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.
479                 removeDebugPipe();
480         }
481
482         __initialized = true;
483
484         _INFO("CoreRuntime initialize success");
485
486         return 0;
487 }
488
489 void CoreRuntime::finalize()
490 {
491         // call plugin finalize function to notify finalize to plugin
492         // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
493         pluginFinalize();
494
495         // ignore the signal generated by an exception that occurred during shutdown
496         checkOnTerminate = true;
497
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.");
503                 _exit(0);
504         }
505
506         if (__hostHandle != nullptr) {
507                 int st = shutdown(__hostHandle, __domainId);
508                 if (st < 0)
509                         _ERR("shutdown core clr fail! (0x%08x)", st);
510                 __hostHandle = nullptr;
511         }
512
513         if (__coreclrLib != nullptr) {
514                 if (dlclose(__coreclrLib) != 0) {
515                         _ERR("libcoreclr.so close failed");
516                 }
517
518                 __coreclrLib = nullptr;
519         }
520
521         finalizePluginManager();
522
523         delete __pm;
524         __pm = NULL;
525
526         __envList.clear();
527
528         _INFO("CoreRuntime finalized");
529 }
530
531 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[], bool profile)
532 {
533         if (!__initialized) {
534                 _ERR("Runtime is not initialized");
535                 return -1;
536         }
537
538         if (path == nullptr) {
539                 _ERR("executable path is null");
540                 return -1;
541         }
542
543         if (!isFile(path)) {
544                 _ERR("File not exist : %s", path);
545                 return -1;
546         }
547
548         // VD has their own signal handler.
549         if (!pluginHasLogControl()) {
550                 registerSigHandler();
551         }
552
553         pluginSetAppInfo(appId, path);
554
555         // temporal root path is overrided to real application root path
556         __pm->setAppRootPath(root);
557
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);
563
564                 // set profile.data path and collect/use it if it non-exists/exists.
565                 if (profile) {
566                         char multiCoreJitProfile[strlen(localDataPath) + strlen(PROFILE_BASENAME) + 1];
567                         memcpy(multiCoreJitProfile, localDataPath, strlen(localDataPath) + 1);
568                         strncat(multiCoreJitProfile, PROFILE_BASENAME, strlen(PROFILE_BASENAME));
569
570                         setEnvironmentVariable("COMPlus_MultiCoreJitProfile", multiCoreJitProfile);
571                         setEnvironmentVariable("COMPlus_MultiCoreJitMinNumCpus", "1");
572
573                         if (exist(multiCoreJitProfile)) {
574                                 setEnvironmentVariable("COMPlus_MultiCoreJitNoProfileGather", "1");
575                                 _INFO("MCJ playing start for %s", appId);
576                         } else {
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.
583                                         if (delay > 0) {
584                                                 if (delay > MAX_DELAY_SEC) delay = MAX_DELAY_SEC;
585                                                 stopProfileAfterDelay(delay);
586                                         }
587                                 }
588                                 _INFO("MCJ recording start for %s", appId);
589                         }
590                 }
591                 free(localDataPath);
592         }
593
594         if (exist(__pm->getAppRootPath() + "/bin/" + DISABLE_IPV6_FILE)) {
595                 setSwitch("System.Net.DisableIPv6", true);
596         }
597
598         setSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true);
599
600         pluginBeforeExecute();
601
602         _INFO("execute assembly : %s", path);
603
604         unsigned int ret = 0;
605         int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
606         if (st < 0)
607                 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
608         return ret;
609 }
610
611 }  // namespace dotnetcore
612 }  // namespace runtime
613 }  // namespace tizen