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