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