Coverage Report

Created: 2024-07-09 06:09

/proc/self/cwd/pw_tokenizer/decode.cc
Line
Count
Source (jump to first uncovered line)
1
// Copyright 2020 The Pigweed Authors
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4
// use this file except in compliance with the License. You may obtain a copy of
5
// 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, WITHOUT
11
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12
// License for the specific language governing permissions and limitations under
13
// the License.
14
15
#include "pw_tokenizer/internal/decode.h"
16
17
#include <algorithm>
18
#include <array>
19
#include <cctype>
20
#include <cstring>
21
22
#include "pw_varint/varint.h"
23
24
namespace pw::tokenizer {
25
namespace {
26
27
// Functions for parsing a printf format specifier.
28
0
size_t SkipFlags(const char* str) {
29
0
  size_t i = 0;
30
0
  while (str[i] == '-' || str[i] == '+' || str[i] == '#' || str[i] == ' ' ||
31
0
         str[i] == '0') {
32
0
    i += 1;
33
0
  }
34
0
  return i;
35
0
}
36
37
0
size_t SkipAsteriskOrInteger(const char* str) {
38
0
  if (str[0] == '*') {
39
0
    return 1;
40
0
  }
41
42
0
  size_t i = (str[0] == '-' || str[0] == '+') ? 1 : 0;
43
44
0
  while (std::isdigit(str[i])) {
45
0
    i += 1;
46
0
  }
47
0
  return i;
48
0
}
49
50
0
std::array<char, 2> ReadLengthModifier(const char* str) {
51
  // Check for ll or hh.
52
0
  if (str[0] == str[1] && (str[0] == 'l' || str[0] == 'h')) {
53
0
    return {str[0], str[1]};
54
0
  }
55
0
  if (std::strchr("hljztL", str[0]) != nullptr) {
56
0
    return {str[0]};
57
0
  }
58
0
  return {};
59
0
}
60
61
// Returns the error message that is used in place of a decoded arg when an
62
// error occurs.
63
std::string ErrorMessage(ArgStatus status,
64
                         std::string_view spec,
65
0
                         std::string_view value) {
66
0
  const char* message;
67
0
  if (status.HasError(ArgStatus::kSkipped)) {
68
0
    message = "SKIPPED";
69
0
  } else if (status.HasError(ArgStatus::kMissing)) {
70
0
    message = "MISSING";
71
0
  } else if (status.HasError(ArgStatus::kDecodeError)) {
72
0
    message = "ERROR";
73
0
  } else {
74
0
    message = "INTERNAL ERROR";
75
0
  }
76
77
0
  std::string result(PW_TOKENIZER_ARG_DECODING_ERROR_PREFIX);
78
0
  result.append(spec);
79
0
  result.push_back(' ');
80
0
  result.append(message);
81
82
0
  if (!value.empty()) {
83
0
    result.push_back(' ');
84
0
    result.push_back('(');
85
0
    result.append(value);
86
0
    result.push_back(')');
87
0
  }
88
89
0
  result.append(PW_TOKENIZER_ARG_DECODING_ERROR_SUFFIX);
90
0
  return result;
91
0
}
92
93
}  // namespace
94
95
DecodedArg::DecodedArg(ArgStatus error,
96
                       std::string_view spec,
97
                       size_t raw_size_bytes,
98
                       std::string_view value)
99
    : value_(ErrorMessage(error, spec, value)),
100
      spec_(spec),
101
      raw_data_size_bytes_(raw_size_bytes),
102
0
      status_(error) {}
103
104
13
StringSegment StringSegment::ParseFormatSpec(const char* format) {
105
13
  if (format[0] != '%' || format[1] == '\0') {
106
13
    return StringSegment();
107
13
  }
108
109
  // Parse the format specifier.
110
0
  size_t i = 1;
111
112
  // Skip the flags.
113
0
  i += SkipFlags(&format[i]);
114
115
  // Skip the field width.
116
0
  i += SkipAsteriskOrInteger(&format[i]);
117
118
  // Skip the precision.
119
0
  if (format[i] == '.') {
120
0
    i += 1;
121
0
    i += SkipAsteriskOrInteger(&format[i]);
122
0
  }
123
124
  // Read the length modifier.
125
0
  const std::array<char, 2> length = ReadLengthModifier(&format[i]);
126
0
  i += (length[0] == '\0' ? 0 : 1) + (length[1] == '\0' ? 0 : 1);
127
128
  // Read the conversion specifier.
129
0
  const char spec = format[i];
130
131
0
  Type type;
132
0
  if (spec == 's') {
133
0
    type = kString;
134
0
  } else if (spec == 'c' || spec == 'd' || spec == 'i') {
135
0
    type = kSignedInt;
136
0
  } else if (std::strchr("oxXup", spec) != nullptr) {
137
    // The source size matters for unsigned integers because they need to be
138
    // masked off to their correct length, since zig-zag decode sign extends.
139
    // TODO(hepler): 64-bit targets likely have 64-bit l, j, z, and t. Also, p
140
    // needs to be 64-bit on these targets.
141
0
    type = length[0] == 'j' || length[1] == 'l' ? kUnsigned64 : kUnsigned32;
142
0
  } else if (std::strchr("fFeEaAgG", spec) != nullptr) {
143
0
    type = kFloatingPoint;
144
0
  } else if (spec == '%' && i == 1) {
145
0
    type = kPercent;
146
0
  } else {
147
0
    return StringSegment();
148
0
  }
149
150
0
  return {std::string_view(format, i + 1), type, VarargSize(length, spec)};
151
0
}
152
153
StringSegment::ArgSize StringSegment::VarargSize(std::array<char, 2> length,
154
0
                                                 char spec) {
155
  // Use pointer size for %p or any other type (for which this doesn't matter).
156
0
  if (std::strchr("cdioxXu", spec) == nullptr) {
157
0
    return VarargSize<void*>();
158
0
  }
159
0
  if (length[0] == 'l') {
160
0
    return length[1] == 'l' ? VarargSize<long long>() : VarargSize<long>();
161
0
  }
162
0
  if (length[0] == 'j') {
163
0
    return VarargSize<intmax_t>();
164
0
  }
165
0
  if (length[0] == 'z') {
166
0
    return VarargSize<size_t>();
167
0
  }
168
0
  if (length[0] == 't') {
169
0
    return VarargSize<ptrdiff_t>();
170
0
  }
171
0
  return VarargSize<int>();
172
0
}
173
174
DecodedArg StringSegment::DecodeString(
175
0
    const span<const uint8_t>& arguments) const {
176
0
  if (arguments.empty()) {
177
0
    return DecodedArg(ArgStatus::kMissing, text_);
178
0
  }
179
180
0
  ArgStatus status =
181
0
      (arguments[0] & 0x80u) == 0u ? ArgStatus::kOk : ArgStatus::kTruncated;
182
183
0
  const uint_fast8_t size = arguments[0] & 0x7Fu;
184
185
0
  if (arguments.size() - 1 < size) {
186
0
    status.Update(ArgStatus::kDecodeError);
187
0
    span<const uint8_t> arg_val = arguments.subspan(1);
188
0
    return DecodedArg(
189
0
        status,
190
0
        text_,
191
0
        arguments.size(),
192
0
        {reinterpret_cast<const char*>(arg_val.data()), arg_val.size()});
193
0
  }
194
195
0
  std::string value(reinterpret_cast<const char*>(arguments.data() + 1), size);
196
197
0
  if (status.HasError(ArgStatus::kTruncated)) {
198
0
    value.append("[...]");
199
0
  }
200
201
0
  return DecodedArg::FromValue(text_.c_str(), value.c_str(), 1 + size, status);
202
0
}
203
204
DecodedArg StringSegment::DecodeInteger(
205
0
    const span<const uint8_t>& arguments) const {
206
0
  if (arguments.empty()) {
207
0
    return DecodedArg(ArgStatus::kMissing, text_);
208
0
  }
209
210
0
  int64_t value;
211
0
  const size_t bytes = varint::Decode(as_bytes(arguments), &value);
212
213
0
  if (bytes == 0u) {
214
0
    return DecodedArg(ArgStatus::kDecodeError,
215
0
                      text_,
216
0
                      std::min(varint::kMaxVarint64SizeBytes,
217
0
                               static_cast<size_t>(arguments.size())));
218
0
  }
219
220
  // Unsigned ints need to be masked to their bit width due to sign extension.
221
0
  if (type_ == kUnsigned32) {
222
0
    value &= 0xFFFFFFFFu;
223
0
  }
224
225
0
  if (local_size_ == k32Bit) {
226
0
    return DecodedArg::FromValue(
227
0
        text_.c_str(), static_cast<uint32_t>(value), bytes);
228
0
  }
229
0
  return DecodedArg::FromValue(text_.c_str(), value, bytes);
230
0
}
231
232
DecodedArg StringSegment::DecodeFloatingPoint(
233
0
    const span<const uint8_t>& arguments) const {
234
0
  static_assert(sizeof(float) == 4u);
235
0
  if (arguments.size() < sizeof(float)) {
236
0
    return DecodedArg(ArgStatus::kMissing, text_);
237
0
  }
238
239
0
  float value;
240
0
  std::memcpy(&value, arguments.data(), sizeof(value));
241
0
  return DecodedArg::FromValue(text_.c_str(), value, sizeof(value));
242
0
}
243
244
1.87k
DecodedArg StringSegment::Decode(const span<const uint8_t>& arguments) const {
245
1.87k
  switch (type_) {
246
1.87k
    case kLiteral:
247
1.87k
      return DecodedArg(text_);
248
0
    case kPercent:
249
0
      return DecodedArg("%");
250
0
    case kString:
251
0
      return DecodeString(arguments);
252
0
    case kSignedInt:
253
0
    case kUnsigned32:
254
0
    case kUnsigned64:
255
0
      return DecodeInteger(arguments);
256
0
    case kFloatingPoint:
257
0
      return DecodeFloatingPoint(arguments);
258
1.87k
  }
259
260
0
  return DecodedArg(ArgStatus::kDecodeError, text_);
261
1.87k
}
262
263
0
DecodedArg StringSegment::Skip() const {
264
0
  switch (type_) {
265
0
    case kLiteral:
266
0
      return DecodedArg(text_);
267
0
    case kPercent:
268
0
      return DecodedArg("%");
269
0
    case kString:
270
0
    case kSignedInt:
271
0
    case kUnsigned32:
272
0
    case kUnsigned64:
273
0
    case kFloatingPoint:
274
0
    default:
275
0
      return DecodedArg(ArgStatus::kSkipped, text_);
276
0
  }
277
0
}
278
279
0
std::string DecodedFormatString::value() const {
280
0
  std::string output;
281
282
0
  for (const DecodedArg& arg : segments_) {
283
0
    output.append(arg.ok() ? arg.value() : arg.spec());
284
0
  }
285
286
0
  return output;
287
0
}
288
289
0
std::string DecodedFormatString::value_with_errors() const {
290
0
  std::string output;
291
292
0
  for (const DecodedArg& arg : segments_) {
293
0
    output.append(arg.value());
294
0
  }
295
296
0
  return output;
297
0
}
298
299
0
size_t DecodedFormatString::argument_count() const {
300
0
  return std::count_if(segments_.begin(), segments_.end(), [](const auto& arg) {
301
0
    return !arg.spec().empty();
302
0
  });
303
0
}
304
305
0
size_t DecodedFormatString::decoding_errors() const {
306
0
  return std::count_if(segments_.begin(), segments_.end(), [](const auto& arg) {
307
0
    return !arg.ok();
308
0
  });
309
0
}
310
311
4
FormatString::FormatString(const char* format) {
312
4
  const char* text_start = format;
313
314
17
  while (format[0] != '\0') {
315
13
    if (StringSegment spec = StringSegment::ParseFormatSpec(format);
316
13
        !spec.empty()) {
317
      // Add the text segment seen so far (if any).
318
0
      if (text_start < format) {
319
0
        segments_.emplace_back(
320
0
            std::string_view(text_start, format - text_start));
321
0
      }
322
323
      // Move along the index and text segment start.
324
0
      format += spec.text().size();
325
0
      text_start = format;
326
327
      // Add the format specifier that was just found.
328
0
      segments_.push_back(std::move(spec));
329
13
    } else {
330
13
      format += 1;
331
13
    }
332
13
  }
333
334
4
  if (text_start < format) {
335
4
    segments_.emplace_back(std::string_view(text_start, format - text_start));
336
4
  }
337
4
}
338
339
1.87k
DecodedFormatString FormatString::Format(span<const uint8_t> arguments) const {
340
1.87k
  std::vector<DecodedArg> results;
341
1.87k
  bool skip = false;
342
343
1.87k
  for (const auto& segment : segments_) {
344
1.87k
    if (skip) {
345
0
      results.push_back(segment.Skip());
346
1.87k
    } else {
347
1.87k
      results.push_back(segment.Decode(arguments));
348
1.87k
      arguments = arguments.subspan(results.back().raw_size_bytes());
349
350
      // If an error occurred, skip decoding the remaining arguments.
351
1.87k
      if (!results.back().ok()) {
352
0
        skip = true;
353
0
      }
354
1.87k
    }
355
1.87k
  }
356
357
1.87k
  return DecodedFormatString(std::move(results), arguments.size());
358
1.87k
}
359
360
}  // namespace pw::tokenizer