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