xref: /freebsd/contrib/llvm-project/lldb/tools/lldb-server/LLDBServerUtilities.cpp (revision 924226fba12cc9a228c73b956e1b7fa24c60b055)
1 //===-- LLDBServerUtilities.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 "LLDBServerUtilities.h"
10 
11 #include "lldb/Utility/Args.h"
12 #include "lldb/Utility/Log.h"
13 #include "lldb/Utility/StreamString.h"
14 
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/Support/FileSystem.h"
18 
19 using namespace lldb;
20 using namespace lldb_private::lldb_server;
21 using namespace llvm;
22 
23 static std::shared_ptr<raw_ostream> GetLogStream(StringRef log_file) {
24   if (!log_file.empty()) {
25     std::error_code EC;
26     std::shared_ptr<raw_ostream> stream_sp = std::make_shared<raw_fd_ostream>(
27         log_file, EC, sys::fs::OF_TextWithCRLF | sys::fs::OF_Append);
28     if (!EC)
29       return stream_sp;
30     errs() << llvm::formatv(
31         "Failed to open log file `{0}`: {1}\nWill log to stderr instead.\n",
32         log_file, EC.message());
33   }
34   // No need to delete the stderr stream.
35   return std::shared_ptr<raw_ostream>(&errs(), [](raw_ostream *) {});
36 }
37 
38 bool LLDBServerUtilities::SetupLogging(const std::string &log_file,
39                                        const StringRef &log_channels,
40                                        uint32_t log_options) {
41 
42   auto log_stream_sp = GetLogStream(log_file);
43 
44   SmallVector<StringRef, 32> channel_array;
45   log_channels.split(channel_array, ":", /*MaxSplit*/ -1, /*KeepEmpty*/ false);
46   for (auto channel_with_categories : channel_array) {
47     std::string error;
48     llvm::raw_string_ostream error_stream(error);
49     Args channel_then_categories(channel_with_categories);
50     std::string channel(channel_then_categories.GetArgumentAtIndex(0));
51     channel_then_categories.Shift(); // Shift off the channel
52 
53     bool success = Log::EnableLogChannel(
54         log_stream_sp, log_options, channel,
55         channel_then_categories.GetArgumentArrayRef(), error_stream);
56     if (!success) {
57       errs() << formatv("Unable to setup logging for channel \"{0}\": {1}",
58                         channel, error_stream.str());
59       return false;
60     }
61   }
62   return true;
63 }
64