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