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