Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/tools/lldb-server/lldb-platform.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- lldb-platform.cpp ---------------------------------------*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
9
#include <cerrno>
10
#if defined(__APPLE__)
11
#include <netinet/in.h>
12
#endif
13
#include <csignal>
14
#include <cstdint>
15
#include <cstdio>
16
#include <cstdlib>
17
#include <cstring>
18
#if !defined(_WIN32)
19
#include <sys/wait.h>
20
#endif
21
#include <fstream>
22
23
#include "llvm/Support/FileSystem.h"
24
#include "llvm/Support/FileUtilities.h"
25
#include "llvm/Support/WithColor.h"
26
#include "llvm/Support/raw_ostream.h"
27
28
#include "Acceptor.h"
29
#include "LLDBServerUtilities.h"
30
#include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.h"
31
#include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
32
#include "lldb/Host/ConnectionFileDescriptor.h"
33
#include "lldb/Host/HostGetOpt.h"
34
#include "lldb/Host/OptionParser.h"
35
#include "lldb/Host/common/TCPSocket.h"
36
#include "lldb/Utility/FileSpec.h"
37
#include "lldb/Utility/Status.h"
38
39
using namespace lldb;
40
using namespace lldb_private;
41
using namespace lldb_private::lldb_server;
42
using namespace lldb_private::process_gdb_remote;
43
using namespace llvm;
44
45
// option descriptors for getopt_long_only()
46
47
static int g_debug = 0;
48
static int g_verbose = 0;
49
static int g_server = 0;
50
51
static struct option g_long_options[] = {
52
    {"debug", no_argument, &g_debug, 1},
53
    {"verbose", no_argument, &g_verbose, 1},
54
    {"log-file", required_argument, nullptr, 'l'},
55
    {"log-channels", required_argument, nullptr, 'c'},
56
    {"listen", required_argument, nullptr, 'L'},
57
    {"port-offset", required_argument, nullptr, 'p'},
58
    {"gdbserver-port", required_argument, nullptr, 'P'},
59
    {"min-gdbserver-port", required_argument, nullptr, 'm'},
60
    {"max-gdbserver-port", required_argument, nullptr, 'M'},
61
    {"socket-file", required_argument, nullptr, 'f'},
62
    {"server", no_argument, &g_server, 1},
63
    {nullptr, 0, nullptr, 0}};
64
65
#if defined(__APPLE__)
66
4
#define LOW_PORT (IPPORT_RESERVED)
67
2
#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
68
#else
69
#define LOW_PORT (1024u)
70
#define HIGH_PORT (49151u)
71
#endif
72
73
#if !defined(_WIN32)
74
// Watch for signals
75
0
static void signal_handler(int signo) {
76
0
  switch (signo) {
77
0
  case SIGHUP:
78
    // Use SIGINT first, if that does not work, use SIGHUP as a last resort.
79
    // And we should not call exit() here because it results in the global
80
    // destructors
81
    // to be invoked and wreaking havoc on the threads still running.
82
0
    Host::SystemLog(Host::eSystemLogWarning,
83
0
                    "SIGHUP received, exiting lldb-server...\n");
84
0
    abort();
85
0
    break;
86
0
  }
87
0
}
88
#endif
89
90
1
static void display_usage(const char *progname, const char *subcommand) {
91
1
  fprintf(stderr, "Usage:\n  %s %s [--log-file log-file-name] [--log-channels "
92
1
                  "log-channel-list] [--port-file port-file-path] --server "
93
1
                  "--listen port\n",
94
1
          progname, subcommand);
95
1
  exit(0);
96
1
}
97
98
static Status save_socket_id_to_file(const std::string &socket_id,
99
0
                                     const FileSpec &file_spec) {
100
0
  FileSpec temp_file_spec(file_spec.GetDirectory().GetStringRef());
101
0
  Status error(llvm::sys::fs::create_directory(temp_file_spec.GetPath()));
102
0
  if (error.Fail())
103
0
    return Status("Failed to create directory %s: %s",
104
0
                  temp_file_spec.GetCString(), error.AsCString());
105
106
0
  llvm::SmallString<64> temp_file_path;
107
0
  temp_file_spec.AppendPathComponent("port-file.%%%%%%");
108
0
  temp_file_path = temp_file_spec.GetPath();
109
110
0
  Status status;
111
0
  if (auto Err =
112
0
          handleErrors(llvm::writeFileAtomically(
113
0
                           temp_file_path, file_spec.GetPath(), socket_id),
114
0
                       [&status, &file_spec](const AtomicFileWriteError &E) {
115
0
                         std::string ErrorMsgBuffer;
116
0
                         llvm::raw_string_ostream S(ErrorMsgBuffer);
117
0
                         E.log(S);
118
119
0
                         switch (E.Error) {
120
0
                         case atomic_write_error::failed_to_create_uniq_file:
121
0
                           status = Status("Failed to create temp file: %s",
122
0
                                           ErrorMsgBuffer.c_str());
123
0
                           break;
124
0
                         case atomic_write_error::output_stream_error:
125
0
                           status = Status("Failed to write to port file.");
126
0
                           break;
127
0
                         case atomic_write_error::failed_to_rename_temp_file:
128
0
                           status = Status("Failed to rename file %s to %s: %s",
129
0
                                           ErrorMsgBuffer.c_str(),
130
0
                                           file_spec.GetPath().c_str(),
131
0
                                           ErrorMsgBuffer.c_str());
132
0
                           break;
133
0
                         }
134
0
                       })) {
135
0
    return Status("Failed to atomically write file %s",
136
0
                  file_spec.GetPath().c_str());
137
0
  }
138
0
  return status;
139
0
}
140
141
// main
142
1
int main_platform(int argc, char *argv[]) {
143
1
  const char *progname = argv[0];
144
1
  const char *subcommand = argv[1];
145
1
  argc--;
146
1
  argv++;
147
1
#if !defined(_WIN32)
148
1
  signal(SIGPIPE, SIG_IGN);
149
1
  signal(SIGHUP, signal_handler);
150
1
#endif
151
1
  int long_option_index = 0;
152
1
  Status error;
153
1
  std::string listen_host_port;
154
1
  int ch;
155
156
1
  std::string log_file;
157
1
  StringRef
158
1
      log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
159
160
1
  GDBRemoteCommunicationServerPlatform::PortMap gdbserver_portmap;
161
1
  int min_gdbserver_port = 0;
162
1
  int max_gdbserver_port = 0;
163
1
  uint16_t port_offset = 0;
164
165
1
  FileSpec socket_file;
166
1
  bool show_usage = false;
167
1
  int option_error = 0;
168
1
  int socket_error = -1;
169
170
1
  std::string short_options(OptionParser::GetShortOptionString(g_long_options));
171
172
#if __GLIBC__
173
  optind = 0;
174
#else
175
1
  optreset = 1;
176
1
  optind = 1;
177
1
#endif
178
179
5
  while ((ch = getopt_long_only(argc, argv, short_options.c_str(),
180
5
                                g_long_options, &long_option_index)) != -1) {
181
4
    switch (ch) {
182
1
    case 0: // Any optional that auto set themselves will return 0
183
1
      break;
184
185
1
    case 'L':
186
1
      listen_host_port.append(optarg);
187
1
      break;
188
189
0
    case 'l': // Set Log File
190
0
      if (optarg && optarg[0])
191
0
        log_file.assign(optarg);
192
0
      break;
193
194
0
    case 'c': // Log Channels
195
0
      if (optarg && optarg[0])
196
0
        log_channels = StringRef(optarg);
197
0
      break;
198
199
0
    case 'f': // Socket file
200
0
      if (optarg && optarg[0])
201
0
        socket_file.SetFile(optarg, FileSpec::Style::native);
202
0
      break;
203
204
0
    case 'p': {
205
0
      if (!llvm::to_integer(optarg, port_offset)) {
206
0
        WithColor::error() << "invalid port offset string " << optarg << "\n";
207
0
        option_error = 4;
208
0
        break;
209
0
      }
210
0
      if (port_offset < LOW_PORT || port_offset > HIGH_PORT) {
211
0
        WithColor::error() << llvm::formatv(
212
0
            "port offset {0} is not in the "
213
0
            "valid user port range of {1} - {2}\n",
214
0
            port_offset, LOW_PORT, HIGH_PORT);
215
0
        option_error = 5;
216
0
      }
217
0
    } break;
218
219
0
    case 'P':
220
1
    case 'm':
221
2
    case 'M': {
222
2
      uint16_t portnum;
223
2
      if (!llvm::to_integer(optarg, portnum)) {
224
0
        WithColor::error() << "invalid port number string " << optarg << "\n";
225
0
        option_error = 2;
226
0
        break;
227
0
      }
228
2
      if (portnum < LOW_PORT || portnum > HIGH_PORT) {
229
0
        WithColor::error() << llvm::formatv(
230
0
            "port number {0} is not in the "
231
0
            "valid user port range of {1} - {2}\n",
232
0
            portnum, LOW_PORT, HIGH_PORT);
233
0
        option_error = 1;
234
0
        break;
235
0
      }
236
2
      if (ch == 'P')
237
0
        gdbserver_portmap.AllowPort(portnum);
238
2
      else if (ch == 'm')
239
1
        min_gdbserver_port = portnum;
240
1
      else
241
1
        max_gdbserver_port = portnum;
242
2
    } break;
243
244
0
    case 'h': /* fall-through is intentional */
245
0
    case '?':
246
0
      show_usage = true;
247
0
      break;
248
4
    }
249
4
  }
250
251
1
  if (!LLDBServerUtilities::SetupLogging(log_file, log_channels, 0))
252
0
    return -1;
253
254
  // Make a port map for a port range that was specified.
255
1
  if (min_gdbserver_port && min_gdbserver_port < max_gdbserver_port) {
256
0
    gdbserver_portmap = GDBRemoteCommunicationServerPlatform::PortMap(
257
0
        min_gdbserver_port, max_gdbserver_port);
258
1
  } else if (min_gdbserver_port || 
max_gdbserver_port0
) {
259
1
    WithColor::error() << llvm::formatv(
260
1
        "--min-gdbserver-port ({0}) is not lower than "
261
1
        "--max-gdbserver-port ({1})\n",
262
1
        min_gdbserver_port, max_gdbserver_port);
263
1
    option_error = 3;
264
1
  }
265
266
  // Print usage and exit if no listening port is specified.
267
1
  if (listen_host_port.empty())
268
0
    show_usage = true;
269
270
1
  if (show_usage || option_error) {
271
1
    display_usage(progname, subcommand);
272
1
    exit(option_error);
273
1
  }
274
275
  // Skip any options we consumed with getopt_long_only.
276
0
  argc -= optind;
277
0
  argv += optind;
278
0
  lldb_private::Args inferior_arguments;
279
0
  inferior_arguments.SetArguments(argc, const_cast<const char **>(argv));
280
281
0
  const bool children_inherit_listen_socket = false;
282
  // the test suite makes many connections in parallel, let's not miss any.
283
  // The highest this should get reasonably is a function of the number
284
  // of target CPUs. For now, let's just use 100.
285
0
  const int backlog = 100;
286
287
0
  std::unique_ptr<Acceptor> acceptor_up(Acceptor::Create(
288
0
      listen_host_port, children_inherit_listen_socket, error));
289
0
  if (error.Fail()) {
290
0
    fprintf(stderr, "failed to create acceptor: %s", error.AsCString());
291
0
    exit(socket_error);
292
0
  }
293
294
0
  error = acceptor_up->Listen(backlog);
295
0
  if (error.Fail()) {
296
0
    printf("failed to listen: %s\n", error.AsCString());
297
0
    exit(socket_error);
298
0
  }
299
0
  if (socket_file) {
300
0
    error =
301
0
        save_socket_id_to_file(acceptor_up->GetLocalSocketId(), socket_file);
302
0
    if (error.Fail()) {
303
0
      fprintf(stderr, "failed to write socket id to %s: %s\n",
304
0
              socket_file.GetPath().c_str(), error.AsCString());
305
0
      return 1;
306
0
    }
307
0
  }
308
309
0
  do {
310
0
    GDBRemoteCommunicationServerPlatform platform(
311
0
        acceptor_up->GetSocketProtocol(), acceptor_up->GetSocketScheme());
312
313
0
    if (port_offset > 0)
314
0
      platform.SetPortOffset(port_offset);
315
316
0
    if (!gdbserver_portmap.empty()) {
317
0
      platform.SetPortMap(std::move(gdbserver_portmap));
318
0
    }
319
320
0
    const bool children_inherit_accept_socket = true;
321
0
    Connection *conn = nullptr;
322
0
    error = acceptor_up->Accept(children_inherit_accept_socket, conn);
323
0
    if (error.Fail()) {
324
0
      WithColor::error() << error.AsCString() << '\n';
325
0
      exit(socket_error);
326
0
    }
327
0
    printf("Connection established.\n");
328
0
    if (g_server) {
329
      // Collect child zombie processes.
330
0
#if !defined(_WIN32)
331
0
      while (waitpid(-1, nullptr, WNOHANG) > 0)
332
0
        ;
333
0
#endif
334
0
      if (fork()) {
335
        // Parent doesn't need a connection to the lldb client
336
0
        delete conn;
337
338
        // Parent will continue to listen for new connections.
339
0
        continue;
340
0
      } else {
341
        // Child process will handle the connection and exit.
342
0
        g_server = 0;
343
        // Listening socket is owned by parent process.
344
0
        acceptor_up.release();
345
0
      }
346
0
    } else {
347
      // If not running as a server, this process will not accept
348
      // connections while a connection is active.
349
0
      acceptor_up.reset();
350
0
    }
351
0
    platform.SetConnection(std::unique_ptr<Connection>(conn));
352
353
0
    if (platform.IsConnected()) {
354
0
      if (inferior_arguments.GetArgumentCount() > 0) {
355
0
        lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
356
0
        llvm::Optional<uint16_t> port = 0;
357
0
        std::string socket_name;
358
0
        Status error = platform.LaunchGDBServer(inferior_arguments,
359
0
                                                "", // hostname
360
0
                                                pid, port, socket_name);
361
0
        if (error.Success())
362
0
          platform.SetPendingGdbServer(pid, *port, socket_name);
363
0
        else
364
0
          fprintf(stderr, "failed to start gdbserver: %s\n", error.AsCString());
365
0
      }
366
367
0
      bool interrupt = false;
368
0
      bool done = false;
369
0
      while (!interrupt && !done) {
370
0
        if (platform.GetPacketAndSendResponse(llvm::None, error, interrupt,
371
0
                                              done) !=
372
0
            GDBRemoteCommunication::PacketResult::Success)
373
0
          break;
374
0
      }
375
376
0
      if (error.Fail())
377
0
        WithColor::error() << error.AsCString() << '\n';
378
0
    }
379
0
  } while (g_server);
380
381
0
  fprintf(stderr, "lldb-server exiting...\n");
382
383
0
  return 0;
384
0
}