Home | History | Annotate | Line # | Download | only in libutil
      1 /*	$NetBSD: snprintb.c,v 1.50 2025/10/09 18:51:41 rillig Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2002, 2024 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     18  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     26  * POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 #ifndef _STANDALONE
     30 # ifndef _KERNEL
     31 
     32 #  if HAVE_NBTOOL_CONFIG_H
     33 #   include "nbtool_config.h"
     34 #  endif
     35 
     36 #  include <sys/cdefs.h>
     37 #  if defined(LIBC_SCCS)
     38 __RCSID("$NetBSD: snprintb.c,v 1.50 2025/10/09 18:51:41 rillig Exp $");
     39 #  endif
     40 
     41 #  include <sys/types.h>
     42 #  include <inttypes.h>
     43 #  include <stdio.h>
     44 #  include <string.h>
     45 #  include <util.h>
     46 #  include <errno.h>
     47 # else /* ! _KERNEL */
     48 #  include <sys/cdefs.h>
     49 __KERNEL_RCSID(0, "$NetBSD: snprintb.c,v 1.50 2025/10/09 18:51:41 rillig Exp $");
     50 #  include <sys/param.h>
     51 #  include <sys/inttypes.h>
     52 #  include <sys/systm.h>
     53 #  include <lib/libkern/libkern.h>
     54 # endif /* ! _KERNEL */
     55 
     56 # ifndef HAVE_SNPRINTB_M
     57 typedef struct {
     58 	char *const buf;
     59 	size_t const bufsize;
     60 	const char *bitfmt;
     61 	uint64_t const val;
     62 	size_t const line_max;
     63 
     64 	char num_fmt[5];
     65 	size_t total_len;
     66 	size_t line_pos;
     67 	size_t comma_pos;
     68 	int in_angle_brackets;
     69 } state;
     70 
     71 static int
     72 is_ident(char c)
     73 {
     74 	return ('0' <= c && c <= '9')
     75 	    || ('A' <= c && c <= 'Z')
     76 	    || ('a' <= c && c <= 'z')
     77 	    || c == '_';
     78 }
     79 
     80 static void
     81 store(state *s, char c)
     82 {
     83 	if (s->total_len < s->bufsize)
     84 		s->buf[s->total_len] = c;
     85 	s->total_len++;
     86 }
     87 
     88 static int
     89 store_num(state *s, const char *fmt, uintmax_t num)
     90 {
     91 	int num_len = s->total_len < s->bufsize
     92 	    ? snprintf(s->buf + s->total_len, s->bufsize - s->total_len,
     93 		fmt, num)
     94 	    : snprintf(NULL, 0, fmt, num);
     95 	if (num_len > 0)
     96 		s->total_len += num_len;
     97 	return num_len;
     98 }
     99 
    100 static void
    101 store_eol(state *s)
    102 {
    103 	if (s->total_len - s->line_pos > s->line_max) {
    104 		s->total_len = s->line_pos + s->line_max - 1;
    105 		store(s, '#');
    106 	}
    107 	store(s, '\0');
    108 	s->line_pos = s->total_len;
    109 	s->comma_pos = 0;
    110 	s->in_angle_brackets = 0;
    111 }
    112 
    113 static void
    114 store_delimiter(state *s)
    115 {
    116 	if (s->in_angle_brackets) {
    117 		s->comma_pos = s->total_len;
    118 		store(s, ',');
    119 	} else {
    120 		store(s, '<');
    121 		s->in_angle_brackets = 1;
    122 	}
    123 }
    124 
    125 static void
    126 maybe_wrap_line(state *s, const char *bitfmt)
    127 {
    128 	if (s->line_max > 0
    129 	    && s->comma_pos > 0
    130 	    && s->total_len - s->line_pos >= s->line_max) {
    131 		s->total_len = s->comma_pos;
    132 		store(s, '>');
    133 		store_eol(s);
    134 		store_num(s, s->num_fmt, s->val);
    135 		s->bitfmt = bitfmt;
    136 	}
    137 }
    138 
    139 static int
    140 old_style(state *s)
    141 {
    142 	while (*s->bitfmt != '\0') {
    143 		const char *cur_bitfmt = s->bitfmt;
    144 		uint8_t bit = *s->bitfmt;
    145 		if (bit > 32)
    146 			return -1;
    147 		if ((uint8_t)cur_bitfmt[1] <= 32)
    148 			return -1;
    149 		if (s->val & (1U << (bit - 1))) {
    150 			store_delimiter(s);
    151 			while ((uint8_t)*++s->bitfmt > 32)
    152 				store(s, *s->bitfmt);
    153 			maybe_wrap_line(s, cur_bitfmt);
    154 		} else
    155 			while ((uint8_t)*++s->bitfmt > 32)
    156 				continue;
    157 	}
    158 	return 0;
    159 }
    160 
    161 static int
    162 new_style(state *s)
    163 {
    164 	uint8_t field_kind = 0;	// 0 or 'f' or 'F'
    165 	uint64_t field = 0;	// valid if field_kind != '\0'
    166 	int matched = 1;
    167 	const char *prev_bitfmt = s->bitfmt;
    168 	while (*s->bitfmt != '\0') {
    169 		const char *cur_bitfmt = s->bitfmt;
    170 		uint8_t kind = cur_bitfmt[0];
    171 		switch (kind) {
    172 		case 'b':
    173 			field_kind = 0;
    174 			prev_bitfmt = cur_bitfmt;
    175 			uint8_t b_bit = cur_bitfmt[1];
    176 			if (b_bit >= 64)
    177 				return -1;
    178 			if (cur_bitfmt[2] == '\0')
    179 				return -1;
    180 			s->bitfmt += 2;
    181 			if (((s->val >> b_bit) & 1) == 0)
    182 				goto skip_description;
    183 			store_delimiter(s);
    184 			while (*s->bitfmt++ != '\0')
    185 				store(s, s->bitfmt[-1]);
    186 			maybe_wrap_line(s, cur_bitfmt);
    187 			break;
    188 		case 'f':
    189 		case 'F':
    190 			field_kind = kind;
    191 			prev_bitfmt = cur_bitfmt;
    192 			matched = 0;
    193 			uint8_t f_lsb = cur_bitfmt[1];
    194 			if (f_lsb >= 64)
    195 				return -1;
    196 			uint8_t f_width = cur_bitfmt[2];
    197 			if (f_width > 64)
    198 				return -1;
    199 			if (kind == 'f' && cur_bitfmt[3] == '\0')
    200 				return -1;
    201 			field = s->val >> f_lsb;
    202 			if (f_width < 64)
    203 				field &= ((uint64_t) 1 << f_width) - 1;
    204 			s->bitfmt += 3;
    205 			store_delimiter(s);
    206 			if (kind == 'F')
    207 				goto skip_description;
    208 			while (*s->bitfmt++ != '\0')
    209 				store(s, s->bitfmt[-1]);
    210 			store(s, '=');
    211 			store_num(s, s->num_fmt, field);
    212 			maybe_wrap_line(s, cur_bitfmt);
    213 			break;
    214 		case '=':
    215 		case ':':
    216 			s->bitfmt += 2;
    217 			if (kind == '=' && field_kind != 'f')
    218 				return -1;
    219 			if (kind == ':' && field_kind != 'F'
    220 			    && (field_kind != 'f' || is_ident(*s->bitfmt)))
    221 				return -1;
    222 			uint8_t cmp = cur_bitfmt[1];
    223 			if (cur_bitfmt[2] == '\0')
    224 				return -1;
    225 			if (field != cmp)
    226 				goto skip_description;
    227 			matched = 1;
    228 			if (kind == '=')
    229 				store(s, '=');
    230 			while (*s->bitfmt++ != '\0')
    231 				store(s, s->bitfmt[-1]);
    232 			maybe_wrap_line(s, prev_bitfmt);
    233 			break;
    234 		case '*':
    235 			if (field_kind == 0)
    236 				return -1;
    237 			field_kind = 0;
    238 			if (cur_bitfmt[1] == '\0')
    239 				return -1;
    240 			s->bitfmt++;
    241 			if (matched)
    242 				goto skip_description;
    243 			matched = 1;
    244 			if (store_num(s, s->bitfmt, field) < 0)
    245 				return -1;
    246 			maybe_wrap_line(s, prev_bitfmt);
    247 			goto skip_description;
    248 		default:
    249 			return -1;
    250 		skip_description:
    251 			while (*s->bitfmt++ != '\0')
    252 				continue;
    253 			break;
    254 		}
    255 	}
    256 	return 0;
    257 }
    258 
    259 static void
    260 finish_buffer(state *s)
    261 {
    262 	if (s->line_max > 0) {
    263 		store_eol(s);
    264 		store(s, '\0');
    265 		if (s->total_len <= s->bufsize)
    266 			return;
    267 		if (s->bufsize >= 3)
    268 			s->buf[s->bufsize - 3] = '#';
    269 		if (s->bufsize >= 2)
    270 			s->buf[s->bufsize - 2] = '\0';
    271 		if (s->bufsize >= 1)
    272 			s->buf[s->bufsize - 1] = '\0';
    273 	} else {
    274 		store(s, '\0');
    275 		if (s->total_len <= s->bufsize)
    276 			return;
    277 		if (s->bufsize >= 2)
    278 			s->buf[s->bufsize - 2] = '#';
    279 		if (s->bufsize >= 1)
    280 			s->buf[s->bufsize - 1] = '\0';
    281 	}
    282 }
    283 
    284 int
    285 snprintb_m(char *buf, size_t bufsize, const char *bitfmt, uint64_t val,
    286 	   size_t line_max)
    287 {
    288 	int old = *bitfmt != '\177';
    289 	if (!old)
    290 		bitfmt++;
    291 
    292 	state s = {
    293 		.buf = buf,
    294 		.bufsize = bufsize,
    295 		.bitfmt = bitfmt,
    296 		.val = val,
    297 		.line_max = line_max,
    298 	};
    299 	int had_error = 0;
    300 
    301 	switch (*s.bitfmt++) {
    302 	case 8:
    303 		memcpy(s.num_fmt, "%#jo", 4);
    304 		break;
    305 	case 10:
    306 		memcpy(s.num_fmt, "%ju", 4);
    307 		break;
    308 	case 16:
    309 		memcpy(s.num_fmt, "%#jx", 4);
    310 		break;
    311 	default:
    312 		goto had_error;
    313 	}
    314 
    315 	store_num(&s, s.num_fmt, val);
    316 
    317 	if ((old ? old_style(&s) : new_style(&s)) < 0) {
    318 had_error:
    319 #ifndef _KERNEL
    320 		errno = EINVAL;
    321 #endif
    322 		had_error = 1;
    323 		store(&s, '#');
    324 	} else if (s.in_angle_brackets)
    325 		store(&s, '>');
    326 	finish_buffer(&s);
    327 	return had_error ? -1 : (int)(s.total_len - 1);
    328 }
    329 
    330 int
    331 snprintb(char *buf, size_t bufsize, const char *bitfmt, uint64_t val)
    332 {
    333 	return snprintb_m(buf, bufsize, bitfmt, val, 0);
    334 }
    335 # endif /* ! HAVE_SNPRINTB_M */
    336 #endif /* ! _STANDALONE */
    337