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