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