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