81fdb0ce3ba1766db74c054d766f6f5b25dfc137
[platform/core/dotnet/launcher.git] / NativeLauncher / launcher / exec / corerun.cc
1 /*
2  * Copyright (c) 2020 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 #include <dlfcn.h>
18 #include <string>
19 #include "coreclr_host.h"
20 #include "log.h"
21 #include "utils.h"
22
23 static const char* CLR_PATH = "/usr/share/dotnet.tizen/netcoreapp";
24 static const char* TOOL_PATH = "/home/owner/share/.dotnet/tools";
25 static const char* DIAGNOSTICS_TOOL_PATH = "/home/owner/share/tmp/sdk_tools/coreclr-diagnostics";
26
27 void DisplayUsage() {
28         _SOUT(
29                 "Execute a .NET application or command.\n\n"
30                 "Usage: dotnet [options] [path-to-executable] [arguments]\n"
31                 "Usage: dotnet [command] [arguments]\n\n"
32                 "Options:\n"
33                 "-h, --help                         show this help message\n"
34                 "--clr-path <path>                  path to libcoreclr.so and runtime assemblies\n"
35                 "--tool-path <path>                 path to the tool installation directory\n"
36                 "--additionalprobingpath <path>     path containing assemblies to probe for\n"
37                 "--globalizationinvariant           run in globalization invariant mode\n\n"
38                 "Commands:\n"
39                 "counters       monitor or collect performance counters\n"
40                 "dump           capture or analyze a coredump\n"
41                 "gcdump         capture a heapdump\n"
42                 "trace          collect or convert a diagnostic event trace\n"
43                 "stack          reports the managed stacks\n");
44 }
45
46 int main(int argc, const char* argv[]) {
47 #ifdef __arm__
48         // libunwind library is used to unwind stack frame, but libunwind for ARM
49         // does not support ARM vfpv3/NEON registers in DWARF format correctly.
50         // Therefore let's disable stack unwinding using DWARF information
51         // See https://github.com/dotnet/runtime/issues/6479
52         //
53         // libunwind use following methods to unwind stack frame.
54         // UNW_ARM_METHOD_ALL          0xFF
55         // UNW_ARM_METHOD_DWARF        0x01
56         // UNW_ARM_METHOD_FRAME        0x02
57         // UNW_ARM_METHOD_EXIDX        0x04
58         putenv(const_cast<char*>("UNW_ARM_UNWIND_METHOD=6"));
59 #endif // __arm__
60
61         argv++;
62         argc--;
63
64         if (argc <= 0) {
65                 DisplayUsage();
66                 return -1;
67         }
68
69         std::string clrFilesPath(CLR_PATH);
70         std::string toolDllsPath(clrFilesPath + "/SOS");
71
72         std::string managedAssemblyPath;
73         std::string additionalProbingPath;
74         bool globalizationInvariant = false;
75
76         while (argc > 0) {
77                 std::string arg(argv[0]);
78
79                 if (arg == "-?" || arg == "-h" || arg == "--help") {
80                         DisplayUsage();
81                         return 0;
82                 } else if (arg == "--clr-path" && argc > 1) {
83                         clrFilesPath = argv[1];
84                         argc--;
85                         argv++;
86                 } else if (arg == "--tool-path" && argc > 1) {
87                         toolDllsPath = argv[1];
88                         argc--;
89                         argv++;
90                 } else if (arg == "--additionalprobingpath" && argc > 1) {
91                         additionalProbingPath = getAbsolutePath(argv[1]);
92                         argc--;
93                         argv++;
94                 } else if (arg == "--globalizationinvariant") {
95                         globalizationInvariant = true;
96                 } else if ((arg == "--runtimeconfig" || arg == "--depsfile") && argc > 1) {
97                         // Just for compatibility with corefx tests.
98                         // See ParseArguments() in coreclr/hosts/unixcorerun/corerun.cpp.
99                         argc--;
100                         argv++;
101                 } else if (arg.at(0) == '-') {
102                         _SERR("Unknown option %s.", argv[0]);
103                         DisplayUsage();
104                         return -1;
105                 } else if (isManagedAssembly(arg) || isNativeImage(arg)) {
106                         if (!isFile(arg)) {
107                                 _SERR("The specified file does not exist.");
108                                 return -1;
109                         }
110                         managedAssemblyPath = arg;
111                         argc--;
112                         argv++;
113                         break;
114                 } else if (arg == "exec") {
115                         // 'dotnet' and 'dotnet exec' can be alternatively used.
116                 } else if (arg == "tool") {
117                         _SERR("This command is not currently supported.");
118                         return -1;
119                 } else {
120                         std::string toolDll = "/dotnet-" + arg + ".dll";
121                         std::string searchToolPath1 = toolDllsPath + toolDll;
122                         std::string searchToolPath2 = std::string(TOOL_PATH) + toolDll;
123                         std::string searchToolPath3 = std::string(DIAGNOSTICS_TOOL_PATH) + toolDll;
124                         if (isFile(searchToolPath1)) {
125                                 managedAssemblyPath = searchToolPath1;
126                         } else if (isFile(searchToolPath2)) {
127                                 managedAssemblyPath = searchToolPath2;
128                         } else if (isFile(searchToolPath3)) {
129                                 managedAssemblyPath = searchToolPath3;
130                         } else {
131                                 _SERR(
132                                         "Could not execute because dotnet-%s does not exist.\n"
133                                         "Go to https://developer.samsung.com/tizen to learn how to install tools.\n", argv[0]);
134                                 return -1;
135                         }
136
137                         // Implicit compatibility mode for System.CommandLine.
138                         std::string termValue(getenv("TERM"));
139                         if (termValue == "linux") {
140                                 setenv("TERM", "xterm", 1);
141                         }
142
143                         argc--;
144                         argv++;
145                         break;
146                 }
147
148                 argc--;
149                 argv++;
150         }
151
152         std::string currentExeAbsolutePath = getAbsolutePath("/proc/self/exe");
153         if (currentExeAbsolutePath.empty()) {
154                 _SERR("Failed to get the current executable's absolute path.");
155                 return -1;
156         }
157
158         std::string clrFilesAbsolutePath = getAbsolutePath(clrFilesPath);
159         if (clrFilesAbsolutePath.empty()) {
160                 _SERR("Failed to resolve the full path to the CLR files.");
161                 return -1;
162         }
163
164         std::string managedAssemblyAbsolutePath = getAbsolutePath(managedAssemblyPath);
165         if (managedAssemblyAbsolutePath.empty()) {
166                 _SERR("Failed to get the managed assembly's absolute path.");
167                 return -1;
168         }
169
170         std::string coreclrLibPath(clrFilesAbsolutePath + "/libcoreclr.so");
171         std::string appPath = getBaseName(managedAssemblyAbsolutePath);
172         std::string nativeDllSearchDirs(appPath);
173         nativeDllSearchDirs += ":" + additionalProbingPath;
174         nativeDllSearchDirs += ":" + clrFilesAbsolutePath;
175
176         std::string tpaList(managedAssemblyAbsolutePath);
177         // For now we don't parse .deps.json file but let application DLLs can override runtime DLLs.
178         std::vector<std::string> tpaDirs = { appPath, additionalProbingPath, clrFilesAbsolutePath };
179         addAssembliesFromDirectories(tpaDirs, tpaList);
180
181         void* coreclrLib = dlopen(coreclrLibPath.c_str(), RTLD_NOW | RTLD_LOCAL);
182         if (coreclrLib == nullptr) {
183                 const char* error = dlerror();
184                 _SERR("dlopen failed to open the libcoreclr.so with error %s", error);
185                 return -1;
186         }
187
188         coreclr_initialize_ptr initializeCoreCLR = (coreclr_initialize_ptr)dlsym(coreclrLib, "coreclr_initialize");
189         coreclr_execute_assembly_ptr executeAssembly = (coreclr_execute_assembly_ptr)dlsym(coreclrLib, "coreclr_execute_assembly");
190         coreclr_shutdown_ptr shutdownCoreCLR = (coreclr_shutdown_ptr)dlsym(coreclrLib, "coreclr_shutdown");
191
192         if (initializeCoreCLR == nullptr) {
193                 _SERR("Function coreclr_initialize not found in the libcoreclr.so");
194                 return -1;
195         } else if (executeAssembly == nullptr) {
196                 _SERR("Function coreclr_execute_assembly not found in the libcoreclr.so");
197                 return -1;
198         } else if (shutdownCoreCLR == nullptr) {
199                 _SERR("Function coreclr_shutdown not found in the libcoreclr.so");
200                 return -1;
201         }
202
203         bool ncdbStartupHook = isNCDBStartupHookProvided();
204
205         const char* propertyKeys[] = {
206                 "TRUSTED_PLATFORM_ASSEMBLIES",
207                 "APP_PATHS",
208                 "APP_NI_PATHS",
209                 "NATIVE_DLL_SEARCH_DIRECTORIES",
210                 "System.Globalization.Invariant",
211                 ncdbStartupHook ? "STARTUP_HOOKS" : "" // must be the last one
212         };
213         const char* propertyValues[] = {
214                 tpaList.c_str(),
215                 appPath.c_str(),
216                 appPath.c_str(),
217                 nativeDllSearchDirs.c_str(),
218                 globalizationInvariant ? "true" : "false",
219                 ncdbStartupHook ? getNCDBStartupHook() : "" // must be the last one
220         };
221
222         void* hostHandle;
223         unsigned int domainId;
224
225         int st = initializeCoreCLR(
226                 currentExeAbsolutePath.c_str(),
227                 "dotnet",
228                 sizeof(propertyKeys) / sizeof(propertyKeys[0]) - (ncdbStartupHook ? 0 : 1),
229                 propertyKeys,
230                 propertyValues,
231                 &hostHandle,
232                 &domainId);
233
234         if (st < 0) {
235                 _SERR("coreclr_initialize failed - status: 0x%08x", st);
236                 return -1;
237         }
238
239         // Set the current process's command name.
240         std::string managedAssemblyName = getFileName(managedAssemblyAbsolutePath);
241         setCmdName(managedAssemblyName);
242
243         int exitCode = -1;
244
245         st = executeAssembly(
246                 hostHandle,
247                 domainId,
248                 argc,
249                 argv,
250                 managedAssemblyAbsolutePath.c_str(),
251                 (unsigned int*)&exitCode);
252
253         if (st < 0) {
254                 _SERR("coreclr_execute_assembly failed - status: 0x%08x", st);
255                 exitCode = -1;
256         }
257
258         st = shutdownCoreCLR(hostHandle, domainId);
259         if (st < 0) {
260                 _SERR("coreclr_shutdown failed - status: 0x%08x", st);
261                 return -1;
262         }
263
264         return exitCode;
265 }