Change the priority of the function to check (#476)
[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                 if (setEnvironmentVariable) {
174                         setEnvironmentVariable(key, const_cast<char *>(path));
175                 } else {
176                         _ERR("coreclr is not initialized!. setEnvironmentVariable() function is not ready!");
177                         _exit(0);
178                 }
179                 free(path);
180         }
181 }
182
183 static void initEnvForSpecialFolder()
184 {
185         if (getenv("XDG_PICTURES_DIR") == NULL) {
186                 setSpecialFolder(STORAGE_DIRECTORY_IMAGES, "XDG_PICTURES_DIR");
187         }
188
189         if (getenv("XDG_MUSIC_DIR") == NULL) {
190                 setSpecialFolder(STORAGE_DIRECTORY_MUSIC, "XDG_MUSIC_DIR");
191         }
192
193         if (getenv("XDG_VIDEOS_DIR") == NULL) {
194                 setSpecialFolder(STORAGE_DIRECTORY_VIDEOS, "XDG_VIDEOS_DIR");
195         }
196 }
197
198 static void setLang()
199 {
200         //To reduce search overhead of libicuuc.so.xx
201         setenv("CLR_ICU_VERSION_OVERRIDE", "build", 1);
202
203         char* lang = vconf_get_str(VCONFKEY_LANGSET);
204         if (!lang) {
205                 _ERR("Fail to get language from vconf");
206                 return;
207         }
208
209         // In order to operate ICU (used for globalization) normally, the following
210         // environment variables must be set before using ICU API.
211         // When running Applicaiton, the following environment variables are set by AppFW.
212         // But when preloading the dll in the candidate process, the following environment variables are not set
213         // As a result, CultureInfo is incorrectly generated and malfunctions.
214         // For example, uloc_getDefault() returns en_US_POSIX, CultureInfo is set to invariant mode.
215         setenv("LANG", const_cast<char *>(lang), 1);
216         setlocale(LC_ALL, const_cast<char *>(lang));
217
218         free(lang);
219 }
220
221 static std::string readSelfPath()
222 {
223         char buff[PATH_MAX];
224         ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1);
225         if (len != -1) {
226                 buff[len] = '\0';
227                 return std::string(buff);
228         }
229
230         return "";
231 }
232
233 static void removeDebugPipe()
234 {
235         DIR *dir;
236         struct dirent* entry;
237         char debugPipeFiles[PATH_MAX];;
238         sprintf(debugPipeFiles, "/tmp/clr-debug-pipe-%d-", getpid());
239
240         dir = opendir("/tmp");
241         if (dir == nullptr) {
242                 _ERR("Fail to open /tmp directory");
243                 return;
244         }
245
246         while ((entry = readdir(dir)) != nullptr) {
247                 std::string path = concatPath("/tmp", entry->d_name);
248                 if (path.find(debugPipeFiles) != std::string::npos) {
249                         if (!removeFile(path)) {
250                                 _ERR("Fail to remove file (%s)", path.c_str());
251                         }
252                 }
253         }
254
255         closedir(dir);
256 }
257
258 void preload()
259 {
260         typedef void (*PreloadDelegate)();
261         PreloadDelegate preloadDelegate;
262
263         int ret = createDelegate(__hostHandle,
264                 __domainId,
265                 "Tizen.Runtime",
266                 "Tizen.Runtime.Preloader",
267                 "Preload",
268                 (void**)&preloadDelegate);
269
270         if (ret < 0) {
271                 _ERR("Failed to create delegate for Tizen.Runtime Preload (0x%08x)", ret);
272         } else {
273                 preloadDelegate();
274         }
275
276         pluginPreload();
277 }
278
279 bool initializeCoreClr(PathManager* pm, const std::string& tpa)
280 {
281         bool ncdbStartupHook = isNCDBStartupHookProvided();
282
283         const char *propertyKeys[] = {
284                 "TRUSTED_PLATFORM_ASSEMBLIES",
285                 "APP_PATHS",
286                 "APP_NI_PATHS",
287                 "NATIVE_DLL_SEARCH_DIRECTORIES",
288                 "AppDomainCompatSwitch",
289                 ncdbStartupHook ? "STARTUP_HOOKS" : "" // must be the last one
290         };
291
292         const char *propertyValues[] = {
293                 tpa.c_str(),
294                 pm->getAppPaths().c_str(),
295                 pm->getAppNIPaths().c_str(),
296                 pm->getNativeDllSearchingPaths().c_str(),
297                 "UseLatestBehaviorWhenTFMNotSpecified",
298                 ncdbStartupHook ? getNCDBStartupHook() : "" // must be the last one
299         };
300
301         std::string selfPath = readSelfPath();
302
303         int st = initializeClr(selfPath.c_str(),
304                                                         "TizenDotnetApp",
305                                                         sizeof(propertyKeys) / sizeof(propertyKeys[0]) - (ncdbStartupHook ? 0 : 1),
306                                                         propertyKeys,
307                                                         propertyValues,
308                                                         &__hostHandle,
309                                                         &__domainId);
310
311         if (st < 0) {
312                 _ERR("initialize core clr fail! (0x%08x)", st);
313                 return false;
314         }
315
316         pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
317
318         _INFO("Initialize core clr success");
319         return true;
320 }
321
322 int CoreRuntime::initialize(const char* appType, LaunchMode launchMode)
323 {
324         if (__initialized) {
325                 _ERR("CoreRuntime is already initialized");
326                 return -1;
327         }
328
329         // set language environment to support ICU
330         setLang();
331
332         char *env = nullptr;
333         env = getenv("CORECLR_ENABLE_PROFILING");
334         if (env != nullptr && !strcmp(env, "1")) {
335                 _INFO("profiling mode on");
336                 __isProfileMode = true;
337         }
338
339         // plugin initialize should be called before creating threads.
340         // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
341         // When attaching to a secure zone, if there is a created thread, it will failed.
342         // So, plugin initialize should be called before creating threads.
343         if (initializePluginManager(appType) < 0) {
344                 _ERR("Failed to initialize PluginManager");
345                 return -1;
346         }
347
348         // checkInjection checks dotnet-launcher run mode
349         // At the moment, this mechanism is used only when the Memory Profiler is started.
350         int res = checkInjection();
351         if (res != 0) {
352                 _ERR("Failed to initnialize Memory Profiler");
353                 return -1;
354         }
355
356 #ifdef __arm__
357         // libunwind library is used to unwind stack frame, but libunwind for ARM
358         // does not support ARM vfpv3/NEON registers in DWARF format correctly.
359         // Therefore let's disable stack unwinding using DWARF information
360         // See https://github.com/dotnet/coreclr/issues/6698
361         //
362         // libunwind use following methods to unwind stack frame.
363         // UNW_ARM_METHOD_ALL           0xFF
364         // UNW_ARM_METHOD_DWARF         0x01
365         // UNW_ARM_METHOD_FRAME         0x02
366         // UNW_ARM_METHOD_EXIDX         0x04
367         putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
368 #endif // __arm__
369
370         // Enable diagnostics.
371         // clr create clr-debug-pipe-xxx and dotnet-diagnostics-xxx file under /tmp dir.
372         putenv(const_cast<char *>("COMPlus_EnableDiagnostics=1"));
373
374         // Write Debug.WriteLine to stderr
375         putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
376
377 #ifdef USE_DEFAULT_BASE_ADDR
378         putenv(const_cast<char *>("COMPlus_UseDefaultBaseAddr=1"));
379 #endif // USE_DEFAULT_BASE_ADDR
380
381         // Disable config cache to set environment after coreclr_initialize()
382         putenv(const_cast<char *>("COMPlus_DisableConfigCache=1"));
383
384         // read string from external file and set them to environment value.
385         setEnvFromFile();
386
387         try {
388                 __pm = new PathManager();
389         } catch (const std::exception& e) {
390                 _ERR("Failed to create PathManager");
391                 return -1;
392         }
393
394         char* pluginDllPaths = pluginGetDllPath();
395         if (pluginDllPaths && pluginDllPaths[0] != '\0') {
396                 __pm->addPlatformAssembliesPaths(pluginDllPaths, true);
397         }
398
399         char* pluginNativePaths = pluginGetNativeDllSearchingPath();
400         if (pluginNativePaths && pluginNativePaths[0] != '\0') {
401                 __pm->addNativeDllSearchingPaths(pluginNativePaths, true);
402         }
403
404         char* pluginExtraDllPaths = pluginGetExtraDllPath();
405         if (pluginExtraDllPaths && pluginExtraDllPaths[0] != '\0') {
406                 __pm->setExtraDllPaths(pluginExtraDllPaths);
407         }
408
409         std::string libCoreclr(concatPath(__pm->getRuntimePath(), "libcoreclr.so"));
410
411         __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
412         if (__coreclrLib == nullptr) {
413                 char *err = dlerror();
414                 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
415                 return -1;
416         }
417
418 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
419         do { \
420                 variable = (type)dlsym(__coreclrLib, name); \
421                 if (variable == nullptr) { \
422                         _ERR(name " is not found in the libcoreclr.so"); \
423                         return -1; \
424                 } \
425         } while (0)
426
427         CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
428         CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
429         CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
430         CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
431
432 #undef CORELIB_RETURN_IF_NOSYM
433
434         _INFO("libcoreclr dlopen and dlsym success");
435
436         std::string tpa;
437         char* pluginTPA = pluginGetTPA();
438         if (pluginTPA && pluginTPA[0] != '\0') {
439                 tpa = std::string(pluginTPA);
440         } else {
441                 addAssembliesFromDirectories(__pm->getPlatformAssembliesPaths(), tpa);
442         }
443
444         if (!initializeCoreClr(__pm, tpa)) {
445                 _ERR("Failed to initialize coreclr");
446                 return -1;
447         }
448
449         int st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Environment", "SetEnvironmentVariable", (void**)&setEnvironmentVariable);
450         if (st < 0 || setEnvironmentVariable == nullptr) {
451                 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Environment -> SetEnvironmentVariable failed (0x%08x)", st);
452                 return -1;
453         }
454
455         st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.Profiler", "StopProfileAfterDelay", (void**)&stopProfileAfterDelay);
456         if (st < 0 || stopProfileAfterDelay == nullptr) {
457                 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.Profiler -> StopProfileAfterDelay failed (0x%08x)", st);
458                 return -1;
459         }
460
461         st = createDelegate(__hostHandle, __domainId, "Tizen.Runtime", "Tizen.Runtime.AppSetting", "SetSwitch", (void**)&setSwitch);
462         if (st < 0 || setSwitch == nullptr) {
463                 _ERR("Create delegate for Tizen.Runtime.dll -> Tizen.Runtime.AppSetting -> SetSwitch failed (0x%08x)", st);
464                 return -1;
465         }
466
467         if (launchMode == LaunchMode::loader) {
468                 // preload libraries and manage dlls for optimizing startup time
469                 preload();
470
471                 // The debug pipe created in the candidate process has a "User" label.
472                 // As a result, smack deny occurs when app process try to access the debug pipe.
473                 // Also, since debugging is performed only in standalone mode,
474                 // the debug pipe doesnot be used in the candidate process.
475                 // So, to avoid smack deny error, delete unused debug pipe files.
476                 removeDebugPipe();
477         }
478
479
480         // Set environment for System.Environment.SpecialFolder
481         // Below function creates dbus connection by callging storage API.
482         // If dbus connection is created bofere fork(), forked process cannot use dbus.
483         // To avoid gdbus blocking issue, below function should be called after fork()
484         // Addtionally, setenv() is not thread-safe function. storage API makes thread internally
485         // and it makes crash while calling setenv(). So, use setEnvrionmentVariable() instead of setenv()
486         initEnvForSpecialFolder();
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                                 _INFO("MCJ playing start for %s", appId);
582                         } else {
583                                 setEnvironmentVariable("COMPlus_MultiCoreJitNoProfileGather", "0");
584                                 // stop profiling and write collected data after delay if env value is set.
585                                 char *env = getenv("CLR_MCJ_PROFILE_WRITE_DELAY");
586                                 if (env != nullptr) {
587                                         int delay = std::atoi(env);
588                                         // To avoid undefined behavior by out-of-range input(atoi), set max delay value to 100.
589                                         if (delay > 0) {
590                                                 if (delay > MAX_DELAY_SEC) delay = MAX_DELAY_SEC;
591                                                 stopProfileAfterDelay(delay);
592                                         }
593                                 }
594                                 _INFO("MCJ recording start for %s", appId);
595                         }
596                 }
597                 free(localDataPath);
598         }
599
600         if (exist(__pm->getAppRootPath() + "/bin/" + DISABLE_IPV6_FILE)) {
601                 setSwitch("System.Net.DisableIPv6", true);
602         }
603
604         setSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true);
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