C# .dll with code for type preloading (#57)
[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 void CoreRuntime::preloadTypes()
234 {
235         const static std::string initDllPath = "/usr/share/dotnet.tizen/framework/Tizen.Init.dll";
236         if (!isFileExist(initDllPath)) {
237                 _ERR("Failed to locate Tizen.Init.dll");
238                 return;
239         }
240
241         typedef void (*InitDelegate)();
242         InitDelegate initDelegate;
243
244         int ret = createDelegate(__hostHandle,
245                 __domainId,
246                 "Tizen.Init",
247                 "Tizen.Init.TypeLoader",
248                 "PreloadTypes",
249                 (void**)&initDelegate);
250
251         if (ret < 0) {
252                 _ERR("Failed to create delegate for PreloadTypes (0x%08x)", ret);
253         } else {
254                 initDelegate();
255         }
256 }
257
258 CoreRuntime::CoreRuntime(const char* mode) :
259         initializeClr(nullptr),
260         executeAssembly(nullptr),
261         shutdown(nullptr),
262         createDelegate(nullptr),
263         setEnvironmentVariable(nullptr),
264         __coreclrLib(nullptr),
265         __hostHandle(nullptr),
266         __domainId(-1),
267         fd(0),
268         __initialized(false)
269 {
270         _INFO("Constructor called!!");
271
272         // plugin initialize should be called before start loader mainloop.
273         // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
274         // When attaching to a secure zone, if there is a created thread, it will failed.
275         // So, plugin initialize should be called before mainloop start.
276         if (initializePluginManager(mode) < 0) {
277                 _ERR("Failed to initialize PluginManager");
278         }
279
280         if (pluginHasLogControl()) {
281                 __enableLogManager = false;
282         } else {
283                 __enableLogManager = true;
284         }
285 }
286
287 CoreRuntime::~CoreRuntime()
288 {
289         dispose();
290 }
291
292 int CoreRuntime::initialize(bool standalone)
293 {
294         // checkInjection checks dotnet-launcher run mode,
295         // if it contains DOTNET_LAUNCHER_INJECT variable, it injects library.
296         // At the moment, this mechanism is used only when the Memory Profiler is started.
297         int res = checkInjection();
298         if (res != 0) {
299                 _ERR("Failed to initnialize Memory Profiler");
300                 return -1;
301         }
302 #define __XSTR(x) #x
303 #define __STR(x) __XSTR(x)
304
305 #ifdef NATIVE_LIB_DIR
306         __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
307 #endif
308
309 #undef __STR
310 #undef __XSTR
311
312 #ifdef __arm__
313         // libunwind library is used to unwind stack frame, but libunwind for ARM
314         // does not support ARM vfpv3/NEON registers in DWARF format correctly.
315         // Therefore let's disable stack unwinding using DWARF information
316         // See https://github.com/dotnet/coreclr/issues/6698
317         //
318         // libunwind use following methods to unwind stack frame.
319         // UNW_ARM_METHOD_ALL          0xFF
320         // UNW_ARM_METHOD_DWARF        0x01
321         // UNW_ARM_METHOD_FRAME        0x02
322         // UNW_ARM_METHOD_EXIDX        0x04
323         putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
324 #endif // __arm__
325
326         // Disable debug pipes and semaphores creation in case of non-standlone mode
327         if (!standalone)
328                 putenv(const_cast<char *>("COMPlus_EnableDiagnostics=0"));
329
330         // Write Debug.WriteLine to stderr
331         putenv(const_cast<char *>("COMPlus_DebugWriteToStdErr=1"));
332
333         // read string from external file and set them to environment value.
334         setEnvFromFile();
335
336         // Set environment for System.Environment.SpecialFolder
337         initEnvForSpecialFolder();
338
339         if (initializePathManager(std::string(), std::string(), std::string()) < 0) {
340                 _ERR("Failed to initialize PathManager");
341                 return -1;
342         }
343
344         if (__enableLogManager) {
345                 if (initializeLogManager() < 0) {
346                         _ERR("Failed to initnialize LogManager");
347                         return -1;
348                 }
349
350                 if (redirectFD() < 0) {
351                         _ERR("Failed to redirect FD");
352                         return -1;
353                 }
354
355                 if (runLoggingThread() < 0) {
356                         _ERR("Failed to create and run logging thread to redicrect log");
357                         return -1;
358                 }
359         }
360
361         std::string libCoreclr(concatPath(getRuntimeDir(), "libcoreclr.so"));
362
363         __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
364         if (__coreclrLib == nullptr) {
365                 char *err = dlerror();
366                 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
367                 return -1;
368         }
369
370 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
371         do { \
372                 variable = (type)dlsym(__coreclrLib, name); \
373                 if (variable == nullptr) { \
374                         _ERR(name " is not found in the libcoreclr.so"); \
375                         return -1; \
376                 } \
377         } while (0)
378
379         CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
380         CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
381         CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
382         CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
383         CORELIB_RETURN_IF_NOSYM(set_environment_variable_ptr, setEnvironmentVariable, "SetEnvironmentVariableW");
384
385 #undef CORELIB_RETURN_IF_NOSYM
386
387         _INFO("libcoreclr dlopen and dlsym success");
388
389         if (!standalone)
390                 pluginPreload();
391
392         fd = open("/proc/self", O_DIRECTORY);
393         std::string appRoot = std::string("/proc/self/fd/") + std::to_string(fd);
394         std::string appBin = concatPath(appRoot, "bin");
395         std::string appLib = concatPath(appRoot, "lib");
396         std::string probePath = appBin + ":" + appLib;
397         std::string tpa = getTPA();
398         std::string nativeLibPath = getExtraNativeLibDirs(appRoot) + ":" + appBin + ":" + appLib + ":" + __nativeLibDirectory;
399         std::string appName = std::string("dotnet-launcher-") + std::to_string(getpid());
400
401         if (!initializeCoreClr(appName.c_str(), probePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
402                 _ERR("Failed to initialize coreclr");
403                 return -1;
404         }
405
406         __initialized = true;
407
408         if (!standalone)
409         {
410                 preloadTypes();         // Preload common managed code
411         }
412
413         _INFO("CoreRuntime initialize success");
414
415         return 0;
416 }
417
418 bool CoreRuntime::initializeCoreClr(const char* appId,
419                                                                          const char* assemblyProbePaths,
420                                                                          const char* pinvokeProbePaths,
421                                                                          const char* tpaList)
422 {
423         const char *propertyKeys[] = {
424                 "TRUSTED_PLATFORM_ASSEMBLIES",
425                 "APP_PATHS",
426                 "APP_NI_PATHS",
427                 "NATIVE_DLL_SEARCH_DIRECTORIES",
428                 "AppDomainCompatSwitch"
429         };
430
431         const char *propertyValues[] = {
432                 tpaList,
433                 assemblyProbePaths,
434                 assemblyProbePaths,
435                 pinvokeProbePaths,
436                 "UseLatestBehaviorWhenTFMNotSpecified"
437         };
438
439         std::string selfPath = readSelfPath();
440
441         int st = initializeClr(selfPath.c_str(),
442                                                         appId,
443                                                         sizeof(propertyKeys) / sizeof(propertyKeys[0]),
444                                                         propertyKeys,
445                                                         propertyValues,
446                                                         &__hostHandle,
447                                                         &__domainId);
448
449         if (st < 0) {
450                 _ERR("initialize core clr fail! (0x%08x)", st);
451                 return false;
452         }
453
454         pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
455
456         _INFO("Initialize core clr success");
457         return true;
458 }
459
460 void CoreRuntime::dispose()
461 {
462         // call plugin finalize function to notify finalize to plugin
463         // dlclose shoud be done after coreclr shutdown to avoid breaking signal chain
464         pluginFinalize();
465
466         // ignore the signal generated by an exception that occurred during shutdown
467         checkOnTerminate = true;
468
469         if (__hostHandle != nullptr) {
470                 int st = shutdown(__hostHandle, __domainId);
471                 if (st < 0)
472                         _ERR("shutdown core clr fail! (0x%08x)", st);
473                 __hostHandle = nullptr;
474         }
475
476         if (__coreclrLib != nullptr) {
477                 if (dlclose(__coreclrLib) != 0) {
478                         _ERR("libcoreclr.so close failed");
479                 }
480
481                 __coreclrLib = nullptr;
482         }
483
484         finalizePluginManager();
485         finalizePathManager();
486
487         __envList.clear();
488
489         _INFO("Dotnet runtime disposed");
490 }
491
492 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
493 {
494         if (!__initialized) {
495                 _ERR("Runtime is not initialized");
496                 return -1;
497         }
498
499         if (path == nullptr) {
500                 _ERR("executable path is null");
501                 return -1;
502         }
503
504         if (!isFileExist(path)) {
505                 _ERR("File not exist : %s", path);
506                 return -1;
507         }
508
509         if (__enableLogManager) {
510                 // launchpad override stdout and stderr to journalctl before launch application.
511                 // we have to re-override that to input pipe for logging thread.
512                 if (redirectFD() < 0) {
513                         _ERR("Failed to redirect FD");
514                         return -1;
515                 }
516
517                 registerSigHandler();
518         }
519
520         pluginSetAppInfo(appId, path);
521
522         int fd2 = open(root, O_DIRECTORY);
523         dup3(fd2, fd, O_CLOEXEC);
524         if (fd2 >= 0)
525                 close(fd2);
526
527         // set application data path to coreclr environment.
528         // application data path can be changed by owner. So, we have to set data path just before launching.
529         char* localDataPath = app_get_data_path();
530         if (localDataPath != nullptr) {
531                 std::u16string envval = utf8ToUtf16(localDataPath);
532
533                 if (!setEnvironmentVariable(u"XDG_DATA_HOME", envval.c_str())) {
534                         _ERR("Failed to set XDG_DATA_HOME");
535                 }
536
537                 free(localDataPath);
538         }
539
540         pluginBeforeExecute();
541
542         _INFO("execute assembly : %s", path);
543
544         unsigned int ret = 0;
545         int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
546         if (st < 0)
547                 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
548         return ret;
549 }
550
551 }  // namespace dotnetcore
552 }  // namespace runtime
553 }  // namespace tizen