Refactoring dotnet-launcher
[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
20 #include <string>
21 #include <fstream>
22 #include <vector>
23
24 #include <fcntl.h>
25 #include <sys/stat.h>
26 #include <sys/types.h>
27 #include <sys/wait.h>
28 #include <unistd.h>
29
30 #include "utils.h"
31 #include "log.h"
32 #include "launcher.h"
33 #include "dotnet_launcher.h"
34 #include "plugin_manager.h"
35 #include "path_manager.h"
36
37 #define PLUGIN_PATH "/usr/share/dotnet.tizen/lib/libdotnet_plugin.so"
38
39 namespace tizen {
40 namespace runtime {
41 namespace dotnetcore {
42
43 #if defined (__aarch64__)
44 #define ARCHITECTURE_IDENTIFIER "arm64"
45 const static std::vector<std::string> RID_FALLBACK_GRAPH =
46         {"linux-arm64", "linux", "unix-arm64", "unix", "any", "base"};
47
48 #elif defined (__arm__)
49 #define ARCHITECTURE_IDENTIFIER "arm"
50 const static std::vector<std::string> RID_FALLBACK_GRAPH =
51         {"tizen.4.0.0-armel", "tizen.4.0.0", "tizen-armel", "tizen", "linux-armel", "linux", "unix-armel", "unix", "any", "base"};
52
53 #elif defined (__x86_64__)
54 #define ARCHITECTURE_IDENTIFIER "x64"
55 const static std::vector<std::string> RID_FALLBACK_GRAPH =
56         {"linux-x64", "linux", "unix-x64", "unix", "any", "base"};
57
58 #elif defined (__i386__)
59 #define ARCHITECTURE_IDENTIFIER "x86"
60 const static std::vector<std::string> RID_FALLBACK_GRAPH =
61         {"linux-x86", "linux", "unix-x86", "unix", "any", "base"};
62
63 #else
64 #error "Unknown target"
65 #endif
66
67 static std::string getExtraNativeLibDirs(const std::string& appRoot)
68 {
69         std::string candidate;
70         for (unsigned int i = 0; i < RID_FALLBACK_GRAPH.size(); i++) {
71                 if(!candidate.empty()) {
72                         candidate += ":";
73                 }
74                 candidate += concatPath(appRoot, "bin/runtimes/" + RID_FALLBACK_GRAPH[i] + "/native");
75         }
76
77         candidate = candidate + ":" + concatPath(appRoot, "lib/" ARCHITECTURE_IDENTIFIER);
78         if (!strncmp(ARCHITECTURE_IDENTIFIER, "arm64", 5)) {
79                 candidate = candidate + ":" + concatPath(appRoot, "lib/aarch64");
80         }
81
82         return candidate;
83 }
84
85 CoreRuntime::CoreRuntime(const char* mode) :
86         initializeClr(nullptr),
87         executeAssembly(nullptr),
88         shutdown(nullptr),
89         createDelegate(nullptr),
90         __coreclrLib(nullptr),
91         __hostHandle(nullptr),
92         __domainId(-1),
93         fd(0),
94         __mode(mode)
95 {
96         _DBG("Constructor called!!");
97
98         if (runLoggingThread() < 0) {
99                 _ERR("Failed to create logging thread");
100         }
101 }
102
103 CoreRuntime::~CoreRuntime()
104 {
105         dispose();
106 }
107
108 int CoreRuntime::initialize(bool standalone)
109 {
110 #define __XSTR(x) #x
111 #define __STR(x) __XSTR(x)
112
113 #ifdef NATIVE_LIB_DIR
114         __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
115 #endif
116
117 #undef __STR
118 #undef __XSTR
119
120 #ifdef __arm__
121         // libunwind library is used to unwind stack frame, but libunwind for ARM
122         // does not support ARM vfpv3/NEON registers in DWARF format correctly.
123         // Therefore let's disable stack unwinding using DWARF information
124         // See https://github.com/dotnet/coreclr/issues/6698
125         //
126         // libunwind use following methods to unwind stack frame.
127         // UNW_ARM_METHOD_ALL          0xFF
128         // UNW_ARM_METHOD_DWARF        0x01
129         // UNW_ARM_METHOD_FRAME        0x02
130         // UNW_ARM_METHOD_EXIDX        0x04
131         putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
132 #endif // __arm__
133
134         if (initializePluginManager(__mode) < 0) {
135                 _ERR("Failed to initialize PluginManager");
136                 return -1;
137         }
138
139         if (initializePathManager(std::string(), std::string(), std::string()) < 0) {
140                 _ERR("Failed to initialize PathManager");
141                 return -1;
142         }
143
144         std::string libCoreclr(concatPath(getRuntimeDir(), "libcoreclr.so"));
145
146         __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
147         if (__coreclrLib == nullptr) {
148                 char *err = dlerror();
149                 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
150                 return -1;
151         }
152
153 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
154         do { \
155                 variable = (type)dlsym(__coreclrLib, name); \
156                 if (variable == nullptr) { \
157                         _ERR(name " is not found in the libcoreclr.so"); \
158                         return -1; \
159                 } \
160         } while (0)
161
162         CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
163         CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
164         CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
165         CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
166
167 #undef CORELIB_RETURN_IF_NOSYM
168
169         _DBG("libcoreclr dlopen and dlsym success");
170
171         if (!standalone)
172                 pluginPreload();
173
174         fd = open("/proc/self", O_DIRECTORY);
175         std::string appRoot = std::string("/proc/self/fd/") + std::to_string(fd);
176         std::string appBin = concatPath(appRoot, "bin");
177         std::string appLib = concatPath(appRoot, "lib");
178         std::string probePath = appBin + ":" + appLib;
179         std::string tpa = getTPA();
180         std::string nativeLibPath = getExtraNativeLibDirs(appRoot) + ":" + appBin + ":" + appLib + ":" + __nativeLibDirectory;
181         std::string appName = std::string("dotnet-launcher-") + std::to_string(getpid());
182
183         if (!initializeCoreClr(appName.c_str(), probePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
184                 _ERR("Failed to initialize coreclr");
185                 return -1;
186         }
187
188         return 0;
189 }
190
191 bool CoreRuntime::initializeCoreClr(const char* appId,
192                                                                          const char* assemblyProbePaths,
193                                                                          const char* pinvokeProbePaths,
194                                                                          const char* tpaList)
195 {
196         const char *propertyKeys[] = {
197                 "TRUSTED_PLATFORM_ASSEMBLIES",
198                 "APP_PATHS",
199                 "APP_NI_PATHS",
200                 "NATIVE_DLL_SEARCH_DIRECTORIES",
201                 "AppDomainCompatSwitch"
202         };
203
204         const char *propertyValues[] = {
205                 tpaList,
206                 assemblyProbePaths,
207                 assemblyProbePaths,
208                 pinvokeProbePaths,
209                 "UseLatestBehaviorWhenTFMNotSpecified"
210         };
211
212         std::string selfPath = readSelfPath();
213
214         int st = initializeClr(selfPath.c_str(),
215                                                         appId,
216                                                         sizeof(propertyKeys) / sizeof(propertyKeys[0]),
217                                                         propertyKeys,
218                                                         propertyValues,
219                                                         &__hostHandle,
220                                                         &__domainId);
221
222         if (st < 0) {
223                 _ERR("initialize core clr fail! (0x%08x)", st);
224                 return false;
225         }
226
227         pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
228
229         _DBG("Initialize core clr success");
230         return true;
231 }
232
233 void CoreRuntime::dispose()
234 {
235         if (__hostHandle != nullptr) {
236                 int st = shutdown(__hostHandle, __domainId);
237                 if (st < 0)
238                         _ERR("shutdown core clr fail! (0x%08x)", st);
239                 __hostHandle = nullptr;
240         }
241
242         if (__coreclrLib != nullptr) {
243                 if (dlclose(__coreclrLib) != 0) {
244                         _ERR("libcoreclr.so close failed");
245                 }
246
247                 __coreclrLib = nullptr;
248         }
249
250         finalizePluginManager();
251         finalizePathManager();
252
253         _DBG("Dotnet runtime disposed");
254 }
255
256 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
257 {
258         if (path == nullptr) {
259                 _ERR("executable path is null");
260                 return -11;
261         }
262
263         if (!isFileExist(path)) {
264                 _ERR("File not exist : %s", path);
265                 return -1;
266         }
267
268         pluginSetAppInfo(appId, path);
269
270         int fd2 = open(root, O_DIRECTORY);
271         dup3(fd2, fd, O_CLOEXEC);
272         if (fd2 >= 0)
273                 close(fd2);
274
275         pluginBeforeExecute();
276
277         unsigned int ret = 0;
278         int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
279         if (st < 0)
280                 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
281         return ret;
282 }
283
284 }  // namespace dotnetcore
285 }  // namespace runtime
286 }  // namespace tizen