1 //===-- Implementation of a class for mapping signals to strings ----------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "signal_to_string.h"
10 #include "platform_signals.h"
12 #include "src/__support/CPP/span.h"
13 #include "src/__support/CPP/string_view.h"
14 #include "src/__support/CPP/stringstream.h"
15 #include "src/__support/StringUtil/message_mapper.h"
16 #include "src/__support/integer_to_string.h"
17 #include "src/__support/macros/attributes.h"
18 #include "src/__support/macros/config.h"
23 namespace LIBC_NAMESPACE_DECL
{
26 constexpr size_t max_buff_size() {
27 constexpr size_t base_str_len
= sizeof("Real-time signal");
28 // the buffer should be able to hold "Real-time signal" + ' ' + num_str
29 return (base_str_len
+ 1 + IntegerToString
<int>::buffer_size()) *
33 // This is to hold signal strings that have to be custom built. It may be
34 // rewritten on every call to strsignal (or other signal to string function).
35 constexpr size_t SIG_BUFFER_SIZE
= max_buff_size();
36 LIBC_THREAD_LOCAL
char signal_buffer
[SIG_BUFFER_SIZE
];
38 constexpr size_t TOTAL_STR_LEN
= total_str_len(PLATFORM_SIGNALS
);
40 constexpr size_t SIG_ARRAY_SIZE
= max_key_val(PLATFORM_SIGNALS
) + 1;
42 constexpr MessageMapper
<SIG_ARRAY_SIZE
, TOTAL_STR_LEN
>
43 signal_mapper(PLATFORM_SIGNALS
);
45 cpp::string_view
build_signal_string(int sig_num
, cpp::span
<char> buffer
) {
46 cpp::string_view base_str
;
47 if (sig_num
>= SIGRTMIN
&& sig_num
<= SIGRTMAX
) {
48 base_str
= cpp::string_view("Real-time signal");
51 base_str
= cpp::string_view("Unknown signal");
54 // if the buffer can't hold "Unknown signal" + ' ' + num_str, then just
55 // return "Unknown signal".
57 (base_str
.size() + 1 + IntegerToString
<int>::buffer_size()))
60 cpp::StringStream
buffer_stream(
61 {const_cast<char *>(buffer
.data()), buffer
.size()});
62 buffer_stream
<< base_str
<< ' ' << sig_num
<< '\0';
63 return buffer_stream
.str();
66 } // namespace internal
68 cpp::string_view
get_signal_string(int sig_num
) {
69 return get_signal_string(
70 sig_num
, {internal::signal_buffer
, internal::SIG_BUFFER_SIZE
});
73 cpp::string_view
get_signal_string(int sig_num
, cpp::span
<char> buffer
) {
74 auto opt_str
= internal::signal_mapper
.get_str(sig_num
);
78 return internal::build_signal_string(sig_num
, buffer
);
81 } // namespace LIBC_NAMESPACE_DECL