[Coverity-112249] Fixed coverity issue. (NEGATIVE_RETURNS)
[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
35 #define PLUGIN_PATH "/usr/share/dotnet.tizen/lib/libdotnet_plugin.so"
36
37 namespace tizen {
38 namespace runtime {
39 namespace dotnetcore {
40
41 #if defined (__aarch64__)
42 #define ARCHITECTURE_IDENTIFIER "arm64"
43 const static std::vector<std::string> RID_FALLBACK_GRAPH =
44         {"linux-arm64", "linux", "unix-arm64", "unix", "any", "base"};
45
46 #elif defined (__arm__)
47 #define ARCHITECTURE_IDENTIFIER "arm"
48 const static std::vector<std::string> RID_FALLBACK_GRAPH =
49         {"tizen.4.0.0-armel", "tizen.4.0.0", "tizen-armel", "tizen", "linux-armel", "linux", "unix-armel", "unix", "any", "base"};
50
51 #elif defined (__x86_64__)
52 #define ARCHITECTURE_IDENTIFIER "x64"
53 const static std::vector<std::string> RID_FALLBACK_GRAPH =
54         {"linux-x64", "linux", "unix-x64", "unix", "any", "base"};
55
56 #elif defined (__i386__)
57 #define ARCHITECTURE_IDENTIFIER "x86"
58 const static std::vector<std::string> RID_FALLBACK_GRAPH =
59         {"linux-x86", "linux", "unix-x86", "unix", "any", "base"};
60
61 #else
62 #error "Unknown target"
63 #endif
64
65 static std::string getExtraNativeLibDirs(const std::string& appRoot)
66 {
67         std::string candidate;
68         for (unsigned int i = 0; i < RID_FALLBACK_GRAPH.size(); i++) {
69                 if(!candidate.empty()) {
70                         candidate += ":";
71                 }
72                 candidate += concatPath(appRoot, "bin/runtimes/" + RID_FALLBACK_GRAPH[i] + "/native");
73         }
74
75         candidate = candidate + ":" + concatPath(appRoot, "lib/" ARCHITECTURE_IDENTIFIER);
76         if (!strncmp(ARCHITECTURE_IDENTIFIER, "arm64", 5)) {
77                 candidate = candidate + ":" + concatPath(appRoot, "lib/aarch64");
78         }
79
80         return candidate;
81 }
82
83 CoreRuntime::CoreRuntime(const char* mode) :
84         initializeClr(nullptr),
85         executeAssembly(nullptr),
86         shutdown(nullptr),
87         createDelegate(nullptr),
88         __coreclrLib(nullptr),
89         __hostHandle(nullptr),
90         __domainId(-1),
91         preparedFunction(nullptr),
92         launchFunction(nullptr),
93         __pluginLib(nullptr),
94         pluginInitialize(nullptr),
95         pluginPreload(nullptr),
96         pluginSetAppInfo(nullptr),
97         pluginSetCoreclrInfo(nullptr),
98         pluginGetDllPath(nullptr),
99         pluginBeforeExecute(nullptr),
100         pluginFinalize(nullptr),
101         fd(0),
102         __mode(mode)
103 {
104 #define __XSTR(x) #x
105 #define __STR(x) __XSTR(x)
106
107 #ifdef DEVICE_API_DIR
108         __deviceAPIDirectory = __STR(DEVICE_API_DIR);
109 #endif
110 #ifdef RUNTIME_DIR
111         __runtimeDirectory = __STR(RUNTIME_DIR);
112 #endif
113 #ifdef NATIVE_LIB_DIR
114         __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
115 #endif
116
117 #undef __STR
118 #undef __XSTR
119
120         // support launcher plugin
121         if (!fileNotExist(PLUGIN_PATH)) {
122                 __pluginLib = dlopen(PLUGIN_PATH, RTLD_NOW | RTLD_LOCAL);
123                 if (__pluginLib) {
124                         pluginInitialize  = (plugin_initialize_ptr)dlsym(__pluginLib, "plugin_initialize");
125                         pluginPreload  = (plugin_preload_ptr)dlsym(__pluginLib, "plugin_preload");
126                         pluginSetAppInfo  = (plugin_set_app_info_ptr)dlsym(__pluginLib, "plugin_set_app_info");
127                         pluginSetCoreclrInfo = (plugin_set_coreclr_info_ptr)dlsym(__pluginLib, "plugin_set_coreclr_info");
128                         pluginGetDllPath  = (plugin_get_dll_path_ptr)dlsym(__pluginLib, "plugin_get_dll_path");
129                         pluginBeforeExecute  = (plugin_before_execute_ptr)dlsym(__pluginLib, "plugin_before_execute");
130                         pluginFinalize  = (plugin_finalize_ptr)dlsym(__pluginLib, "plugin_finalize");
131                 }
132         }
133
134         if (pluginInitialize)
135                 pluginInitialize(mode);
136
137         _DBG("Constructor called!!");
138 }
139
140 CoreRuntime::~CoreRuntime()
141 {
142         dispose();
143 }
144
145 int CoreRuntime::initialize(bool standalone)
146 {
147 #ifdef __arm__
148         // libunwind library is used to unwind stack frame, but libunwind for ARM
149         // does not support ARM vfpv3/NEON registers in DWARF format correctly.
150         // Therefore let's disable stack unwinding using DWARF information
151         // See https://github.com/dotnet/coreclr/issues/6698
152         //
153         // libunwind use following methods to unwind stack frame.
154         // UNW_ARM_METHOD_ALL          0xFF
155         // UNW_ARM_METHOD_DWARF        0x01
156         // UNW_ARM_METHOD_FRAME        0x02
157         // UNW_ARM_METHOD_EXIDX        0x04
158         putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
159 #endif // __arm__
160
161         if (__deviceAPIDirectory.empty()) {
162                 _ERR("Empty Device API Directory");
163                 return 1;
164         } else {
165                 __deviceAPIDirectory = absolutePath(__deviceAPIDirectory);
166         }
167
168         if (__runtimeDirectory.empty()) {
169                 _ERR("Empty Runtime Directory");
170                 return 1;
171         } else {
172                 __runtimeDirectory = absolutePath(__runtimeDirectory);
173         }
174
175         // set Reference API directory
176         __refAPIDirectory = __deviceAPIDirectory + "/ref";
177
178         std::string libCoreclr(concatPath(__runtimeDirectory, "libcoreclr.so"));
179
180         _DBG("libcoreclr : %s", libCoreclr.c_str());
181
182         __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
183         if (__coreclrLib == nullptr) {
184                 char *err = dlerror();
185                 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
186                 return 1;
187         }
188
189 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
190         do { \
191                 variable = (type)dlsym(__coreclrLib, name); \
192                 if (variable == nullptr) { \
193                         _ERR(name " is not found in the libcoreclr.so"); \
194                         return 1; \
195                 } \
196         } while (0)
197
198         CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
199         CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
200         CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
201         CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
202
203 #undef CORELIB_RETURN_IF_NOSYM
204
205         _DBG("libcoreclr dlopen and dlsym success");
206
207         if (!standalone && pluginPreload)
208                 pluginPreload();
209
210         fd = open("/proc/self", O_DIRECTORY);
211         std::string path_tmp = std::string("/proc/self/fd/") + std::to_string(fd);
212
213         std::string appRoot = path_tmp;
214         std::string appBin = concatPath(appRoot, "bin");
215         std::string appLib = concatPath(appRoot, "lib");
216         std::string probePath = appBin + ":" + appLib;
217
218         std::string tpa;
219         std::vector<std::string> searchDirectories;
220         searchDirectories.push_back(__runtimeDirectory);
221         searchDirectories.push_back(__deviceAPIDirectory);
222         searchDirectories.push_back(__refAPIDirectory);
223
224         if (pluginGetDllPath) {
225                 std::string pluginPath = pluginGetDllPath();
226                 if (!pluginPath.empty()) {
227                         splitPath(pluginPath, searchDirectories);
228                 }
229         }
230
231         assembliesInDirectory(searchDirectories, tpa);
232
233         std::string nativeLibPath;
234         nativeLibPath = getExtraNativeLibDirs(appRoot) + ":" + appBin + ":" + appLib + ":" + __nativeLibDirectory;
235
236         std::string appName = std::string("dotnet-launcher-") + std::to_string(getpid());
237         if (!initializeCoreClr(appName.c_str(), probePath.c_str(), nativeLibPath.c_str(), tpa.c_str())) {
238                 _ERR("Failed to initialize coreclr");
239                 return 1;
240         }
241
242         return 0;
243 }
244
245 bool CoreRuntime::initializeCoreClr(const char* appId,
246                                                                          const char* assemblyProbePaths,
247                                                                          const char* pinvokeProbePaths,
248                                                                          const char* tpaList)
249 {
250         const char *propertyKeys[] = {
251                 "TRUSTED_PLATFORM_ASSEMBLIES",
252                 "APP_PATHS",
253                 "APP_NI_PATHS",
254                 "NATIVE_DLL_SEARCH_DIRECTORIES",
255                 "AppDomainCompatSwitch"
256         };
257
258         const char *propertyValues[] = {
259                 tpaList,
260                 assemblyProbePaths,
261                 assemblyProbePaths,
262                 pinvokeProbePaths,
263                 "UseLatestBehaviorWhenTFMNotSpecified"
264         };
265
266         std::string selfPath = readSelfPath();
267
268         int st = initializeClr(selfPath.c_str(),
269                                                         appId,
270                                                         sizeof(propertyKeys) / sizeof(propertyKeys[0]),
271                                                         propertyKeys,
272                                                         propertyValues,
273                                                         &__hostHandle,
274                                                         &__domainId);
275
276         if (st < 0) {
277                 _ERR("initialize core clr fail! (0x%08x)", st);
278                 return false;
279         }
280
281         if (pluginSetCoreclrInfo)
282                 pluginSetCoreclrInfo(__hostHandle, __domainId, createDelegate);
283
284         _DBG("Initialize core clr success");
285         return true;
286 }
287
288 void CoreRuntime::dispose()
289 {
290         if (__hostHandle != nullptr) {
291                 int st = shutdown(__hostHandle, __domainId);
292                 if (st < 0)
293                         _ERR("shutdown core clr fail! (0x%08x)", st);
294         }
295
296         if (dlclose(__coreclrLib) != 0)
297                 _ERR("libcoreclr.so close failed");
298
299         __coreclrLib = nullptr;
300
301         if (pluginFinalize)
302                 pluginFinalize();
303
304         if (__pluginLib != nullptr) {
305                 if (dlclose(__pluginLib) != 0)
306                         _ERR("libdotnet_plugin.so close failed");
307
308                 __pluginLib = nullptr;
309                 pluginInitialize = nullptr;
310                 pluginPreload = nullptr;
311                 pluginSetAppInfo = nullptr;
312                 pluginSetCoreclrInfo = nullptr;
313                 pluginGetDllPath = nullptr;
314                 pluginBeforeExecute = nullptr;
315                 pluginFinalize = nullptr;
316         }
317
318         _DBG("Dotnet runtime disposed");
319 }
320
321 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
322 {
323         if (runLoggingThread() < 0) {
324                 _ERR("Failed to create logging thread");
325         }
326
327         if (path == nullptr) {
328                 _ERR("executable path is null");
329                 return 1;
330         }
331
332         if (fileNotExist(path)) {
333                 _ERR("File not exist : %s", path);
334                 return 1;
335         }
336
337         if (pluginSetAppInfo)
338                 pluginSetAppInfo(appId, path);
339
340         int fd2 = open(root, O_DIRECTORY);
341         dup3(fd2, fd, O_CLOEXEC);
342         if (fd2 >= 0)
343                 close(fd2);
344
345         if (pluginBeforeExecute)
346                 pluginBeforeExecute();
347
348         if (runLoggingThread() < 0) {
349                 _ERR("Failed to create logging thread");
350         }
351
352         unsigned int ret = 0;
353         int st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
354         if (st < 0)
355                 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
356         return ret;
357 }
358
359 }  // namespace dotnetcore
360 }  // namespace runtime
361 }  // namespace tizen