Repository navigation
Expand file tree
/
Copy pathformat_string.cpp
More file actions
383 lines (357 loc) · 12 KB
/
Copy pathformat_string.cpp
File metadata and controls
383 lines (357 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#include <cstring>
#include <iomanip>
#include "format_string.h"
#include "output/output.h"
#include "struct.h"
#include "util/exceptions.h"
#include "util/gfp_flags.h"
#include "util/strings.h"
namespace bpftrace {
using namespace output;
char FormatError::ID;
void FormatError::log(llvm::raw_ostream& OS) const
{
OS << msg_;
}
// N.B. the `gr`, `r`, `rh` and `rx` specifiers are non-standard and also have
// modifiers that *follow* the primary specifier. This means that they need
// special cases, and the ordering matters to ensure that we capture the
// modifiers if they are present (so `r` is the final match in the list).
// The %gr specifier for GFP flag type in human-readable format.
const std::regex FormatSpec::regex(
R"(%(-?)(\+?)( ?)(#?)(0?)(\*|\d+)?(?:\.(\*|\d+))?([hlLjzt]*)([diouxXeEfFGaAcspn%]|gr|g|rh|rx|r))");
FormatSpec::FormatSpec(const std::smatch& match)
{
left_align = !match[1].str().empty();
show_sign = !match[2].str().empty();
space_prefix = !match[3].str().empty();
alternate_form = !match[4].str().empty();
lead_zeros = !match[5].str().empty();
if (!match[6].str().empty() && match[6].str() != "*") {
width = std::stoi(match[6].str());
}
if (!match[7].str().empty() && match[7].str() != "*") {
precision = std::stoi(match[7].str());
}
length_modifier = match[8].str();
specifier = match[9].str();
}
FormatString::FormatString() = default;
FormatString::FormatString(std::string fmt) : fmt_(std::move(fmt))
{
parse();
}
FormatString::~FormatString() = default;
void FormatString::parse()
{
fragments.clear();
specs.clear();
auto begin = std::sregex_iterator(fmt_.begin(),
fmt_.end(),
FormatSpec::regex);
auto end = std::sregex_iterator();
size_t last_match_end = 0;
std::stringstream last_fragment;
for (auto it = begin; it != end; ++it) {
last_fragment << fmt_.substr(last_match_end,
it->position() - last_match_end);
last_match_end = it->position() + it->length();
auto spec = FormatSpec(*it);
if (spec.specifier == "%") {
last_fragment << "%";
continue;
}
fragments.emplace_back(last_fragment.str());
last_fragment.str(""); // Reset the fragment.
specs.emplace_back(std::move(spec));
}
last_fragment << fmt_.substr(last_match_end);
fragments.emplace_back(last_fragment.str());
}
Result<> FormatString::check(const std::vector<SizedType>& args) const
{
std::stringstream err;
if (args.size() < specs.size()) {
err << "not enough arguments for format string (" << args.size()
<< " supplied, " << specs.size() << " expected)";
return make_error<FormatError>(err.str());
}
if (args.size() > specs.size()) {
err << "too many arguments for format string (" << args.size()
<< " supplied, " << specs.size() << " expected)";
return make_error<FormatError>(err.str());
}
// Walk over the arguments and check the most basic type information.
static const std::vector<Type> any_integer = { Type::integer,
Type::boolean,
Type::pointer };
static const std::map<std::string, std::vector<Type>> required_type = {
{ "d", any_integer },
{ "i", any_integer },
{ "u", any_integer },
{ "o", any_integer },
{ "x", any_integer },
{ "X", any_integer },
{ "c", any_integer },
{ "r", { Type::buffer } },
{ "rx", { Type::buffer } },
{ "rh", { Type::buffer } },
{ "s", {} },
{ "p", any_integer },
{ "gr", any_integer },
};
for (size_t i = 0; i < specs.size(); i++) {
if (args[i].IsNoneTy() || args[i].IsVoidTy()) {
err << "unable to print none type for specifier: " << specs[i].specifier;
return make_error<FormatError>(err.str());
}
auto it = required_type.find(specs[i].specifier);
if (it == required_type.end()) {
err << "unsupported format specifier: " << specs[i].specifier;
return make_error<FormatError>(err.str());
}
if (it->second.empty()) {
// Anything goes.
continue;
}
bool found = false;
for (const auto& allowed : it->second) {
if (args[i].GetTy() == allowed) {
found = true;
break;
}
}
if (!found) {
err << "unsupported format specifier for type '" << typestr(args[i])
<< "': " << specs[i].specifier;
return make_error<FormatError>(err.str());
}
}
return OK();
}
template <typename T, typename Cast = T>
Result<> as_number(std::stringstream& ss, const Primitive& p)
{
return std::visit(
[&](const auto& v) -> Result<> {
if constexpr (std::is_same_v<std::decay_t<decltype(v)>,
output::Primitive::Symbolic>) {
return as_number<T, Cast>(ss, output::Primitive(v.numeric));
} else if constexpr (std::is_same_v<std::decay_t<decltype(v)>,
int64_t> ||
std::is_same_v<std::decay_t<decltype(v)>,
uint64_t> ||
std::is_same_v<std::decay_t<decltype(v)>,
double> ||
std::is_same_v<std::decay_t<decltype(v)>, bool>) {
if constexpr (std::is_same_v<T, void*>) {
ss << reinterpret_cast<void*>(static_cast<unsigned long long>(v));
} else {
ss << static_cast<T>(static_cast<Cast>(v));
}
return OK();
} else {
std::stringstream msg;
msg << "invalid integer conversion: " << p;
return make_error<FormatError>(msg.str());
}
},
p.variant);
}
template <typename T = long long, typename Cast = int>
Result<> as_signed_integer(std::stringstream& ss,
const Primitive& p,
const std::string& length_modifier)
{
if (length_modifier == "hh") {
return as_number<T, char>(ss, p);
} else if (length_modifier == "h") {
return as_number<T, short>(ss, p);
} else if (length_modifier == "l") {
return as_number<T, long>(ss, p);
} else if (length_modifier == "ll") {
return as_number<T, long long>(ss, p);
} else if (length_modifier == "j") {
return as_number<T, intmax_t>(ss, p);
} else if (length_modifier == "z") {
return as_number<T, ssize_t>(ss, p);
} else if (length_modifier == "t") {
return as_number<T, ptrdiff_t>(ss, p);
} else {
return as_number<T, Cast>(ss, p);
}
}
template <typename T = unsigned long, typename Cast = unsigned int>
Result<> as_unsigned_integer(std::stringstream& ss,
const Primitive& p,
const std::string& length_modifier)
{
if (length_modifier == "hh") {
return as_number<T, unsigned char>(ss, p);
} else if (length_modifier == "h") {
return as_number<T, unsigned short>(ss, p);
} else if (length_modifier == "l") {
return as_number<T, unsigned long>(ss, p);
} else if (length_modifier == "ll") {
return as_number<T, unsigned long long>(ss, p);
} else if (length_modifier == "j") {
return as_number<T, uintmax_t>(ss, p);
} else if (length_modifier == "z") {
return as_number<T, size_t>(ss, p);
} else if (length_modifier == "t") {
return as_number<T, ptrdiff_t>(ss, p);
} else {
return as_number<T, Cast>(ss, p);
}
}
Result<> as_floating_point(std::stringstream& ss,
const Primitive& p,
const std::string& length_modifier)
{
if (length_modifier == "L") {
return as_number<long double>(ss, p);
} else {
return as_number<double>(ss, p);
}
}
static Result<> as_string(std::stringstream& ss,
const Primitive& p,
[[maybe_unused]] const std::string& length_modifier)
{
ss << p;
return OK();
}
template <bool keep_ascii = true, bool escape_hex = true>
static Result<> as_buffer(std::stringstream& ss,
const Primitive& p,
const std::string& length_modifier)
{
if (std::holds_alternative<Primitive::Buffer>(p.variant)) {
const auto& buf = std::get<Primitive::Buffer>(p.variant);
ss << util::hex_format_buffer(
buf.data.data(), buf.data.size(), keep_ascii, escape_hex);
return OK();
} else {
return as_string(ss, p, length_modifier);
}
}
static Result<> as_gfp_flags(
std::stringstream& ss,
const Primitive& p,
[[maybe_unused]] const std::string& length_modifier)
{
return std::visit(
[&](const auto& v) -> Result<> {
if constexpr (std::is_same_v<std::decay_t<decltype(v)>,
output::Primitive::Symbolic>) {
return as_gfp_flags(ss,
output::Primitive(v.numeric),
length_modifier);
} else if constexpr (std::is_same_v<std::decay_t<decltype(v)>,
int64_t> ||
std::is_same_v<std::decay_t<decltype(v)>,
uint64_t>) {
ss << util::GFPFlags::format(static_cast<uint64_t>(v));
return OK();
} else {
std::stringstream msg;
msg << "invalid GFP flags conversion: " << p;
return make_error<FormatError>(msg.str());
}
},
p.variant);
}
Result<std::string> FormatSpec::apply(const Primitive& p) const
{
std::stringstream ss;
if (left_align) {
ss << std::left;
} else {
ss << std::right;
}
if (width > 0) {
ss << std::setw(width);
}
if (lead_zeros) {
ss << std::setfill('0');
}
if (precision >= 0 &&
(specifier == "f" || specifier == "F" || specifier == "e" ||
specifier == "E" || specifier == "g" || specifier == "G" ||
specifier == "a" || specifier == "A")) {
ss << std::setprecision(precision);
if (specifier == "f" || specifier == "F") {
ss << std::fixed;
} else if (specifier == "e" || specifier == "E") {
ss << std::scientific;
}
}
if (specifier == "o") {
ss << std::oct;
} else if (specifier == "x") {
ss << std::hex << std::nouppercase;
} else if (specifier == "X") {
ss << std::hex << std::uppercase;
}
if (alternate_form) {
ss << std::showbase;
}
if (show_sign) {
ss << std::showpos;
}
using SpecifierHandler = Result<> (*)(std::stringstream&,
const Primitive&,
const std::string&);
static const std::map<std::string, SpecifierHandler> specifier_dispatch = {
{ "d", as_signed_integer },
{ "i", as_signed_integer },
{ "u", as_unsigned_integer },
{ "o", as_unsigned_integer },
{ "x", as_unsigned_integer },
{ "X", as_unsigned_integer },
{ "f", as_floating_point },
{ "F", as_floating_point },
{ "e", as_floating_point },
{ "E", as_floating_point },
{ "g", as_floating_point },
{ "G", as_floating_point },
{ "a", as_floating_point },
{ "A", as_floating_point },
{ "c", as_signed_integer<char> },
{ "r", as_buffer },
{ "rx", as_buffer<false> },
{ "rh", as_buffer<false, false> },
{ "s", as_string },
{ "p", as_unsigned_integer<void*> },
{ "gr", as_gfp_flags },
};
auto* dispatcher = as_string; // Default.
auto it = specifier_dispatch.find(specifier);
if (it != specifier_dispatch.end()) {
dispatcher = it->second;
}
auto ok = dispatcher(ss, p, length_modifier);
if (!ok) {
return ok.takeError();
}
return ss.str();
}
std::string FormatString::format(const std::vector<Primitive>& args) const
{
std::stringstream ss;
for (size_t i = 0; i < args.size(); i++) {
ss << fragments[i];
auto s = specs[i].apply(args[i]);
if (s) {
// Write the formatted string.
ss << *s;
} else {
// Nothing has been written, so just embed the error into the string here.
// This is what happens in `Go` when a value cannot be formatted properly.
ss << "!{" << s.takeError() << "}";
}
}
ss << fragments.back();
return ss.str();
}
} // namespace bpftrace