call plugin_initialize before mainloop start
[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         __initialized(false)
96 {
97         _DBG("Constructor called!!");
98
99         // plugin initialize should be called before start loader mainloop.
100         // In case of VD plugins, attaching secure zone is done in the plugin_initialize().
101         // When attaching to a secure zone, if there is a created thread, it will failed.
102         // So, plugin initialize should be called before mainloop start.
103         if (initializePluginManager(mode) < 0) {
104                 _ERR("Failed to initialize PluginManager");
105         }
106 }
107
108 CoreRuntime::~CoreRuntime()
109 {
110         dispose();
111 }
112
113 int CoreRuntime::initialize(bool standalone)
114 {
115 #define __XSTR(x) #x
116 #define __STR(x) __XSTR(x)
117
118 #ifdef NATIVE_LIB_DIR
119         __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
120 #endif
121
122 #undef __STR
123 #undef __XSTR
124
125 #ifdef __arm__
126         // libunwind library is used to unwind stack frame, but libunwind for ARM
127         // does not support ARM vfpv3/NEON registers in DWARF format correctly.
128         // Therefore let's disable stack unwinding using DWARF information
129         // See https://github.com/dotnet/coreclr/issues/6698
130         //
131         // libunwind use following methods to unwind stack frame.
132         // UNW_ARM_METHOD_ALL          0xFF
133         // UNW_ARM_METHOD_DWARF        0x01
134         // UNW_ARM_METHOD_FRAME        0x02
135         // UNW_ARM_METHOD_EXIDX        0x04
136         putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
137 #endif // __arm__
138
139         if (initializePathManager(std::string(), std::string(), std::string()) < 0) {
140                 _ERR("Failed to initialize PathManager");
141                 return -1;
142         }
143
144         if (initializeLogManager() < 0) {
145                 _ERR("Failed to initnialize LogManager");
146                 return -1;
147         }
148
149         if (redirectFD() < 0) {
150                 _ERR("Failed to redirect FD");
151                 return -1;
152         }
153
154         if (runLoggingThread() < 0) {
155                 _ERR("Failed to create and run logging thread to redicrect log");
156                 return -1;
157         }
158
159         std::string libCoreclr(concatPath(getRuntimeDir(), "libcoreclr.so"));
160
161         __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
162         if (__coreclrLib == nullptr) {
163                 char *err = dlerror();
164                 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
165                 return -1;
166         }
167
168 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
169         do { \
170                 variable = (type)dlsym(__coreclrLib, name); \
171                 if (variable == nullptr) { \
172                         _ERR(name " is not found in the libcoreclr.so"); \
173                         return -1; \
174                 } \
175         } while (0)
176
177         CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
178         CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
179         CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
180         CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
181
182 #undef CORELIB_RETURN_IF_NOSYM
183
184         _DBG("libcoreclr dlopen and dlsym success");
185
186         if (!standalone)
187                 pluginPreload();
188
189         fd = open("/proc/self", O_DIRECTORY);
190         std::string appRoot = std::string("/proc/self/fd/") + std::to_string(fd);
191         std::string appBin = concatPath(appRoot, "bin");
192         std::string appLib = concatPath(appRoot, "lib");
193         std::string probePath = appBin + ":" + appLib;
194         std::string tpa = getTPA();
195         std::string nativeLibPath = getExtraNativeLibDirs(appRoot) + ":" + appBin + ":" + appLib + ":" + __nativeLibDirectory;
196         std::string appName = std::string("dotnet-launcher-") + std::to_string(getpid());
197
198         if (!initializeCoreClr(appName.c_str(), probePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
199                 _ERR("Failed to initialize coreclr");
200                 return -1;
201         }
202
203         __initialized = true;
204
205         return 0;
206 }
207
208 bool CoreRuntime::initializeCoreClr(const char* appId,
209                                                                          const char* assemblyProbePaths,
210                                                                          const char* pinvokeProbePaths,
211                                                                          const char* tpaList)
212 {
213         const char *propertyKeys[] = {
214                 "TRUSTED_PLATFORM_ASSEMBLIES",
215                 "APP_PATHS",
216                 "APP_NI_PATHS",
217                 "NATIVE_DLL_SEARCH_DIRECTORIES",
218                 "AppDomainCompatSwitch"
219         };
220
221         const char *propertyValues[] = {
222                 tpaList,
223                 assemblyProbePaths,
224                 assemblyProbePaths,
225                 pinvokeProbePaths,
226                 "UseLatestBehaviorWhenTFMNotSpecified"
227         };
228
229         std::string selfPath = readSelfPath();
230
231         int st = initializeClr(selfPath.c_str(),
232                                                         appId,
233                                                         sizeof(propertyKeys) / sizeof(propertyKeys[0]),
234                                                         propertyKeys,
235                                                         propertyValues,
236                                                         &__hostHandle,
237                                                         &__domainId);
238
239         if (st < 0) {
240                 _ERR("initialize core clr fail! (0x%08x)", st);
241                 return false;
242         }
243
244         pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
245
246         _DBG("Initialize core clr success");
247         return true;
248 }
249
250 void CoreRuntime::dispose()
251 {
252         if (__hostHandle != nullptr) {
253                 int st = shutdown(__hostHandle, __domainId);
254                 if (st < 0)
255                         _ERR("shutdown core clr fail! (0x%08x)", st);
256                 __hostHandle = nullptr;
257         }
258
259         if (__coreclrLib != nullptr) {
260                 if (dlclose(__coreclrLib) != 0) {
261                         _ERR("libcoreclr.so close failed");
262                 }
263
264                 __coreclrLib = nullptr;
265         }
266
267         finalizePluginManager();
268         finalizePathManager();
269
270         _DBG("Dotnet runtime disposed");
271 }
272
273 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
274 {
275         if (!__initialized) {
276                 _ERR("Runtime is not initialized");
277                 return -1;
278         }
279
280         if (path == nullptr) {
281                 _ERR("executable path is null");
282                 return -1;
283         }
284
285         if (!isFileExist(path)) {
286                 _ERR("File not exist : %s", path);
287                 return -1;
288         }
289
290         // launchpad override stdout and stderr to journalctl before launch application.
291         // we have to re-override that to input pipe for logging thread.
292         if (redirectFD() < 0) {
293                 _ERR("Failed to redirect FD");
294                 return -1;
295         }
296
297         pluginSetAppInfo(appId, path);
298
299         int fd2 = open(root, O_DIRECTORY);
300         dup3(fd2, fd, O_CLOEXEC);
301         if (fd2 >= 0)
302                 close(fd2);
303
304         pluginBeforeExecute();
305
306         unsigned int ret = 0;
307         int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
308         if (st < 0)
309                 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
310         return ret;
311 }
312
313 }  // namespace dotnetcore
314 }  // namespace runtime
315 }  // namespace tizen