xref: /aosp_15_r20/external/sandboxed-api/sandboxed_api/sandbox2/logsink.cc (revision ec63e07ab9515d95e79c211197c445ef84cefa6a)
1 // Copyright 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "sandboxed_api/sandbox2/logsink.h"
16 
17 #include <unistd.h>
18 
19 #include <csignal>
20 #include <cstdio>
21 #include <string>
22 
23 #include "absl/base/log_severity.h"
24 #include "absl/log/log_entry.h"
25 #include "absl/log/log_sink_registry.h"
26 #include "absl/strings/str_cat.h"
27 #include "absl/strings/str_format.h"
28 #include "absl/synchronization/mutex.h"
29 #include "sandboxed_api/sandbox2/logserver.pb.h"
30 
31 namespace sandbox2 {
32 
33 constexpr char LogSink::kLogFDName[];
34 
LogSink(int fd)35 LogSink::LogSink(int fd) : comms_(fd) { absl::AddLogSink(this); }
36 
~LogSink()37 LogSink::~LogSink() { absl::RemoveLogSink(this); }
38 
Send(const absl::LogEntry & e)39 void LogSink::Send(const absl::LogEntry& e) {
40   absl::MutexLock l(&lock_);
41 
42   LogMessage msg;
43   msg.set_severity(static_cast<int>(e.log_severity()));
44   msg.set_path(std::string(e.source_basename()));
45   msg.set_line(e.source_line());
46   msg.set_message(absl::StrCat(e.text_message(), "\n"));
47   msg.set_pid(getpid());
48 
49   if (!comms_.SendProtoBuf(msg)) {
50     absl::FPrintF(stderr, "sending log message to supervisor failed:\n%s\n",
51                   e.text_message_with_prefix());
52   }
53 
54   if (e.log_severity() == absl::LogSeverity::kFatal) {
55     // Raise a SIGABRT to prevent the remaining code in logging to try to dump a
56     // symbolized stack trace which can lead to syscall violations.
57     kill(0, SIGABRT);
58   }
59 }
60 
61 }  // namespace sandbox2
62