2 * Copyright (c) 2015-2016 Landon Fuller <landonf@FreeBSD.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer,
10 * without modification.
11 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12 * similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
13 * redistribution must be conditioned upon including a substantially
14 * similar Disclaimer requirement for further binary redistribution.
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
20 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21 * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
22 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
27 * THE POSSIBILITY OF SUCH DAMAGES.
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
33 #include <sys/param.h>
38 #include <sys/ctype.h>
39 #include <sys/kernel.h>
40 #include <sys/malloc.h>
41 #include <sys/systm.h>
43 #include <machine/_inttypes.h>
55 #include "bhnd_nvram_private.h"
56 #include "bhnd_nvram_valuevar.h"
59 #define bhnd_nv_hex2ascii(hex) hex2ascii(hex)
61 static char const bhnd_nv_hex2ascii[] = "0123456789abcdefghijklmnopqrstuvwxyz";
62 #define bhnd_nv_hex2ascii(hex) (bhnd_nv_hex2ascii[hex])
66 * Maximum size, in bytes, of a string-encoded NVRAM integer value, not
67 * including any prefix (0x, 0, etc).
69 * We assume the largest possible encoding is the base-2 representation
70 * of a 64-bit integer.
72 #define NV_NUMSTR_MAX ((sizeof(uint64_t) * CHAR_BIT) + 1)
75 * Format a string representation of @p value using @p fmt, with, writing the
78 * @param value The value to be formatted.
79 * @param fmt The format string.
80 * @param[out] outp On success, the string will be written to this
81 * buffer. This argment may be NULL if the value is
83 * @param[in,out] olen The capacity of @p outp. On success, will be set
84 * to the actual number of bytes required for the
85 * requested string encoding (including a trailing
88 * Refer to bhnd_nvram_val_vprintf() for full format string documentation.
91 * @retval EINVAL If @p fmt contains unrecognized format string
93 * @retval ENOMEM If the @p outp is non-NULL, and the provided @p olen
94 * is too small to hold the encoded value.
95 * @retval EFTYPE If value coercion from @p value to a single string
96 * value via @p fmt is unsupported.
97 * @retval ERANGE If value coercion of @p value would overflow (or
98 * underflow) the representation defined by @p fmt.
101 bhnd_nvram_val_printf(bhnd_nvram_val *value, const char *fmt, char *outp,
108 error = bhnd_nvram_val_vprintf(value, fmt, outp, olen, ap);
116 * Format a string representation of the elements of @p value using @p fmt,
117 * writing the result to @p outp.
119 * @param value The value to be formatted.
120 * @param fmt The format string.
121 * @param[out] outp On success, the string will be written to this
122 * buffer. This argment may be NULL if the value is
124 * @param[in,out] olen The capacity of @p outp. On success, will be set
125 * to the actual number of bytes required for the
126 * requested string encoding (including a trailing
128 * @param ap Argument list.
130 * @par Format Strings
132 * Value format strings are similar, but not identical to, those used
135 * Format specifier format:
136 * %[repeat][flags][width][.precision][length modifier][specifier]
138 * The format specifier is interpreted as an encoding directive for an
139 * individual value element; each format specifier will fetch the next element
140 * from the value, encode the element as the appropriate type based on the
141 * length modifiers and specifier, and then format the result as a string.
143 * For example, given a string value of '0x000F', and a format specifier of
144 * '%#hhx', the value will be asked to encode its first element as
145 * BHND_NVRAM_TYPE_UINT8. String formatting will then be applied to the 8-bit
146 * unsigned integer representation, producing a string value of "0xF".
149 * - [digits] Repeatedly apply the format specifier to the input
150 * value's elements up to `digits` times. The delimiter
151 * must be passed as a string in the next variadic
153 * - [] Repeatedly apply the format specifier to the input
154 * value's elements until all elements have been. The
155 * processed. The delimiter must be passed as a string in
156 * the next variadic argument.
157 * - [*] Repeatedly apply the format specifier to the input
158 * value's elements. The repeat count is read from the
159 * next variadic argument as a size_t value
162 * - '#' use alternative form (e.g. 0x/0X prefixing of hex
165 * - '-' left adjust padding
166 * - '+' include a sign character
167 * - ' ' include a space in place of a sign character for
171 * - digits minimum field width.
172 * - * read the minimum field width from the next variadic
173 * argument as a ssize_t value. A negative value enables
175 * - .digits field precision.
176 * - .* read the field precision from the next variadic argument
177 * as a ssize_t value. A negative value enables left
181 * - 'hh', 'I8' Convert the value to an 8-bit signed or unsigned
183 * - 'h', 'I16' Convert the value to an 16-bit signed or unsigned
185 * - 'l', 'I32' Convert the value to an 32-bit signed or unsigned
187 * - 'll', 'j', 'I64' Convert the value to an 64-bit signed or unsigned
191 * - 'd', 'i' Convert and format as a signed decimal integer.
192 * - 'u' Convert and format as an unsigned decimal integer.
193 * - 'o' Convert and format as an unsigned octal integer.
194 * - 'x' Convert and format as an unsigned hexadecimal integer,
195 * using lowercase hex digits.
196 * - 'X' Convert and format as an unsigned hexadecimal integer,
197 * using uppercase hex digits.
198 * - 's' Convert and format as a string.
199 * - '%' Print a literal '%' character.
202 * @retval EINVAL If @p fmt contains unrecognized format string
204 * @retval ENOMEM If the @p outp is non-NULL, and the provided @p olen
205 * is too small to hold the encoded value.
206 * @retval EFTYPE If value coercion from @p value to a single string
207 * value via @p fmt is unsupported.
208 * @retval ERANGE If value coercion of @p value would overflow (or
209 * underflow) the representation defined by @p fmt.
212 bhnd_nvram_val_vprintf(bhnd_nvram_val *value, const char *fmt, char *outp,
213 size_t *olen, va_list ap)
217 size_t limit, nbytes;
222 /* Determine output byte limit */
229 #define WRITE_CHAR(_c) do { \
230 if (limit > nbytes) \
231 *(outp + nbytes) = _c; \
233 if (nbytes == SIZE_MAX) \
238 /* Encode string value as per the format string */
239 for (const char *p = fmt; *p != '\0'; p++) {
241 size_t precision, width, delim_len;
243 bool alt_form, ladjust, have_precision;
244 char padc, signc, lenc;
255 have_precision = false;
261 /* Copy all input to output until we hit a format specifier */
267 /* Hit '%' -- is this followed by an escaped '%' literal? */
275 /* Parse repeat specifier */
279 /* Determine repeat count */
281 /* Repeat consumes all input */
282 repeat = bhnd_nvram_val_nelem(value);
283 } else if (*p == '*') {
284 /* Repeat is supplied as an argument */
285 repeat = va_arg(ap, size_t);
290 /* Repeat specified as argument */
291 repeat = strtoul(p, &endp, 10);
293 BHND_NV_LOG("error parsing repeat "
298 /* Advance past repeat count */
302 /* Advance past terminating ']' */
304 BHND_NV_LOG("error parsing repeat count at "
310 delim = va_arg(ap, const char *);
311 delim_len = strlen(delim);
333 /* Must not override '+' */
341 /* Non-flag character */
352 /* Parse minimum width */
356 /* Width is supplied as an argument */
357 arg = va_arg(ap, int);
359 /* Negative width argument is interpreted as
360 * '-' flag followed by positive width */
368 } else if (bhnd_nv_isdigit(*p)) {
372 /* Parse width value */
374 error = bhnd_nvram_parse_int(p, strlen(p), 10, &parsed,
375 &v, &len, BHND_NVRAM_TYPE_UINT32);
377 BHND_NV_LOG("error parsing width %s: %d\n", p,
382 /* Save width and advance input */
387 /* Parse precision */
393 have_precision = true;
398 /* Precision is specified as an argument */
399 arg = va_arg(ap, int);
401 /* Negative precision argument is interpreted
402 * as '-' flag followed by positive
410 } else if (!bhnd_nv_isdigit(*p)) {
411 /* Implicit precision of 0 */
414 /* Parse precision value */
416 error = bhnd_nvram_parse_int(p, strlen(p), 10,
418 BHND_NVRAM_TYPE_UINT32);
420 BHND_NV_LOG("error parsing width %s: "
425 /* Save precision and advance input */
431 /* Parse length modifiers */
442 /* Set initial length value */
445 } else if (lenc == *p && bits == 16) {
446 /* Modify previous length value */
449 BHND_NV_LOG("invalid length modifier "
457 /* Set initial length value */
460 } else if (lenc == *p && bits == 32) {
461 /* Modify previous length value */
464 BHND_NV_LOG("invalid length modifier "
471 /* Conflicts with all other length
472 * specifications, and may only occur once */
474 BHND_NV_LOG("invalid length modifier "
486 /* Conflicts with all other length
487 * specifications, and may only occur once */
489 BHND_NV_LOG("invalid length modifier "
496 /* Parse the length specifier value */
498 bits = strtoul(p, &endp, 10);
500 BHND_NV_LOG("invalid size specifier: "
505 /* Advance input past the parsed integer */
510 /* Non-length modifier character */
521 /* Parse conversion specifier and format the value(s) */
522 for (u_long n = 0; n < repeat; n++) {
523 bhnd_nvram_type arg_type;
527 bool is_signed, is_upper;
533 /* Fetch next element */
534 elem = bhnd_nvram_val_next(value, elem, &elen);
536 BHND_NV_LOG("format string references more "
537 "than %zu available value elements\n",
538 bhnd_nvram_val_nelem(value));
543 * If this is not the first value, append the delimiter.
548 nremain = limit - nbytes;
550 if (nremain >= delim_len)
551 memcpy(outp + nbytes, delim, delim_len);
553 /* Add delimiter length to the total byte count */
554 if (SIZE_MAX - nbytes < delim_len)
555 return (EFTYPE); /* overflows size_t */
560 /* Parse integer conversion specifiers */
586 /* Format argument */
588 #define NV_ENCODE_INT(_width) do { \
589 arg_type = (is_signed) ? BHND_NVRAM_TYPE_INT ## _width : \
590 BHND_NVRAM_TYPE_UINT ## _width; \
591 arg_size = sizeof(v.u ## _width); \
592 error = bhnd_nvram_val_encode_elem(value, elem, elen, \
593 &v.u ## _width, &arg_size, arg_type); \
595 BHND_NV_LOG("error encoding argument as %s: %d\n", \
596 bhnd_nvram_type_name(arg_type), error); \
601 if (v.i ## _width < 0) { \
603 numval = (int64_t)-(v.i ## _width); \
605 numval = (int64_t) (v.i ## _width); \
608 numval = v.u ## _width; \
617 char numbuf[NV_NUMSTR_MAX];
635 /* If precision is specified, it overrides
636 * (and behaves identically) to a zero-prefixed
638 if (have_precision) {
644 /* If zero-padding is used, value must be right
649 /* Request encode to the appropriate integer
650 * type, and then promote to common 64-bit
666 BHND_NV_LOG("invalid length specifier: "
672 /* If a precision of 0 is specified and the
673 * value is also zero, no characters should
675 if (have_precision && precision == 0 &&
681 /* Emit string representation to local buffer */
682 BHND_NV_ASSERT(base <= 16, ("invalid base"));
683 sptr = numbuf + nitems(numbuf) - 1;
684 for (slen = 0; slen < sizeof(numbuf); slen++) {
689 c = bhnd_nv_hex2ascii(n);
691 c = bhnd_nv_toupper(c);
696 numval /= (uint64_t)base;
705 /* Reserve space for 0/0x prefix? */
708 /* If 0, no prefix */
710 } else if (base == 8) {
711 arg_size += 1; /* 0 */
712 } else if (base == 16) {
713 arg_size += 2; /* 0x/0X */
717 /* Reserve space for ' ', '+', or '-' prefix? */
718 if (add_neg || signc != '\0') {
725 /* Right adjust (if using spaces) */
726 if (!ladjust && padc != '0') {
727 for (i = arg_size; i < width; i++)
737 } else if (base == 16) {
746 /* Right adjust (if using zeros) */
747 if (!ladjust && padc == '0') {
748 for (i = slen; i < width; i++)
752 /* Write the string to our output buffer */
753 if (limit > nbytes && limit - nbytes >= slen)
754 memcpy(outp + nbytes, sptr, slen);
756 /* Update the total byte count */
757 if (SIZE_MAX - nbytes < arg_size)
758 return (EFTYPE); /* overflows size_t */
763 for (i = arg_size; ladjust && i < width; i++)
773 /* Query the total length of the element when
774 * converted to a string */
775 arg_type = BHND_NVRAM_TYPE_STRING;
776 error = bhnd_nvram_val_encode_elem(value, elem,
777 elen, NULL, &arg_size, arg_type);
779 BHND_NV_LOG("error encoding argument "
781 bhnd_nvram_type_name(arg_type),
786 /* Do not include trailing NUL in the string
792 for (i = arg_size; !ladjust && i < width; i++)
795 /* Determine output positition and remaining
797 if (limit > nbytes) {
799 slen = limit - nbytes;
805 /* Encode the string to our output buffer */
806 error = bhnd_nvram_val_encode_elem(value, elem,
807 elen, s, &slen, arg_type);
808 if (error && error != ENOMEM) {
809 BHND_NV_LOG("error encoding argument "
811 bhnd_nvram_type_name(arg_type),
816 /* Update the total byte count */
817 if (SIZE_MAX - nbytes < arg_size)
818 return (EFTYPE); /* overflows size_t */
823 for (i = arg_size; ladjust && i < width; i++)
832 arg_type = BHND_NVRAM_TYPE_CHAR;
833 arg_size = bhnd_nvram_type_width(arg_type);
835 /* Encode as single character */
836 error = bhnd_nvram_val_encode_elem(value, elem,
837 elen, &c, &arg_size, arg_type);
839 BHND_NV_LOG("error encoding argument "
841 bhnd_nvram_type_name(arg_type),
846 BHND_NV_ASSERT(arg_size == sizeof(c),
847 ("invalid encoded size"));
850 for (i = arg_size; !ladjust && i < width; i++)
856 for (i = arg_size; ladjust && i < width; i++)
865 /* Append terminating NUL */
867 *(outp + nbytes) = '\0';
869 if (nbytes < SIZE_MAX)
874 /* Report required space */
876 if (limit < nbytes) {