c0b53008cee9ea16c46b1251d04afd0d55843d10
[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 "utils.h"
25 #include "log.h"
26 #include "launcher.h"
27 #include "dotnet_launcher.h"
28
29 namespace tizen {
30 namespace runtime {
31 namespace dotnetcore {
32
33 CoreRuntime::CoreRuntime() :
34         initializeClr(nullptr),
35         executeAssembly(nullptr),
36         shutdown(nullptr),
37         createDelegate(nullptr),
38         __coreclrLib(nullptr),
39         __hostHandle(nullptr),
40         __domainId(-1),
41         preparedFunction(nullptr),
42         launchFunction(nullptr)
43 {
44 #define __XSTR(x) #x
45 #define __STR(x) __XSTR(x)
46
47 #ifdef DEVICE_API_DIR
48         __deviceAPIDirectory = __STR(DEVICE_API_DIR);
49 #endif
50 #ifdef RUNTIME_DIR
51         __runtimeDirectory = __STR(RUNTIME_DIR);
52 #endif
53 #ifdef NATIVE_LIB_DIR
54         __nativeLibDirectory = __STR(NATIVE_LIB_DIR);
55 #endif
56
57 #ifdef USE_MANAGED_LAUNCHER
58 #ifdef CORECLR_LAUNCHER_ASSEMBLY_PATH
59         __launcherAssembly = __STR(CORECLR_LAUNCHER_ASSEMBLY_PATH);
60 #endif
61 #endif
62
63 #undef __STR
64 #undef __XSTR
65
66         _DBG("Constructor called!!");
67 }
68
69 CoreRuntime::~CoreRuntime()
70 {
71         dispose();
72 }
73
74 int CoreRuntime::initialize(bool standalone)
75 {
76 #ifdef __arm__
77         // libunwind library is used to unwind stack frame, but libunwind for ARM
78         // does not support ARM vfpv3/NEON registers in DWARF format correctly.
79         // Therefore let's disable stack unwinding using DWARF information
80         // See https://github.com/dotnet/coreclr/issues/6698
81         //
82         // libunwind use following methods to unwind stack frame.
83         // UNW_ARM_METHOD_ALL          0xFF
84         // UNW_ARM_METHOD_DWARF        0x01
85         // UNW_ARM_METHOD_FRAME        0x02
86         // UNW_ARM_METHOD_EXIDX        0x04
87         putenv(const_cast<char *>("UNW_ARM_UNWIND_METHOD=6"));
88 #endif // __arm__
89
90         if (standalone) {
91                 const char *deviceApiDirectory = getenv("__deviceAPIDirectory");
92                 const char *runtimeDirectory = getenv("__runtimeDirectory");
93                 if (deviceApiDirectory != nullptr)
94                         __deviceAPIDirectory = deviceApiDirectory;
95                 if (runtimeDirectory != nullptr)
96                         __runtimeDirectory = runtimeDirectory;
97
98 #ifdef USE_MANAGED_LAUNCHER
99                 const char *launcherAssembly = getenv("__launcherAssembly");
100                 if (launcherAssembly != nullptr)
101                         __launcherAssembly = launcherAssembly;
102 #endif
103         }
104
105         if (__deviceAPIDirectory.empty()) {
106                 _ERR("Empty Device API Directory");
107                 return 1;
108         } else {
109                 __deviceAPIDirectory = absolutePath(__deviceAPIDirectory);
110         }
111
112         if (__runtimeDirectory.empty()) {
113                 _ERR("Empty Runtime Directory");
114                 return 1;
115         } else {
116                 __runtimeDirectory = absolutePath(__runtimeDirectory);
117         }
118
119 #ifdef USE_MANAGED_LAUNCHER
120         if (__launcherAssembly.empty()) {
121                 _ERR("Empty Launcher Assembly");
122                 return 1;
123         } else {
124                 __launcherAssembly = absolutePath(__launcherAssembly);
125         }
126 #endif
127
128         std::string libCoreclr(concatPath(__runtimeDirectory, "libcoreclr.so"));
129
130         _DBG("libcoreclr : %s", libCoreclr.c_str());
131
132         __coreclrLib = dlopen(libCoreclr.c_str(), RTLD_NOW | RTLD_LOCAL);
133         if (__coreclrLib == nullptr) {
134                 char *err = dlerror();
135                 _ERR("dlopen failed to open libcoreclr.so with error %s", err);
136                 return 1;
137         }
138
139 #define CORELIB_RETURN_IF_NOSYM(type, variable, name) \
140         do { \
141                 variable = (type)dlsym(__coreclrLib, name); \
142                 if (variable == nullptr) { \
143                         _ERR(name " is not found in the libcoreclr.so"); \
144                         return 1; \
145                 } \
146         } while (0)
147
148         CORELIB_RETURN_IF_NOSYM(coreclr_initialize_ptr, initializeClr, "coreclr_initialize");
149         CORELIB_RETURN_IF_NOSYM(coreclr_execute_assembly_ptr, executeAssembly, "coreclr_execute_assembly");
150         CORELIB_RETURN_IF_NOSYM(coreclr_shutdown_ptr, shutdown, "coreclr_shutdown");
151         CORELIB_RETURN_IF_NOSYM(coreclr_create_delegate_ptr, createDelegate, "coreclr_create_delegate");
152
153 #undef CORELIB_RETURN_IF_NOSYM
154
155         _DBG("libcoreclr dlopen and dlsym success");
156         _DBG("this addr : %x", this);
157         _DBG("coreclr_initialize : %x", initializeClr);
158
159         return 0;
160 }
161
162 bool CoreRuntime::initializeCoreClr(const char* appId,
163                                                                          const char* assemblyProbePaths,
164                                                                          const char* pinvokeProbePaths,
165                                                                          const char* tpaList)
166 {
167         const char *propertyKeys[] = {
168                 "TRUSTED_PLATFORM_ASSEMBLIES",
169                 "APP_PATHS",
170                 "APP_NI_PATHS",
171                 "NATIVE_DLL_SEARCH_DIRECTORIES",
172                 "AppDomainCompatSwitch"
173         };
174
175         const char *propertyValues[] = {
176                 tpaList,
177                 assemblyProbePaths,
178                 assemblyProbePaths,
179                 pinvokeProbePaths,
180                 "UseLatestBehaviorWhenTFMNotSpecified"
181         };
182
183         std::string selfPath = readSelfPath();
184
185         int st = initializeClr(selfPath.c_str(),
186                                                         appId,
187                                                         sizeof(propertyKeys) / sizeof(propertyKeys[0]),
188                                                         propertyKeys,
189                                                         propertyValues,
190                                                         &__hostHandle,
191                                                         &__domainId);
192
193         if (st < 0) {
194                 _ERR("initialize core clr fail! (0x%08x)", st);
195                 return false;
196         }
197
198         _DBG("Initialize core clr success");
199         return true;
200 }
201
202 int CoreRuntime::runManagedLauncher(const char* appId, const char* appBase, const char* tpaList)
203 {
204         if (fileNotExist(__launcherAssembly)) {
205                 _ERR("Launcher assembly is not exist in %s", __launcherAssembly.c_str());
206                 return 1;
207         }
208
209         if (!initializeCoreClr(appId, appBase, appBase, tpaList)) {
210                 _ERR("Failed to initialize coreclr");
211                 return 1;
212         }
213
214 #ifdef USE_MANAGED_LAUNCHER
215         void *preparedFunctionDelegate;
216         int st = createDelegate(__hostHandle, __domainId,
217                                                         "Tizen.Runtime",
218                                                         "Tizen.Runtime.Coreclr.AssemblyManager",
219                                                         "Prepared", &preparedFunctionDelegate);
220         if (st < 0) {
221                 _ERR("Create delegate for Launch prepared function is fail (0x%08x)", st);
222                 return 1;
223         }
224         preparedFunction = reinterpret_cast<PreparedFunctionPtr>(preparedFunctionDelegate);
225
226         if (preparedFunction != nullptr)
227                 preparedFunction();
228
229         void *launchFunctionDelegate;
230         st = createDelegate(__hostHandle, __domainId,
231                                                 "Tizen.Runtime",
232                                                 "Tizen.Runtime.Coreclr.AssemblyManager",
233                                                 "Launch", &launchFunctionDelegate);
234         if (st < 0) {
235                 _ERR("Create delegate for Launch managed function is fail! (0x%08x)", st);
236                 return 1;
237         }
238         launchFunction = reinterpret_cast<LaunchFunctionPtr>(launchFunctionDelegate);
239 #endif
240         return 0;
241 }
242
243 void CoreRuntime::dispose()
244 {
245         if (__hostHandle != nullptr) {
246                 int st = shutdown(__hostHandle, __domainId);
247                 if (st < 0)
248                         _ERR("shutdown core clr fail! (0x%08x)", st);
249         }
250
251         if (dlclose(__coreclrLib) != 0)
252                 _ERR("libcoreclr.so close failed");
253
254         __coreclrLib = nullptr;
255
256         _DBG("Dotnet runtime disposed");
257 }
258
259 int CoreRuntime::launch(const char* appId, const char* root, const char* path, int argc, char* argv[])
260 {
261         if (path == nullptr) {
262                 _ERR("executable path is null");
263                 return 1;
264         }
265
266         if (fileNotExist(path)) {
267                 _ERR("File not exist : %s", path);
268                 return 1;
269         }
270
271         std::string tpa;
272         std::string appRoot = root;
273         std::string appBin = concatPath(appRoot, "bin");
274         std::string appLib = concatPath(appRoot, "lib");
275         std::string probePath = appBin + ":" + appLib + ":" + __nativeLibDirectory;
276
277         std::vector<std::string> searchDirectories;
278         searchDirectories.push_back(appBin);
279         searchDirectories.push_back(appLib);
280         searchDirectories.push_back(__runtimeDirectory);
281         searchDirectories.push_back(__deviceAPIDirectory);
282 #ifdef USE_MANAGED_LAUNCHER
283         searchDirectories.push_back(baseName(__launcherAssembly));
284 #endif
285
286         assembliesInDirectory(searchDirectories, tpa);
287
288 #ifdef USE_MANAGED_LAUNCHER
289         runManagedLauncher(appId, probePath.c_str(), tpa.c_str());
290
291         bool success = false;
292         if (launchFunction != nullptr) {
293                 std::string cppPath(path);
294
295                 if (isManagedAssembly(cppPath) && !isNativeImage(cppPath)) {
296                         size_t extindex = cppPath.size() - 4;
297                         cppPath = cppPath.substr(0, extindex) + ".ni" + cppPath.substr(extindex, 4);
298                         if (!fileNotExist(cppPath))
299                                 path = cppPath.c_str();
300                 }
301
302                 success = launchFunction(root, path, argc, argv);
303                 if (!success)
304                         _ERR("Failed to launch Application %s", path);
305                 return success ? 0 : 1;
306         } else {
307                 _ERR("Failed to find launch function");
308                 return 1;
309         }
310 #else
311         int st = initializeCoreClr(appId, probePath.c_str(), probePath.c_str(), tpa.c_str());
312         unsigned int ret = 0;
313         st = executeAssembly(__hostHandle, __domainId, argc, (const char**)argv, path, &ret);
314         if (st < 0)
315                 _ERR("Failed to Execute Assembly %s (0x%08x)", path, st);
316         return ret;
317 #endif
318 }
319
320 }  // namespace dotnetcore
321 }  // namespace runtime
322 }  // namespace tizen