Call injectLibrary() after plugin initialization
[platform/core/dotnet/launcher.git] / NativeLauncher / launcher / dotnet / dotnet_launcher.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 <fcntl.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <sys/wait.h>
30 #include <unistd.h>
31 #include <linux/limits.h>
32
33 #include <storage.h>
34 #include <app_common.h>
35
36 #include "injection.h"
37 #include "utils.h"
38 #include "log.h"
39 #include "launcher.h"
40 #include "dotnet_launcher.h"
41 #include "plugin_manager.h"
42 #include "path_manager.h"
43 #include "log_manager.h"
44
45 #define PLUGIN_PATH "/usr/share/dotnet.tizen/lib/libdotnet_plugin.so"
46 #define ENV_FILE_PATH "/usr/share/dotnet.tizen/lib/coreclr_env.list"
47
48 namespace tizen {
49 namespace runtime {
50 namespace dotnetcore {
51
52 #if defined (__aarch64__)
53 #define ARCHITECTURE_IDENTIFIER "arm64"
54 const static std::vector<std::string> RID_FALLBACK_GRAPH =
55         {"linux-arm64", "linux", "unix-arm64", "unix", "any", "base"};
56
57 #elif defined (__arm__)
58 #define ARCHITECTURE_IDENTIFIER "arm"
59 const static std::vector<std::string> RID_FALLBACK_GRAPH =
60         {"tizen.5.0.0-armel", "tizen.5.0.0", "tizen.4.0.0-armel", "tizen.4.0.0", "tizen-armel", "tizen", "linux-armel", "linux", "unix-armel", "unix", "any", "base"};
61
62 #elif defined (__x86_64__)
63 #define ARCHITECTURE_IDENTIFIER "x64"
64 const static std::vector<std::string> RID_FALLBACK_GRAPH =
65         {"linux-x64", "linux", "unix-x64", "unix", "any", "base"};
66
67 #elif defined (__i386__)
68 #define ARCHITECTURE_IDENTIFIER "x86"
69 const static std::vector<std::string> RID_FALLBACK_GRAPH =
70         {"tizen.5.0.0-x86", "tizen.5.0.0", "tizen.4.0.0-x86", "tizen.4.0.0", "tizen-x86", "tizen", "linux-x86", "linux", "unix-x86", "unix", "any", "base"};
71
72 #else
73 #error "Unknown target"
74 #endif
75
76 static std::string getExtraNativeLibDirs(const std::string& appRoot)
77 {
78         std::string candidate;
79         for (unsigned int i = 0; i < RID_FALLBACK_GRAPH.size(); i++) {
80                 if(!candidate.empty()) {
81                         candidate += ":";
82                 }
83                 candidate += concatPath(appRoot, "bin/runtimes/" + RID_FALLBACK_GRAPH[i] + "/native");
84         }
85
86         candidate = candidate + ":" + concatPath(appRoot, "lib/" ARCHITECTURE_IDENTIFIER);
87         if (!strncmp(ARCHITECTURE_IDENTIFIER, "arm64", 5)) {
88                 candidate = candidate + ":" + concatPath(appRoot, "lib/aarch64");
89         }
90
91         return candidate;
92 }
93
94
95 static std::vector<std::string> __envList;
96
97 static void setEnvFromFile()
98 {
99         std::string envList;
100         std::ifstream inFile(ENV_FILE_PATH);
101
102         __envList.clear();
103
104         if (inFile) {
105                 _INFO("coreclr_env.list is found");
106                 inFile >> envList;
107
108                 std::istringstream ss(envList);
109                 std::string token;
110
111                 while (std::getline(ss, token, ':')) {
112                         if (!token.empty()) {
113                                 __envList.push_back(token);
114                         }
115                 }
116
117                 for (unsigned int i = 0; i < __envList.size(); i++) {
118                         putenv(const_cast<char *>(__envList[i].c_str()));
119                 }
120         } else {
121                 _INFO("coreclr_env.list file is not found. skip");
122         }
123 }
124
125 #define _unused(x) ((void)(x))
126
127 struct sigaction sig_abrt_new;
128 struct sigaction sig_abrt_old;
129
130 static bool checkOnSigabrt = false;
131 static bool checkOnTerminate = false;
132
133 static void onSigabrt(int signum)
134 {
135         // use unused variable to avoid build warning
136         ssize_t ret = write(STDERR_FILENO, "onSigabrt called\n", 17);
137
138         if (checkOnTerminate) {
139                 ret = write(STDERR_FILENO, "onSigabrt called while terminate. go to exit\n", 45);
140                 _unused(ret);
141                 exit(0);
142         }
143
144         if (checkOnSigabrt) {
145                 ret = write(STDERR_FILENO, "onSigabrt called again. go to exit\n", 35);
146                 _unused(ret);
147                 exit(0);
148         }
149
150         if (hasException()) {
151                 ret = write(STDERR_FILENO, "******************************************************\n", 55);
152                 ret = write(STDERR_FILENO, "Unhandled exception is occured. check application code\n", 55);
153                 ret = write(STDERR_FILENO, "******************************************************\n", 55);
154         }
155
156         checkOnSigabrt = true;
157         if (sigaction(SIGABRT, &sig_abrt_old, NULL) == 0) {
158                 if (raise(signum) < 0) {
159                         ret = write(STDERR_FILENO, "Fail to raise SIGABRT\n", 22);
160                 }
161         } else {
162                 ret = write(STDERR_FILENO, "Fail to set original SIGABRT handler\n", 37);
163         }
164         _unused(ret);
165 }
166
167 static void registerSigHandler()
168 {
169         sig_abrt_new.sa_handler = onSigabrt;
170         if (sigemptyset(&sig_abrt_new.sa_mask) != 0) {
171                 _ERR("Fail to sigemptyset");
172         }
173
174         if (sigaction(SIGABRT, &sig_abrt_new, &sig_abrt_old) < 0) {
175                 _ERR("Fail to add sig handler");
176         }
177 }
178
179 static bool storage_cb(int id, storage_type_e type, storage_state_e state, const char *path, void *user_data)
180 {
181         int* tmp = (int*)user_data;
182         if (type == STORAGE_TYPE_INTERNAL)
183         {
184                 *tmp = id;
185                 return false;
186         }
187
188         return true;
189 }
190
191 static void initEnvForSpecialFolder()
192 {
193         int storageId;
194         int error;
195         char *path = NULL;
196
197         error = storage_foreach_device_supported(storage_cb, &storageId);
198         if (error != STORAGE_ERROR_NONE) {
199                 return;
200         }
201
202         error = storage_get_directory(storageId, STORAGE_DIRECTORY_IMAGES, &path);
203         if (error == STORAGE_ERROR_NONE && path != NULL) {
204                 setenv("XDG_PICTURES_DIR", const_cast<char *>(path), 1);
205                 free(path);
206                 path = NULL;
207         }
208
209         error = storage_get_directory(storageId, STORAGE_DIRECTORY_MUSIC, &path);
210         if (error == STORAGE_ERROR_NONE && path != NULL) {
211                 setenv("XDG_MUSIC_DIR", const_cast<char *>(path), 1);
212                 free(path);
213                 path = NULL;
214         }
215
216         error = storage_get_directory(storageId, STORAGE_DIRECTORY_VIDEOS, &path);
217         if (error == STORAGE_ERROR_NONE && path != NULL) {
218                 setenv("XDG_VIDEOS_DIR", const_cast<char *>(path), 1);
219                 free(path);
220                 path = NULL;
221         }
222 }
223
224 CoreRuntime::CoreRuntime(const char* mode) :
225         initializeClr(nullptr),
226         executeAssembly(nullptr),
227         shutdown(nullptr),
228         createDelegate(nullptr),
229         setEnvironmentVariable(nullptr),
230         multiByteToWideChar(nullptr),
231         __coreclrLib(nullptr),
232         __hostHandle(nullptr),
233         __domainId(-1),
234         fd(0),
235         __initialized(false)
236 {
237         _INFO("Constructor called!!");
238
239         // plugin initialize should be called before start loader mainloop.
240         // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
241         // When attaching to a secure zone, if there is a created thread, it will failed.
242         // So, plugin initialize should be called before mainloop start.
243         if (initializePluginManager(mode) < 0) {
244                 _ERR("Failed to initialize PluginManager");
245         }
246
247         if (pluginHasLogControl()) {
248                 __enableLogManager = false;
249         } else {
250                 __enableLogManager = true;
251         }
252 }
253
254 CoreRuntime::~CoreRuntime()
255 {
256         dispose();
257 }
258
259 int CoreRuntime::initialize(bool standalone)
260 {
261         // checkInjection checks dotnet-launcher run mode,
262         // if it contains DOTNET_LAUNCHER_INJECT variable, it injects library.
263         // At the moment, this mechanism is used only when the Memory Profiler is started.
264         int res = checkInjection();
265         if (res != 0) {
266                 _ERR("Failed to initnialize Memory Profiler");
267                 return -1;
268         }
269 #define __XSTR(x) #x
270 #define __STR(x) __XSTR(x)
271
272 #ifdef NATIVE_LIB_DIR
273         __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
274 #endif
275
276 #undef __STR
277 #undef __XSTR
278
279 #ifdef __arm__
280         // libunwind library is used to unwind stack frame, but libunwind for ARM
281         // does not support ARM vfpv3/NEON registers in DWARF format correctly.
282         // Therefore let's disable stack unwinding using DWARF information
283         // See https://github.com/dotnet/coreclr/issues/6698
284         //
285         // libunwind use following methods to unwind stack frame.
286         // UNW_ARM_METHOD_ALL          0xFF
287         // UNW_ARM_METHOD_DWARF        0x01
288         // UNW_ARM_METHOD_FRAME        0x02
289         // UNW_ARM_METHOD_EXIDX        0x04
290         putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
291 #endif // __arm__
292
293         // Disable debug pipes and semaphores creation in case of non-standlone mode
294         if (!standalone)
295                 putenv(const_cast<char *>("COMPlus_EnableDiagnostics=0"));
296
297         // read string from external file and set them to environment value.
298         setEnvFromFile();
299
300         // Set environment for System.Environment.SpecialFolder
301         initEnvForSpecialFolder();
302
303         if (initializePathManager(std::string(), std::string(), std::string()) < 0) {
304                 _ERR("Failed to initialize PathManager");
305                 return -1;
306         }
307
308         if (__enableLogManager) {
309                 if (initializeLogManager() < 0) {
310                         _ERR("Failed to initnialize LogManager");
311                         return -1;
312                 }
313
314                 if (redirectFD() < 0) {
315                         _ERR("Failed to redirect FD");
316                         return -1;
317                 }
318
319                 if (runLoggingThread() < 0) {
320                         _ERR("Failed to create and run logging thread to redicrect log");
321                         return -1;
322                 }
323         }
324
325         std::string libCoreclr(concatPath(getRuntimeDir(), "libcoreclr.so"));
326
327         __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
328         if (__coreclrLib == nullptr) {
329                 char *err = dlerror();
330                 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
331                 return -1;
332         }
333
334 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
335         do { \
336                 variable = (type)dlsym(__coreclrLib, name); \
337                 if (variable == nullptr) { \
338                         _ERR(name " is not found in the libcoreclr.so"); \
339                         return -1; \
340                 } \
341         } while (0)
342
343         CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
344         CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
345         CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
346         CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
347         CORELIB_RETURN_IF_NOSYM(set_environment_variable_ptr, setEnvironmentVariable, "SetEnvironmentVariableW");
348         CORELIB_RETURN_IF_NOSYM(multi_byte_to_wide_char_ptr, multiByteToWideChar, "MultiByteToWideChar");
349
350 #undef CORELIB_RETURN_IF_NOSYM
351
352         _INFO("libcoreclr dlopen and dlsym success");
353
354         if (!standalone)
355                 pluginPreload();
356
357         fd = open("/proc/self", O_DIRECTORY);
358         std::string appRoot = std::string("/proc/self/fd/") + std::to_string(fd);
359         std::string appBin = concatPath(appRoot, "bin");
360         std::string appLib = concatPath(appRoot, "lib");
361         std::string probePath = appBin + ":" + appLib;
362         std::string tpa = getTPA();
363         std::string nativeLibPath = getExtraNativeLibDirs(appRoot) + ":" + appBin + ":" + appLib + ":" + __nativeLibDirectory;
364         std::string appName = std::string("dotnet-launcher-") + std::to_string(getpid());
365
366         if (!initializeCoreClr(appName.c_str(), probePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
367                 _ERR("Failed to initialize coreclr");
368                 return -1;
369         }
370
371         __initialized = true;
372
373         _INFO("CoreRuntime initialize success");
374
375         return 0;
376 }
377
378 bool CoreRuntime::initializeCoreClr(const char* appId,
379                                                                          const char* assemblyProbePaths,
380                                                                          const char* pinvokeProbePaths,
381                                                                          const char* tpaList)
382 {
383         const char *propertyKeys[] = {
384                 "TRUSTED_PLATFORM_ASSEMBLIES",
385                 "APP_PATHS",
386                 "APP_NI_PATHS",
387                 "NATIVE_DLL_SEARCH_DIRECTORIES",
388                 "AppDomainCompatSwitch"
389         };
390
391         const char *propertyValues[] = {
392                 tpaList,
393                 assemblyProbePaths,
394                 assemblyProbePaths,
395                 pinvokeProbePaths,
396                 "UseLatestBehaviorWhenTFMNotSpecified"
397         };
398
399         std::string selfPath = readSelfPath();
400
401         int st = initializeClr(selfPath.c_str(),
402                                                         appId,
403                                                         sizeof(propertyKeys) / sizeof(propertyKeys[0]),
404                                                         propertyKeys,
405                                                         propertyValues,
406                                                         &__hostHandle,
407                                                         &__domainId);
408
409         if (st < 0) {
410                 _ERR("initialize core clr fail! (0x%08x)", st);
411                 return false;
412         }
413
414         pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
415
416         _INFO("Initialize core clr success");
417         return true;
418 }
419
420 void CoreRuntime::dispose()
421 {
422         // call plugin finalize function to notify finalize to plugin
423         // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
424         pluginFinalize();
425
426         // ignore the signal generated by an exception that occurred during shutdown
427         checkOnTerminate = true;
428
429         if (__hostHandle != nullptr) {
430                 int st = shutdown(__hostHandle, __domainId);
431                 if (st < 0)
432                         _ERR("shutdown core clr fail! (0x%08x)", st);
433                 __hostHandle = nullptr;
434         }
435
436         if (__coreclrLib != nullptr) {
437                 if (dlclose(__coreclrLib) != 0) {
438                         _ERR("libcoreclr.so close failed");
439                 }
440
441                 __coreclrLib = nullptr;
442         }
443
444         finalizePluginManager();
445         finalizePathManager();
446
447         __envList.clear();
448
449         _INFO("Dotnet runtime disposed");
450 }
451
452 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
453 {
454         if (!__initialized) {
455                 _ERR("Runtime is not initialized");
456                 return -1;
457         }
458
459         if (path == nullptr) {
460                 _ERR("executable path is null");
461                 return -1;
462         }
463
464         if (!isFileExist(path)) {
465                 _ERR("File not exist : %s", path);
466                 return -1;
467         }
468
469         if (__enableLogManager) {
470                 // launchpad override stdout and stderr to journalctl before launch application.
471                 // we have to re-override that to input pipe for logging thread.
472                 if (redirectFD() < 0) {
473                         _ERR("Failed to redirect FD");
474                         return -1;
475                 }
476
477                 registerSigHandler();
478         }
479
480         pluginSetAppInfo(appId, path);
481
482         int fd2 = open(root, O_DIRECTORY);
483         dup3(fd2, fd, O_CLOEXEC);
484         if (fd2 >= 0)
485                 close(fd2);
486
487         // set application data path to coreclr environment.
488         // application data path can be changed by owner. So, we have to set data path just before launching.
489         char* localDataPath = app_get_data_path();
490         if (localDataPath != nullptr) {
491                 char16_t envval[PATH_MAX] = {0};
492                 int copied = multiByteToWideChar(0 /* CP_ACP */, 0, localDataPath, -1, envval, PATH_MAX);
493                 if (copied >= PATH_MAX) {
494                         _ERR("Data Path is bigger than PATH_MAX");
495                 }
496
497                 if (!setEnvironmentVariable(u"XDG_DATA_HOME", envval)) {
498                         _ERR("Failed to set XDG_DATA_HOME");
499
500                 }
501
502                 free(localDataPath);
503         }
504
505         pluginBeforeExecute();
506
507         _INFO("execute assembly : %s", path);
508
509         unsigned int ret = 0;
510         int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
511         if (st < 0)
512                 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
513         return ret;
514 }
515
516 }  // namespace dotnetcore
517 }  // namespace runtime
518 }  // namespace tizen