1 # Copyright 2020 The Pigweed Authors
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
7 # https://www.apache.org/licenses/LICENSE-2.0
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
14 """Decodes arguments and formats tokenized messages.
16 The decode(format_string, encoded_arguments) function provides a simple way to
17 format a string with encoded arguments. The FormatString class may also be used.
19 Missing, truncated, or otherwise corrupted arguments are handled and displayed
20 in the resulting string with an error message.
25 from typing import Iterable, List, NamedTuple, Match, Sequence, Tuple
28 def zigzag_decode(value: int) -> int:
29 """ZigZag decode function from protobuf's wire_format module."""
32 return (value >> 1) ^ (~0)
36 """Represents a format specifier parsed from a printf-style string."""
38 # Regular expression for finding format specifiers.
39 FORMAT_SPEC = re.compile(r'%(?:(?P<flags>[+\- #0]*\d*(?:\.\d+)?)'
40 r'(?P<length>hh|h|ll|l|j|z|t|L)?'
41 r'(?P<type>[csdioxXufFeEaAgGnp])|%)')
43 # Conversions to make format strings Python compatible.
44 _UNSUPPORTED_LENGTH = frozenset(['hh', 'll', 'j', 'z', 't'])
45 _REMAP_TYPE = {'a': 'f', 'A': 'F'}
47 # Conversion specifiers by type; n is not supported.
49 _UNSIGNED_INT = frozenset('oxXup')
50 _FLOATING_POINT = frozenset('fFeEaAgG')
52 _PACKED_FLOAT = struct.Struct('<f')
55 def from_string(cls, format_specifier: str):
56 """Creates a FormatSpec from a str with a single format specifier."""
57 match = cls.FORMAT_SPEC.fullmatch(format_specifier)
61 '{!r} is not a valid single format specifier'.format(
66 def __init__(self, re_match: Match):
67 """Constructs a FormatSpec from an re.Match object for FORMAT_SPEC."""
69 self.specifier: str = self.match.group()
71 self.flags: str = self.match.group('flags') or ''
72 self.length: str = self.match.group('length') or ''
74 # If there is no type, the format spec is %%.
75 self.type: str = self.match.group('type') or '%'
77 # %p prints as 0xFEEDBEEF; other specs may need length/type switched
79 self.compatible = '0x%08X'
81 self.compatible = ''.join([
83 '' if self.length in self._UNSUPPORTED_LENGTH else '',
84 self._REMAP_TYPE.get(self.type, self.type)
87 def decode(self, encoded_arg: bytes) -> 'DecodedArg':
88 """Decodes the provided data according to this format specifier."""
89 if self.type == '%': # literal %
90 return DecodedArg(self, (),
91 b'') # Use () as the value for % formatting.
93 if self.type == 's': # string
94 return self._decode_string(encoded_arg)
96 if self.type == 'c': # character
97 return self._decode_char(encoded_arg)
99 if self.type in self._SIGNED_INT:
100 return self._decode_signed_integer(encoded_arg)
102 if self.type in self._UNSIGNED_INT:
103 return self._decode_unsigned_integer(encoded_arg)
105 if self.type in self._FLOATING_POINT:
106 return self._decode_float(encoded_arg)
108 # Unsupported specifier (e.g. %n)
110 self, None, b'', DecodedArg.DECODE_ERROR,
111 'Unsupported conversion specifier "{}"'.format(self.type))
113 def _decode_signed_integer(self, encoded: bytes) -> 'DecodedArg':
114 """Decodes a signed variable-length integer."""
116 return DecodedArg.missing(self)
124 result |= (byte & 0x7f) << shift
127 return DecodedArg(self, zigzag_decode(result), encoded[:count])
133 return DecodedArg(self, None, encoded[:count], DecodedArg.DECODE_ERROR,
134 'Unterminated variable-length integer')
136 def _decode_unsigned_integer(self, encoded: bytes) -> 'DecodedArg':
137 arg = self._decode_signed_integer(encoded)
139 # Since ZigZag encoding is used, unsigned integers must be masked off to
140 # their original bit length.
141 if arg.value is not None:
142 arg.value &= (1 << self.size_bits()) - 1
146 def _decode_float(self, encoded: bytes) -> 'DecodedArg':
148 return DecodedArg.missing(self)
150 return DecodedArg(self,
151 self._PACKED_FLOAT.unpack_from(encoded)[0],
154 def _decode_string(self, encoded: bytes) -> 'DecodedArg':
155 """Reads a unicode string from the encoded data."""
157 return DecodedArg.missing(self)
159 size_and_status = encoded[0]
160 status = DecodedArg.OK
162 if size_and_status & 0x80:
163 status |= DecodedArg.TRUNCATED
164 size_and_status &= 0x7f
166 raw_data = encoded[0:size_and_status + 1]
169 if len(data) < size_and_status:
170 status |= DecodedArg.DECODE_ERROR
173 decoded = data.decode()
174 except UnicodeDecodeError as err:
175 return DecodedArg(self,
176 repr(bytes(data)).lstrip('b'), raw_data,
177 status | DecodedArg.DECODE_ERROR, err)
179 return DecodedArg(self, decoded, raw_data, status)
181 def _decode_char(self, encoded: bytes) -> 'DecodedArg':
182 """Reads an integer from the data, then converts it to a string."""
183 arg = self._decode_signed_integer(encoded)
187 arg.value = chr(arg.value)
188 except (OverflowError, ValueError) as err:
190 arg.status |= DecodedArg.DECODE_ERROR
194 def size_bits(self) -> int:
195 """Size of the argument in bits; 0 for strings."""
199 # TODO(hepler): 64-bit targets likely have 64-bit l, j, z, and t.
200 return 64 if self.length in ['ll', 'j'] else 32
202 def __str__(self) -> str:
203 return self.specifier
207 """Represents a decoded argument that is ready to be formatted."""
209 # Status flags for a decoded argument. These values should match the
210 # DecodingStatus enum in pw_tokenizer/internal/decode.h.
211 OK = 0 # decoding was successful
212 MISSING = 1 # the argument was not present in the data
213 TRUNCATED = 2 # the argument was truncated during encoding
214 DECODE_ERROR = 4 # an error occurred while decoding the argument
215 SKIPPED = 8 # argument was skipped due to a previous error
218 def missing(cls, specifier: FormatSpec):
219 return cls(specifier, None, b'', cls.MISSING)
222 specifier: FormatSpec,
227 self.specifier = specifier # FormatSpec (e.g. to represent "%0.2f")
228 self.value = value # the decoded value, or None if decoding failed
229 self.raw_data = bytes(
230 raw_data) # the exact bytes used to decode this arg
231 self._status = status
234 def ok(self) -> bool:
235 """The argument was decoded without errors."""
236 return self.status == self.OK or self.status == self.TRUNCATED
239 def status(self) -> int:
243 def status(self, status: int):
244 # The %% specifier is always OK and should always be printed normally.
245 self._status = status if self.specifier.type != '%' else self.OK
247 def format(self) -> str:
248 """Returns formatted version of this argument, with error handling."""
249 if self.status == self.TRUNCATED:
250 return self.specifier.compatible % (self.value + '[...]')
254 return self.specifier.compatible % self.value
255 except (OverflowError, TypeError, ValueError) as err:
256 self.status |= self.DECODE_ERROR
259 if self.status & self.SKIPPED:
260 message = '{} SKIPPED'.format(self.specifier)
261 elif self.status == self.MISSING:
262 message = '{} MISSING'.format(self.specifier)
263 elif self.status & self.DECODE_ERROR:
264 message = '{} ERROR'.format(self.specifier)
266 raise AssertionError('Unhandled DecodedArg status {:x}!'.format(
269 if self.value is None or not str(self.value):
270 return '<[{}]>'.format(message)
272 return '<[{} ({})]>'.format(message, self.value)
274 def __str__(self) -> str:
277 def __repr__(self) -> str:
278 return 'DecodedArg({!r})'.format(self)
281 def parse_format_specifiers(format_string: str) -> Iterable[FormatSpec]:
282 for spec in FormatSpec.FORMAT_SPEC.finditer(format_string):
283 yield FormatSpec(spec)
286 class FormattedString(NamedTuple):
288 args: Sequence[DecodedArg]
293 """Represents a printf-style format string."""
294 def __init__(self, format_string: str):
295 """Parses format specifiers in the format string."""
296 self.format_string = format_string
297 self.specifiers = tuple(parse_format_specifiers(self.format_string))
299 # List of non-specifier string pieces with room for formatted arguments.
300 self._segments = self._parse_string_segments()
302 def _parse_string_segments(self) -> List:
303 """Splits the format string by format specifiers."""
304 if not self.specifiers:
305 return [self.format_string]
307 spec_spans = [spec.match.span() for spec in self.specifiers]
309 # Start with the part of the format string up to the first specifier.
310 string_pieces = [self.format_string[:spec_spans[0][0]]]
312 for ((_, end1), (start2, _)) in zip(spec_spans[:-1], spec_spans[1:]):
313 string_pieces.append(self.format_string[end1:start2])
315 # Append the format string segment after the last format specifier.
316 string_pieces.append(self.format_string[spec_spans[-1][1]:])
318 # Make a list with spots for the replacements between the string pieces.
319 segments: List = [None] * (len(string_pieces) + len(self.specifiers))
320 segments[::2] = string_pieces
324 def decode(self, encoded: bytes) -> Tuple[Sequence[DecodedArg], bytes]:
325 """Decodes arguments according to the format string.
328 encoded: bytes; the encoded arguments
331 tuple with the decoded arguments and any unparsed data
338 for spec in self.specifiers:
339 arg = spec.decode(encoded[index:])
342 # After an error is encountered, continue to attempt to parse
343 # arguments, but mark them all as SKIPPED. If an error occurs,
344 # it's impossible to know if subsequent arguments are valid.
345 arg.status |= DecodedArg.SKIPPED
349 decoded_args.append(arg)
350 index += len(arg.raw_data)
352 return tuple(decoded_args), encoded[index:]
356 show_errors: bool = False) -> FormattedString:
357 """Decodes arguments and formats the string with them.
360 encoded_args: the arguments to decode and format the string with
361 show_errors: if True, an error message is used in place of the %
362 conversion specifier when an argument fails to decode
365 tuple with the formatted string, decoded arguments, and remaining data
367 # Insert formatted arguments in place of each format specifier.
368 args, remaining = self.decode(encoded_args)
371 self._segments[1::2] = (arg.format() for arg in args)
373 self._segments[1::2] = (arg.format()
374 if arg.ok() else arg.specifier.specifier
377 return FormattedString(''.join(self._segments), args, remaining)
380 def decode(format_string: str,
381 encoded_arguments: bytes,
382 show_errors: bool = False) -> str:
383 """Decodes arguments and formats them with the provided format string.
386 format_string: the printf-style format string
387 encoded_arguments: encoded arguments with which to format
388 format_string; must exclude the 4-byte string token
389 show_errors: if True, an error message is used in place of the %
390 conversion specifier when an argument fails to decode
393 the printf-style formatted string
395 return FormatString(format_string).format(encoded_arguments,