Coverage Report

Created: 2022-01-22 13:19

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/tools/lldb-server/lldb-gdbserver.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- lldb-gdbserver.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
#include <cstdint>
11
#include <cstdio>
12
#include <cstdlib>
13
#include <cstring>
14
15
#ifndef _WIN32
16
#include <csignal>
17
#include <unistd.h>
18
#endif
19
20
#include "LLDBServerUtilities.h"
21
#include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h"
22
#include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
23
#include "lldb/Host/Config.h"
24
#include "lldb/Host/ConnectionFileDescriptor.h"
25
#include "lldb/Host/FileSystem.h"
26
#include "lldb/Host/Pipe.h"
27
#include "lldb/Host/Socket.h"
28
#include "lldb/Host/common/NativeProcessProtocol.h"
29
#include "lldb/Target/Process.h"
30
#include "lldb/Utility/Status.h"
31
#include "llvm/ADT/StringRef.h"
32
#include "llvm/Option/ArgList.h"
33
#include "llvm/Option/OptTable.h"
34
#include "llvm/Option/Option.h"
35
#include "llvm/Support/Errno.h"
36
#include "llvm/Support/WithColor.h"
37
38
#if defined(__linux__)
39
#include "Plugins/Process/Linux/NativeProcessLinux.h"
40
#elif defined(__FreeBSD__)
41
#include "Plugins/Process/FreeBSD/NativeProcessFreeBSD.h"
42
#elif defined(__NetBSD__)
43
#include "Plugins/Process/NetBSD/NativeProcessNetBSD.h"
44
#elif defined(_WIN32)
45
#include "Plugins/Process/Windows/Common/NativeProcessWindows.h"
46
#endif
47
48
#ifndef LLGS_PROGRAM_NAME
49
0
#define LLGS_PROGRAM_NAME "lldb-server"
50
#endif
51
52
#ifndef LLGS_VERSION_STR
53
0
#define LLGS_VERSION_STR "local_build"
54
#endif
55
56
using namespace llvm;
57
using namespace lldb;
58
using namespace lldb_private;
59
using namespace lldb_private::lldb_server;
60
using namespace lldb_private::process_gdb_remote;
61
62
namespace {
63
#if defined(__linux__)
64
typedef process_linux::NativeProcessLinux::Factory NativeProcessFactory;
65
#elif defined(__FreeBSD__)
66
typedef process_freebsd::NativeProcessFreeBSD::Factory NativeProcessFactory;
67
#elif defined(__NetBSD__)
68
typedef process_netbsd::NativeProcessNetBSD::Factory NativeProcessFactory;
69
#elif defined(_WIN32)
70
typedef NativeProcessWindows::Factory NativeProcessFactory;
71
#else
72
// Dummy implementation to make sure the code compiles
73
class NativeProcessFactory : public NativeProcessProtocol::Factory {
74
public:
75
  llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
76
  Launch(ProcessLaunchInfo &launch_info,
77
         NativeProcessProtocol::NativeDelegate &delegate,
78
0
         MainLoop &mainloop) const override {
79
0
    llvm_unreachable("Not implemented");
80
0
  }
81
  llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
82
  Attach(lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &delegate,
83
0
         MainLoop &mainloop) const override {
84
0
    llvm_unreachable("Not implemented");
85
0
  }
86
};
87
#endif
88
}
89
90
#ifndef _WIN32
91
// Watch for signals
92
static int g_sighup_received_count = 0;
93
94
0
static void sighup_handler(MainLoopBase &mainloop) {
95
0
  ++g_sighup_received_count;
96
97
0
  Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
98
0
  LLDB_LOGF(log, "lldb-server:%s swallowing SIGHUP (receive count=%d)",
99
0
            __FUNCTION__, g_sighup_received_count);
100
101
0
  if (g_sighup_received_count >= 2)
102
0
    mainloop.RequestTermination();
103
0
}
104
#endif // #ifndef _WIN32
105
106
void handle_attach_to_pid(GDBRemoteCommunicationServerLLGS &gdb_server,
107
0
                          lldb::pid_t pid) {
108
0
  Status error = gdb_server.AttachToProcess(pid);
109
0
  if (error.Fail()) {
110
0
    fprintf(stderr, "error: failed to attach to pid %" PRIu64 ": %s\n", pid,
111
0
            error.AsCString());
112
0
    exit(1);
113
0
  }
114
0
}
115
116
void handle_attach_to_process_name(GDBRemoteCommunicationServerLLGS &gdb_server,
117
0
                                   const std::string &process_name) {
118
  // FIXME implement.
119
0
}
120
121
void handle_attach(GDBRemoteCommunicationServerLLGS &gdb_server,
122
0
                   const std::string &attach_target) {
123
0
  assert(!attach_target.empty() && "attach_target cannot be empty");
124
125
  // First check if the attach_target is convertible to a long. If so, we'll use
126
  // it as a pid.
127
0
  char *end_p = nullptr;
128
0
  const long int pid = strtol(attach_target.c_str(), &end_p, 10);
129
130
  // We'll call it a match if the entire argument is consumed.
131
0
  if (end_p &&
132
0
      static_cast<size_t>(end_p - attach_target.c_str()) ==
133
0
          attach_target.size())
134
0
    handle_attach_to_pid(gdb_server, static_cast<lldb::pid_t>(pid));
135
0
  else
136
0
    handle_attach_to_process_name(gdb_server, attach_target);
137
0
}
138
139
void handle_launch(GDBRemoteCommunicationServerLLGS &gdb_server,
140
0
                   llvm::ArrayRef<llvm::StringRef> Arguments) {
141
0
  ProcessLaunchInfo info;
142
0
  info.GetFlags().Set(eLaunchFlagStopAtEntry | eLaunchFlagDebug |
143
0
                      eLaunchFlagDisableASLR);
144
0
  info.SetArguments(Args(Arguments), true);
145
146
0
  llvm::SmallString<64> cwd;
147
0
  if (std::error_code ec = llvm::sys::fs::current_path(cwd)) {
148
0
    llvm::errs() << "Error getting current directory: " << ec.message() << "\n";
149
0
    exit(1);
150
0
  }
151
0
  FileSpec cwd_spec(cwd);
152
0
  FileSystem::Instance().Resolve(cwd_spec);
153
0
  info.SetWorkingDirectory(cwd_spec);
154
0
  info.GetEnvironment() = Host::GetEnvironment();
155
156
0
  gdb_server.SetLaunchInfo(info);
157
158
0
  Status error = gdb_server.LaunchProcess();
159
0
  if (error.Fail()) {
160
0
    llvm::errs() << llvm::formatv("error: failed to launch '{0}': {1}\n",
161
0
                                  Arguments[0], error);
162
0
    exit(1);
163
0
  }
164
0
}
165
166
0
Status writeSocketIdToPipe(Pipe &port_pipe, llvm::StringRef socket_id) {
167
0
  size_t bytes_written = 0;
168
  // Write the port number as a C string with the NULL terminator.
169
0
  return port_pipe.Write(socket_id.data(), socket_id.size() + 1, bytes_written);
170
0
}
171
172
Status writeSocketIdToPipe(const char *const named_pipe_path,
173
0
                           llvm::StringRef socket_id) {
174
0
  Pipe port_name_pipe;
175
  // Wait for 10 seconds for pipe to be opened.
176
0
  auto error = port_name_pipe.OpenAsWriterWithTimeout(named_pipe_path, false,
177
0
                                                      std::chrono::seconds{10});
178
0
  if (error.Fail())
179
0
    return error;
180
0
  return writeSocketIdToPipe(port_name_pipe, socket_id);
181
0
}
182
183
Status writeSocketIdToPipe(lldb::pipe_t unnamed_pipe,
184
0
                           llvm::StringRef socket_id) {
185
0
  Pipe port_pipe{LLDB_INVALID_PIPE, unnamed_pipe};
186
0
  return writeSocketIdToPipe(port_pipe, socket_id);
187
0
}
188
189
void ConnectToRemote(MainLoop &mainloop,
190
                     GDBRemoteCommunicationServerLLGS &gdb_server,
191
                     bool reverse_connect, llvm::StringRef host_and_port,
192
                     const char *const progname, const char *const subcommand,
193
                     const char *const named_pipe_path, pipe_t unnamed_pipe,
194
0
                     int connection_fd) {
195
0
  Status error;
196
197
0
  std::unique_ptr<Connection> connection_up;
198
0
  std::string url;
199
200
0
  if (connection_fd != -1) {
201
0
    url = llvm::formatv("fd://{0}", connection_fd).str();
202
203
    // Create the connection.
204
0
#if LLDB_ENABLE_POSIX && !defined _WIN32
205
0
    ::fcntl(connection_fd, F_SETFD, FD_CLOEXEC);
206
0
#endif
207
0
  } else if (!host_and_port.empty()) {
208
0
    llvm::Expected<std::string> url_exp =
209
0
        LLGSArgToURL(host_and_port, reverse_connect);
210
0
    if (!url_exp) {
211
0
      llvm::errs() << llvm::formatv("error: invalid host:port or URL '{0}': "
212
0
                                    "{1}\n",
213
0
                                    host_and_port,
214
0
                                    llvm::toString(url_exp.takeError()));
215
0
      exit(-1);
216
0
    }
217
218
0
    url = std::move(url_exp.get());
219
0
  }
220
221
0
  if (!url.empty()) {
222
    // Create the connection or server.
223
0
    std::unique_ptr<ConnectionFileDescriptor> conn_fd_up{
224
0
        new ConnectionFileDescriptor};
225
0
    auto connection_result = conn_fd_up->Connect(
226
0
        url,
227
0
        [named_pipe_path, unnamed_pipe](llvm::StringRef socket_id) {
228
          // If we have a named pipe to write the socket id back to, do that
229
          // now.
230
0
          if (named_pipe_path && named_pipe_path[0]) {
231
0
            Status error = writeSocketIdToPipe(named_pipe_path, socket_id);
232
0
            if (error.Fail())
233
0
              llvm::errs() << llvm::formatv(
234
0
                  "failed to write to the named peipe '{0}': {1}\n",
235
0
                  named_pipe_path, error.AsCString());
236
0
          }
237
          // If we have an unnamed pipe to write the socket id back to, do
238
          // that now.
239
0
          else if (unnamed_pipe != LLDB_INVALID_PIPE) {
240
0
            Status error = writeSocketIdToPipe(unnamed_pipe, socket_id);
241
0
            if (error.Fail())
242
0
              llvm::errs() << llvm::formatv(
243
0
                  "failed to write to the unnamed pipe: {0}\n", error);
244
0
          }
245
0
        },
246
0
        &error);
247
248
0
    if (error.Fail()) {
249
0
      llvm::errs() << llvm::formatv(
250
0
          "error: failed to connect to client at '{0}': {1}\n", url, error);
251
0
      exit(-1);
252
0
    }
253
0
    if (connection_result != eConnectionStatusSuccess) {
254
0
      llvm::errs() << llvm::formatv(
255
0
          "error: failed to connect to client at '{0}' "
256
0
          "(connection status: {1})\n",
257
0
          url, static_cast<int>(connection_result));
258
0
      exit(-1);
259
0
    }
260
0
    connection_up = std::move(conn_fd_up);
261
0
  }
262
0
  error = gdb_server.InitializeConnection(std::move(connection_up));
263
0
  if (error.Fail()) {
264
0
    llvm::errs() << llvm::formatv("failed to initialize connection\n", error);
265
0
    exit(-1);
266
0
  }
267
0
  llvm::outs() << "Connection established.\n";
268
0
}
269
270
namespace {
271
enum ID {
272
  OPT_INVALID = 0, // This is not an option ID.
273
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
274
               HELPTEXT, METAVAR, VALUES)                                      \
275
  OPT_##ID,
276
#include "LLGSOptions.inc"
277
#undef OPTION
278
};
279
280
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
281
#include "LLGSOptions.inc"
282
#undef PREFIX
283
284
const opt::OptTable::Info InfoTable[] = {
285
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
286
               HELPTEXT, METAVAR, VALUES)                                      \
287
  {                                                                            \
288
      PREFIX,      NAME,      HELPTEXT,                                        \
289
      METAVAR,     OPT_##ID,  opt::Option::KIND##Class,                        \
290
      PARAM,       FLAGS,     OPT_##GROUP,                                     \
291
      OPT_##ALIAS, ALIASARGS, VALUES},
292
#include "LLGSOptions.inc"
293
#undef OPTION
294
};
295
296
class LLGSOptTable : public opt::OptTable {
297
public:
298
4
  LLGSOptTable() : OptTable(InfoTable) {}
299
300
0
  void PrintHelp(llvm::StringRef Name) {
301
0
    std::string Usage =
302
0
        (Name + " [options] [[host]:port] [[--] program args...]").str();
303
0
    OptTable::printHelp(llvm::outs(), Usage.c_str(), "lldb-server");
304
0
    llvm::outs() << R"(
305
0
DESCRIPTION
306
0
  lldb-server connects to the LLDB client, which drives the debugging session.
307
0
  If no connection options are given, the [host]:port argument must be present
308
0
  and will denote the address that lldb-server will listen on. [host] defaults
309
0
  to "localhost" if empty. Port can be zero, in which case the port number will
310
0
  be chosen dynamically and written to destinations given by --named-pipe and
311
0
  --pipe arguments.
312
0
313
0
  If no target is selected at startup, lldb-server can be directed by the LLDB
314
0
  client to launch or attach to a process.
315
0
316
0
)";
317
0
  }
318
};
319
} // namespace
320
321
4
int main_gdbserver(int argc, char *argv[]) {
322
4
  Status error;
323
4
  MainLoop mainloop;
324
4
#ifndef _WIN32
325
  // Setup signal handlers first thing.
326
4
  signal(SIGPIPE, SIG_IGN);
327
4
  MainLoop::SignalHandleUP sighup_handle =
328
4
      mainloop.RegisterSignal(SIGHUP, sighup_handler, error);
329
4
#endif
330
331
4
  const char *progname = argv[0];
332
4
  const char *subcommand = argv[1];
333
4
  std::string attach_target;
334
4
  std::string named_pipe_path;
335
4
  std::string log_file;
336
4
  StringRef
337
4
      log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
338
4
  lldb::pipe_t unnamed_pipe = LLDB_INVALID_PIPE;
339
4
  bool reverse_connect = false;
340
4
  int connection_fd = -1;
341
342
  // ProcessLaunchInfo launch_info;
343
4
  ProcessAttachInfo attach_info;
344
345
4
  LLGSOptTable Opts;
346
4
  llvm::BumpPtrAllocator Alloc;
347
4
  llvm::StringSaver Saver(Alloc);
348
4
  bool HasError = false;
349
4
  opt::InputArgList Args = Opts.parseArgs(argc - 1, argv + 1, OPT_UNKNOWN,
350
4
                                          Saver, [&](llvm::StringRef Msg) {
351
2
                                            WithColor::error() << Msg << "\n";
352
2
                                            HasError = true;
353
2
                                          });
354
4
  std::string Name =
355
4
      (llvm::sys::path::filename(argv[0]) + " g[dbserver]").str();
356
4
  std::string HelpText =
357
4
      "Use '" + Name + " --help' for a complete list of options.\n";
358
4
  if (HasError) {
359
2
    llvm::errs() << HelpText;
360
2
    return 1;
361
2
  }
362
363
2
  if (Args.hasArg(OPT_help)) {
364
0
    Opts.PrintHelp(Name);
365
0
    return 0;
366
0
  }
367
368
2
#ifndef _WIN32
369
2
  if (Args.hasArg(OPT_setsid)) {
370
    // Put llgs into a new session. Terminals group processes
371
    // into sessions and when a special terminal key sequences
372
    // (like control+c) are typed they can cause signals to go out to
373
    // all processes in a session. Using this --setsid (-S) option
374
    // will cause debugserver to run in its own sessions and be free
375
    // from such issues.
376
    //
377
    // This is useful when llgs is spawned from a command
378
    // line application that uses llgs to do the debugging,
379
    // yet that application doesn't want llgs receiving the
380
    // signals sent to the session (i.e. dying when anyone hits ^C).
381
0
    {
382
0
      const ::pid_t new_sid = setsid();
383
0
      if (new_sid == -1) {
384
0
        WithColor::warning()
385
0
            << llvm::formatv("failed to set new session id for {0} ({1})\n",
386
0
                             LLGS_PROGRAM_NAME, llvm::sys::StrError());
387
0
      }
388
0
    }
389
0
  }
390
2
#endif
391
392
2
  log_file = Args.getLastArgValue(OPT_log_file).str();
393
2
  log_channels = Args.getLastArgValue(OPT_log_channels);
394
2
  named_pipe_path = Args.getLastArgValue(OPT_named_pipe).str();
395
2
  reverse_connect = Args.hasArg(OPT_reverse_connect);
396
2
  attach_target = Args.getLastArgValue(OPT_attach).str();
397
2
  if (Args.hasArg(OPT_pipe)) {
398
0
    uint64_t Arg;
399
0
    if (!llvm::to_integer(Args.getLastArgValue(OPT_pipe), Arg)) {
400
0
      WithColor::error() << "invalid '--pipe' argument\n" << HelpText;
401
0
      return 1;
402
0
    }
403
0
    unnamed_pipe = (pipe_t)Arg;
404
0
  }
405
2
  if (Args.hasArg(OPT_fd)) {
406
1
    if (!llvm::to_integer(Args.getLastArgValue(OPT_fd), connection_fd)) {
407
1
      WithColor::error() << "invalid '--fd' argument\n" << HelpText;
408
1
      return 1;
409
1
    }
410
1
  }
411
412
1
  if (!LLDBServerUtilities::SetupLogging(
413
1
          log_file, log_channels,
414
1
          LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
415
1
              LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION))
416
0
    return -1;
417
418
1
  std::vector<llvm::StringRef> Inputs;
419
1
  for (opt::Arg *Arg : Args.filtered(OPT_INPUT))
420
0
    Inputs.push_back(Arg->getValue());
421
1
  if (opt::Arg *Arg = Args.getLastArg(OPT_REM)) {
422
0
    for (const char *Val : Arg->getValues())
423
0
      Inputs.push_back(Val);
424
0
  }
425
1
  if (Inputs.empty() && connection_fd == -1) {
426
1
    WithColor::error() << "no connection arguments\n" << HelpText;
427
1
    return 1;
428
1
  }
429
430
0
  NativeProcessFactory factory;
431
0
  GDBRemoteCommunicationServerLLGS gdb_server(mainloop, factory);
432
433
0
  llvm::StringRef host_and_port;
434
0
  if (!Inputs.empty()) {
435
0
    host_and_port = Inputs.front();
436
0
    Inputs.erase(Inputs.begin());
437
0
  }
438
439
  // Any arguments left over are for the program that we need to launch. If
440
  // there
441
  // are no arguments, then the GDB server will start up and wait for an 'A'
442
  // packet
443
  // to launch a program, or a vAttach packet to attach to an existing process,
444
  // unless
445
  // explicitly asked to attach with the --attach={pid|program_name} form.
446
0
  if (!attach_target.empty())
447
0
    handle_attach(gdb_server, attach_target);
448
0
  else if (!Inputs.empty())
449
0
    handle_launch(gdb_server, Inputs);
450
451
  // Print version info.
452
0
  printf("%s-%s\n", LLGS_PROGRAM_NAME, LLGS_VERSION_STR);
453
454
0
  ConnectToRemote(mainloop, gdb_server, reverse_connect, host_and_port,
455
0
                  progname, subcommand, named_pipe_path.c_str(),
456
0
                  unnamed_pipe, connection_fd);
457
458
0
  if (!gdb_server.IsConnected()) {
459
0
    fprintf(stderr, "no connection information provided, unable to run\n");
460
0
    return 1;
461
0
  }
462
463
0
  Status ret = mainloop.Run();
464
0
  if (ret.Fail()) {
465
0
    fprintf(stderr, "lldb-server terminating due to error: %s\n",
466
0
            ret.AsCString());
467
0
    return 1;
468
0
  }
469
0
  fprintf(stderr, "lldb-server exiting...\n");
470
471
0
  return 0;
472
0
}