Branch data Line data Source code
1 : : /*
2 : : * Copyright (c) 2021 BayLibre, SAS
3 : : *
4 : : * SPDX-License-Identifier: Apache-2.0
5 : : */
6 : :
7 : : #include <errno.h>
8 : : #include <stdarg.h>
9 : : #include <stdint.h>
10 : : #include <string.h>
11 : : #include <zephyr/toolchain.h>
12 : : #include <zephyr/linker/utils.h>
13 : : #include <zephyr/sys/cbprintf.h>
14 : : #include <sys/types.h>
15 : : #include <zephyr/sys/util.h>
16 : : #include <zephyr/sys/__assert.h>
17 : : #include <zephyr/logging/log.h>
18 : : LOG_MODULE_REGISTER(cbprintf_package, CONFIG_CBPRINTF_PACKAGE_LOG_LEVEL);
19 : :
20 : : /**
21 : : * @brief Check if address is in read only section.
22 : : *
23 : : * @param addr Address.
24 : : *
25 : : * @return True if address identified within read only section.
26 : : */
27 : 610 : static inline bool ptr_in_rodata(const char *addr)
28 : : {
29 : : #if defined(CBPRINTF_VIA_UNIT_TEST)
30 : : /* Unit test is X86 (or other host) but not using Zephyr
31 : : * linker scripts.
32 : : */
33 : : return false;
34 : : #else
35 : 610 : return linker_is_in_rodata(addr);
36 : : #endif
37 : : }
38 : :
39 : : /*
40 : : * va_list creation
41 : : */
42 : :
43 : : #if defined(__CHECKER__)
44 : : static int cbprintf_via_va_list(cbprintf_cb out,
45 : : cbvprintf_external_formatter_func formatter,
46 : : void *ctx,
47 : : const char *fmt, void *buf)
48 : : {
49 : : return 0;
50 : : }
51 : : #elif defined(__aarch64__)
52 : : /*
53 : : * Reference:
54 : : *
55 : : * Procedure Call Standard for the ARM 64-bit Architecture
56 : : */
57 : :
58 : : struct __va_list {
59 : : void *__stack;
60 : : void *__gr_top;
61 : : void *__vr_top;
62 : : int __gr_offs;
63 : : int __vr_offs;
64 : : };
65 : :
66 : : BUILD_ASSERT(sizeof(va_list) == sizeof(struct __va_list),
67 : : "architecture specific support is wrong");
68 : :
69 : : static int cbprintf_via_va_list(cbprintf_cb out,
70 : : cbvprintf_external_formatter_func formatter,
71 : : void *ctx,
72 : : const char *fmt, void *buf)
73 : : {
74 : : union {
75 : : va_list ap;
76 : : struct __va_list __ap;
77 : : } u;
78 : :
79 : : /* create a valid va_list with our buffer */
80 : : u.__ap.__stack = buf;
81 : : u.__ap.__gr_top = NULL;
82 : : u.__ap.__vr_top = NULL;
83 : : u.__ap.__gr_offs = 0;
84 : : u.__ap.__vr_offs = 0;
85 : :
86 : : return formatter(out, ctx, fmt, u.ap);
87 : : }
88 : :
89 : : #elif defined(__x86_64__)
90 : : /*
91 : : * Reference:
92 : : *
93 : : * System V Application Binary Interface
94 : : * AMD64 Architecture Processor Supplement
95 : : */
96 : :
97 : : struct __va_list {
98 : : unsigned int gp_offset;
99 : : unsigned int fp_offset;
100 : : void *overflow_arg_area;
101 : : void *reg_save_area;
102 : : };
103 : :
104 : : BUILD_ASSERT(sizeof(va_list) == sizeof(struct __va_list),
105 : : "architecture specific support is wrong");
106 : :
107 : : static int cbprintf_via_va_list(cbprintf_cb out,
108 : : cbvprintf_external_formatter_func formatter,
109 : : void *ctx,
110 : : const char *fmt, void *buf)
111 : : {
112 : : union {
113 : : va_list ap;
114 : : struct __va_list __ap;
115 : : } u;
116 : :
117 : : /* create a valid va_list with our buffer */
118 : : u.__ap.overflow_arg_area = buf;
119 : : u.__ap.reg_save_area = NULL;
120 : : u.__ap.gp_offset = (6 * 8);
121 : : u.__ap.fp_offset = (6 * 8 + 16 * 16);
122 : :
123 : : return formatter(out, ctx, fmt, u.ap);
124 : : }
125 : :
126 : : #elif defined(__xtensa__)
127 : : /*
128 : : * Reference:
129 : : *
130 : : * gcc source code (gcc/config/xtensa/xtensa.c)
131 : : * xtensa_build_builtin_va_list(), xtensa_va_start(),
132 : : * xtensa_gimplify_va_arg_expr()
133 : : */
134 : :
135 : : struct __va_list {
136 : : void *__va_stk;
137 : : void *__va_reg;
138 : : int __va_ndx;
139 : : };
140 : :
141 : : BUILD_ASSERT(sizeof(va_list) == sizeof(struct __va_list),
142 : : "architecture specific support is wrong");
143 : :
144 : : static int cbprintf_via_va_list(cbprintf_cb out,
145 : : cbvprintf_external_formatter_func formatter,
146 : : void *ctx,
147 : : const char *fmt, void *buf)
148 : : {
149 : : union {
150 : : va_list ap;
151 : : struct __va_list __ap;
152 : : } u;
153 : :
154 : : /* create a valid va_list with our buffer */
155 : : u.__ap.__va_stk = (char *)buf - 32;
156 : : u.__ap.__va_reg = NULL;
157 : : u.__ap.__va_ndx = (6 + 2) * 4;
158 : :
159 : : return formatter(out, ctx, fmt, u.ap);
160 : : }
161 : :
162 : : #else
163 : : /*
164 : : * Default implementation shared by many architectures like
165 : : * 32-bit ARM and Intel.
166 : : *
167 : : * We assume va_list is a simple pointer.
168 : : */
169 : :
170 : : BUILD_ASSERT(sizeof(va_list) == sizeof(void *),
171 : : "architecture specific support is needed");
172 : :
173 : 209 : static int cbprintf_via_va_list(cbprintf_cb out,
174 : : cbvprintf_external_formatter_func formatter,
175 : : void *ctx,
176 : : const char *fmt, void *buf)
177 : : {
178 : 209 : union {
179 : : va_list ap;
180 : : void *ptr;
181 : : } u;
182 : :
183 : 209 : u.ptr = buf;
184 : :
185 : 209 : return formatter(out, ctx, fmt, u.ap);
186 : : }
187 : :
188 : : #endif
189 : :
190 : 0 : static size_t get_package_len(void *packaged)
191 : : {
192 [ # # ]: 0 : __ASSERT_NO_MSG(packaged != NULL);
193 : :
194 : 0 : uint8_t *buf = packaged;
195 : 0 : uint8_t *start = buf;
196 : 0 : unsigned int args_size, s_nbr, ros_nbr;
197 : :
198 : 0 : args_size = buf[0] * sizeof(int);
199 : 0 : s_nbr = buf[1];
200 : 0 : ros_nbr = buf[2];
201 : :
202 : : /* Move beyond args. */
203 : 0 : buf += args_size;
204 : :
205 : : /* Move beyond read-only string indexes array. */
206 : 0 : buf += ros_nbr;
207 : :
208 : : /* Move beyond strings appended to the package. */
209 [ # # ]: 0 : for (unsigned int i = 0; i < s_nbr; i++) {
210 : 0 : buf++;
211 : 0 : buf += strlen((const char *)buf) + 1;
212 : : }
213 : :
214 : 0 : return (size_t)(uintptr_t)(buf - start);
215 : : }
216 : :
217 : 0 : static int append_string(cbprintf_convert_cb cb, void *ctx, const char *str, uint16_t strl)
218 : : {
219 : : /* Guard against NULL string pointers. Passing NULL to %s is a
220 : : * caller bug, but deferred log packages (see cbvprintf_package())
221 : : * can capture a NULL argument now and dereference it much later,
222 : : * disconnecting the fault from the offending call site and making
223 : : * triage difficult. Substitute "(null)", matching glibc's printf
224 : : * family, so the bad caller shows up in the log instead of the
225 : : * log infrastructure crashing.
226 : : */
227 [ # # ]: 0 : if (str == NULL) {
228 : 0 : str = "(null)";
229 : : }
230 : :
231 [ # # ]: 0 : if (cb == NULL) {
232 : 0 : return 1 + strlen(str);
233 : : }
234 : :
235 [ # # ]: 0 : strl = strl > 0 ? strl : strlen(str) + 1;
236 : 0 : return cb(str, strl, ctx);
237 : : }
238 : :
239 : 418 : int cbvprintf_package(void *packaged, size_t len, uint32_t flags,
240 : : const char *fmt, va_list ap)
241 : : {
242 : : /*
243 : : * Internally, a byte is used to store location of a string argument within a
244 : : * package. MSB bit is set if string is read-only so effectively 7 bits are
245 : : * used for index, which should be enough.
246 : : */
247 : : #define STR_POS_RO_FLAG BIT(7)
248 : : #define STR_POS_MASK BIT_MASK(7)
249 : :
250 : : /* Buffer offset abstraction for better code clarity. */
251 : : #define BUF_OFFSET (buf - (uintptr_t)buf0)
252 : :
253 : 418 : uint8_t *buf0 = packaged; /* buffer start (may be NULL) */
254 : 418 : uintptr_t buf = (uintptr_t)buf0; /* current buffer position */
255 : 418 : unsigned int size; /* current argument's size */
256 : 418 : unsigned int align; /* current argument's required alignment */
257 : 418 : uint8_t str_ptr_pos[16]; /* string pointer positions */
258 : 418 : uint8_t str_ptr_arg[16]; /* string pointer argument index */
259 : 418 : unsigned int s_idx = 0; /* index into str_ptr_pos[] */
260 : 418 : unsigned int s_rw_cnt = 0; /* number of rw strings */
261 : 418 : unsigned int s_ro_cnt = 0; /* number of ro strings */
262 : 418 : int arg_idx = -1; /* Argument index. Preincremented thus starting from -1.*/
263 : 418 : unsigned int i;
264 : 418 : const char *s;
265 : 418 : bool parsing = false;
266 : : /* Flag indicates that rw strings are stored as array with positions,
267 : : * instead of appending them to the package.
268 : : */
269 : 418 : bool rws_pos_en = !!(flags & CBPRINTF_PACKAGE_ADD_RW_STR_POS);
270 : : /* Get number of first read only strings present in the string.
271 : : * There is always at least 1 (fmt) but flags can indicate more, e.g
272 : : * fixed prefix appended to all strings.
273 : : */
274 : 418 : int fros_cnt = 1 + Z_CBPRINTF_PACKAGE_FIRST_RO_STR_CNT_GET(flags);
275 : 418 : bool is_str_arg = false;
276 : 418 : union cbprintf_package_hdr *pkg_hdr = packaged;
277 : :
278 : : /* Buffer must be aligned at least to size of a pointer. */
279 [ + - ]: 418 : if ((uintptr_t)packaged % sizeof(void *)) {
280 : : return -EFAULT;
281 : : }
282 : :
283 : : #if defined(__xtensa__)
284 : : /* Xtensa requires package to be 16 bytes aligned. */
285 : : if ((uintptr_t)packaged % CBPRINTF_PACKAGE_ALIGNMENT) {
286 : : return -EFAULT;
287 : : }
288 : : #endif
289 : :
290 : : /*
291 : : * Make room to store the arg list size, the number of
292 : : * appended writable strings and the number of appended
293 : : * read-only strings. They both occupy 1 byte each.
294 : : * Skip a byte. Then a uint32_t to store flags used to
295 : : * create the package.
296 : : *
297 : : * Given the next value to store is the format string pointer
298 : : * which is guaranteed to be at least 4 bytes, we just reserve
299 : : * multiple of pointer size for the above to preserve alignment.
300 : : *
301 : : * Refer to union cbprintf_package_hdr for more details.
302 : : */
303 : 418 : buf += sizeof(*pkg_hdr);
304 : :
305 : : /*
306 : : * When buf0 is NULL we don't store anything.
307 : : * Instead we count the needed space to store the data.
308 : : * In this case, incoming len argument indicates the anticipated
309 : : * buffer "misalignment" offset.
310 : : */
311 [ + + ]: 418 : if (buf0 == NULL) {
312 : 209 : buf += len % CBPRINTF_PACKAGE_ALIGNMENT;
313 : : /*
314 : : * The space to store the data is represented by both the
315 : : * buffer offset as well as the extra string data to be
316 : : * appended. When only figuring out the needed space, we
317 : : * don't append anything. Instead, we reuse the len variable
318 : : * to sum the size of that data.
319 : : *
320 : : * Also, we subtract any initial misalignment offset from
321 : : * the total as this won't be part of the buffer. To avoid
322 : : * going negative with an unsigned variable, we add an offset
323 : : * (CBPRINTF_PACKAGE_ALIGNMENT) that will be removed before
324 : : * returning.
325 : : */
326 : 209 : len = CBPRINTF_PACKAGE_ALIGNMENT - (len % CBPRINTF_PACKAGE_ALIGNMENT);
327 : : }
328 : :
329 : : /*
330 : : * Otherwise we must ensure we can store at least
331 : : * the pointer to the format string itself.
332 : : */
333 [ + + - + ]: 418 : if ((buf0 != NULL) && (BUF_OFFSET + sizeof(char *)) > len) {
334 : : return -ENOSPC;
335 : : }
336 : :
337 : : /*
338 : : * Then process the format string itself.
339 : : * Here we branch directly into the code processing strings
340 : : * which is in the middle of the following while() loop. That's the
341 : : * reason for the post-decrement on fmt as it will be incremented
342 : : * prior to the next (actually first) round of that loop.
343 : : */
344 : 418 : s = fmt;
345 : 418 : --fmt;
346 : 418 : align = VA_STACK_ALIGN(char *);
347 : 418 : size = sizeof(char *);
348 : 418 : goto process_string;
349 : :
350 : 16174 : while (true) {
351 : :
352 : : #if defined(CONFIG_CBPRINTF_PACKAGE_SUPPORT_TAGGED_ARGUMENTS)
353 : : if ((flags & CBPRINTF_PACKAGE_ARGS_ARE_TAGGED)
354 : : == CBPRINTF_PACKAGE_ARGS_ARE_TAGGED) {
355 : : int arg_tag = va_arg(ap, int);
356 : :
357 : : /*
358 : : * Here we copy the tag over to the package.
359 : : */
360 : : align = VA_STACK_ALIGN(int);
361 : : size = sizeof(int);
362 : :
363 : : /* align destination buffer location */
364 : : buf = ROUND_UP(buf, align);
365 : :
366 : : /* make sure the data fits */
367 : : if (buf0 != NULL && BUF_OFFSET + size > len) {
368 : : return -ENOSPC;
369 : : }
370 : :
371 : : if (buf0 != NULL) {
372 : : *(int *)buf = arg_tag;
373 : : }
374 : :
375 : : buf += sizeof(int);
376 : :
377 : : if (arg_tag == CBPRINTF_PACKAGE_ARG_TYPE_END) {
378 : : /* End of arguments */
379 : : break;
380 : : }
381 : :
382 : : /*
383 : : * There are lots of __fallthrough here since
384 : : * quite a few of the data types have the same
385 : : * storage size.
386 : : */
387 : : switch (arg_tag) {
388 : : case CBPRINTF_PACKAGE_ARG_TYPE_CHAR:
389 : : __fallthrough;
390 : : case CBPRINTF_PACKAGE_ARG_TYPE_UNSIGNED_CHAR:
391 : : __fallthrough;
392 : : case CBPRINTF_PACKAGE_ARG_TYPE_SHORT:
393 : : __fallthrough;
394 : : case CBPRINTF_PACKAGE_ARG_TYPE_UNSIGNED_SHORT:
395 : : __fallthrough;
396 : : case CBPRINTF_PACKAGE_ARG_TYPE_INT:
397 : : __fallthrough;
398 : : case CBPRINTF_PACKAGE_ARG_TYPE_UNSIGNED_INT:
399 : : align = VA_STACK_ALIGN(int);
400 : : size = sizeof(int);
401 : : break;
402 : :
403 : : case CBPRINTF_PACKAGE_ARG_TYPE_LONG:
404 : : __fallthrough;
405 : : case CBPRINTF_PACKAGE_ARG_TYPE_UNSIGNED_LONG:
406 : : align = VA_STACK_ALIGN(long);
407 : : size = sizeof(long);
408 : : break;
409 : :
410 : : case CBPRINTF_PACKAGE_ARG_TYPE_LONG_LONG:
411 : : __fallthrough;
412 : : case CBPRINTF_PACKAGE_ARG_TYPE_UNSIGNED_LONG_LONG:
413 : : align = VA_STACK_ALIGN(long long);
414 : : size = sizeof(long long);
415 : : break;
416 : :
417 : : case CBPRINTF_PACKAGE_ARG_TYPE_FLOAT:
418 : : __fallthrough;
419 : : case CBPRINTF_PACKAGE_ARG_TYPE_DOUBLE:
420 : : __fallthrough;
421 : : case CBPRINTF_PACKAGE_ARG_TYPE_LONG_DOUBLE: {
422 : : /*
423 : : * Handle floats separately as they may be
424 : : * held in a different register set.
425 : : */
426 : : union { double d; long double ld; } v;
427 : :
428 : : if (arg_tag == CBPRINTF_PACKAGE_ARG_TYPE_LONG_DOUBLE) {
429 : : v.ld = va_arg(ap, long double);
430 : : align = VA_STACK_ALIGN(long double);
431 : : size = sizeof(long double);
432 : : } else {
433 : : v.d = va_arg(ap, double);
434 : : align = VA_STACK_ALIGN(double);
435 : : size = sizeof(double);
436 : : }
437 : :
438 : : /* align destination buffer location */
439 : : buf = ROUND_UP(buf, align);
440 : : if (buf0 != NULL) {
441 : : /* make sure it fits */
442 : : if ((BUF_OFFSET + size) > len) {
443 : : return -ENOSPC;
444 : : }
445 : : if (Z_CBPRINTF_VA_STACK_LL_DBL_MEMCPY) {
446 : : memcpy((void *)buf, (uint8_t *)&v, size);
447 : : } else if (fmt[-1] == 'L') {
448 : : *(long double *)buf = v.ld;
449 : : } else {
450 : : *(double *)buf = v.d;
451 : : }
452 : : }
453 : : buf += size;
454 : : parsing = false;
455 : : continue;
456 : : }
457 : :
458 : : case CBPRINTF_PACKAGE_ARG_TYPE_PTR_CHAR:
459 : : is_str_arg = true;
460 : :
461 : : __fallthrough;
462 : : case CBPRINTF_PACKAGE_ARG_TYPE_PTR_VOID:
463 : : align = VA_STACK_ALIGN(void *);
464 : : size = sizeof(void *);
465 : : break;
466 : :
467 : : default:
468 : : return -EINVAL;
469 : : }
470 : :
471 : : } else
472 : : #endif /* CONFIG_CBPRINTF_PACKAGE_SUPPORT_TAGGED_ARGUMENTS */
473 : : {
474 : : /* Scan the format string */
475 [ + + ]: 16174 : if (*++fmt == '\0') {
476 : : break;
477 : : }
478 : :
479 [ + + ]: 15756 : if (!parsing) {
480 [ + + ]: 14318 : if (*fmt == '%') {
481 : 1028 : parsing = true;
482 : 1028 : arg_idx++;
483 : 1028 : align = VA_STACK_ALIGN(int);
484 : 1028 : size = sizeof(int);
485 : : }
486 : 14318 : continue;
487 : : }
488 [ + + - - : 1438 : switch (*fmt) {
- + + - -
- - ]
489 : 2 : case '%':
490 : 2 : parsing = false;
491 : 2 : arg_idx--;
492 : 2 : continue;
493 : :
494 : 410 : case '#':
495 : : case '-':
496 : : case '+':
497 : : case ' ':
498 : : case '0':
499 : : case '1':
500 : : case '2':
501 : : case '3':
502 : : case '4':
503 : : case '5':
504 : : case '6':
505 : : case '7':
506 : : case '8':
507 : : case '9':
508 : : case '.':
509 : : case 'h':
510 : : case 'l':
511 : : case 'L':
512 : 410 : continue;
513 : :
514 : : case '*':
515 : : break;
516 : :
517 : 0 : case 'j':
518 : 0 : align = VA_STACK_ALIGN(intmax_t);
519 : 0 : size = sizeof(intmax_t);
520 : 0 : continue;
521 : :
522 : 0 : case 'z':
523 : 0 : align = VA_STACK_ALIGN(size_t);
524 : 0 : size = sizeof(size_t);
525 : 0 : continue;
526 : :
527 : 0 : case 't':
528 : 0 : align = VA_STACK_ALIGN(ptrdiff_t);
529 : 0 : size = sizeof(ptrdiff_t);
530 : 0 : continue;
531 : :
532 : 416 : case 'c':
533 : : case 'd':
534 : : case 'i':
535 : : case 'o':
536 : : case 'u':
537 : : case 'x':
538 : : case 'X':
539 [ - + ]: 416 : if (fmt[-1] == 'l') {
540 [ # # ]: 0 : if (fmt[-2] == 'l') {
541 : : align = VA_STACK_ALIGN(long long);
542 : : size = sizeof(long long);
543 : : } else {
544 : 0 : align = VA_STACK_ALIGN(long);
545 : 0 : size = sizeof(long);
546 : : }
547 : : }
548 : : parsing = false;
549 : : break;
550 : :
551 : 610 : case 's':
552 : 610 : is_str_arg = true;
553 : :
554 : : __fallthrough;
555 : : case 'p':
556 : : case 'n':
557 : : align = VA_STACK_ALIGN(void *);
558 : : size = sizeof(void *);
559 : : parsing = false;
560 : : break;
561 : :
562 : 0 : case 'a':
563 : : case 'A':
564 : : case 'e':
565 : : case 'E':
566 : : case 'f':
567 : : case 'F':
568 : : case 'g':
569 : 0 : case 'G': {
570 : : /*
571 : : * Handle floats separately as they may be
572 : : * held in a different register set.
573 : : */
574 : 0 : union { double d; long double ld; } v;
575 : :
576 [ # # ]: 0 : if (fmt[-1] == 'L') {
577 : 0 : v.ld = va_arg(ap, long double);
578 : 0 : align = VA_STACK_ALIGN(long double);
579 : 0 : size = sizeof(long double);
580 : : } else {
581 : 0 : v.d = va_arg(ap, double);
582 : 0 : align = VA_STACK_ALIGN(double);
583 : 0 : size = sizeof(double);
584 : : }
585 : : /* align destination buffer location */
586 : 0 : buf = ROUND_UP(buf, align);
587 [ # # ]: 0 : if (buf0 != NULL) {
588 : : /* make sure it fits */
589 [ # # ]: 0 : if (BUF_OFFSET + size > len) {
590 : 0 : return -ENOSPC;
591 : : }
592 : 0 : if (Z_CBPRINTF_VA_STACK_LL_DBL_MEMCPY) {
593 : : memcpy((void *)buf, (uint8_t *)&v, size);
594 [ # # ]: 0 : } else if (fmt[-1] == 'L') {
595 : 0 : *(long double *)buf = v.ld;
596 : : } else {
597 : 0 : *(double *)buf = v.d;
598 : : }
599 : : }
600 : 0 : buf += size;
601 : 0 : parsing = false;
602 : 0 : continue;
603 : : }
604 : :
605 : 0 : default:
606 : 0 : parsing = false;
607 : 0 : continue;
608 : : }
609 : : }
610 : :
611 : : /* align destination buffer location */
612 : 1026 : buf = ROUND_UP(buf, align);
613 : :
614 : : /* make sure the data fits */
615 [ + + - + ]: 1026 : if ((buf0 != NULL) && (BUF_OFFSET + size) > len) {
616 : : return -ENOSPC;
617 : : }
618 : :
619 : : /* copy va_list data over to our buffer */
620 [ + + ]: 1026 : if (is_str_arg) {
621 : 610 : s = va_arg(ap, char *);
622 : 1028 : process_string:
623 [ + + ]: 1028 : if (buf0 != NULL) {
624 : 514 : *(const char **)buf = s;
625 : : }
626 : :
627 [ + + ]: 1028 : bool is_ro = (fros_cnt-- > 0) ? true : ptr_in_rodata(s);
628 : 1028 : bool do_ro = !!(flags & CBPRINTF_PACKAGE_ADD_RO_STR_POS);
629 : :
630 [ + + ]: 1028 : if (is_ro && !do_ro) {
631 : : /* nothing to do */
632 : : } else {
633 : 610 : uint32_t s_ptr_idx = BUF_OFFSET / sizeof(int);
634 : :
635 : : /*
636 : : * In the do_ro case we must consider
637 : : * room for possible STR_POS_RO_FLAG.
638 : : * Otherwise the index range is 8 bits
639 : : * and any overflow is caught later.
640 : : */
641 [ - + ]: 610 : if (do_ro && s_ptr_idx > STR_POS_MASK) {
642 : 0 : __ASSERT(false, "String with too many arguments");
643 : : return -EINVAL;
644 : : }
645 : :
646 [ - + ]: 610 : if (s_idx >= ARRAY_SIZE(str_ptr_pos)) {
647 : 0 : __ASSERT(false, "str_ptr_pos[] too small");
648 : : return -EINVAL;
649 : : }
650 : :
651 [ + + ]: 610 : if (buf0 != NULL) {
652 : : /*
653 : : * Remember string pointer location.
654 : : * We will append non-ro strings later.
655 : : */
656 : 305 : str_ptr_pos[s_idx] = s_ptr_idx;
657 : 305 : str_ptr_arg[s_idx] = arg_idx;
658 [ - + ]: 305 : if (is_ro) {
659 : : /* flag read-only string. */
660 : 0 : str_ptr_pos[s_idx] |= STR_POS_RO_FLAG;
661 : 0 : s_ro_cnt++;
662 : : } else {
663 : 305 : s_rw_cnt++;
664 : : }
665 [ - + ]: 305 : } else if (is_ro) {
666 : : /*
667 : : * Add only pointer position prefix
668 : : * when counting strings.
669 : : */
670 : 0 : len += 1;
671 [ - + ]: 305 : } else if (rws_pos_en) {
672 : : /*
673 : : * Add only pointer position prefix and
674 : : * argument index when counting strings.
675 : : */
676 : 0 : len += 2;
677 : : } else {
678 : : /*
679 : : * Add the string length, the final '\0'
680 : : * and size of the pointer position prefix.
681 : : */
682 : 305 : len += strlen(s) + 1 + 1;
683 : : }
684 : :
685 : 610 : s_idx++;
686 : : }
687 : 1028 : buf += sizeof(char *);
688 : :
689 : 1028 : is_str_arg = false;
690 [ + - ]: 416 : } else if (size == sizeof(int)) {
691 : 416 : int v = va_arg(ap, int);
692 : :
693 [ + + ]: 416 : if (buf0 != NULL) {
694 : 208 : *(int *)buf = v;
695 : : }
696 : 416 : buf += sizeof(int);
697 : 0 : } else if (size == sizeof(long)) {
698 : : long v = va_arg(ap, long);
699 : :
700 : : if (buf0 != NULL) {
701 : : *(long *)buf = v;
702 : : }
703 : : buf += sizeof(long);
704 [ # # ]: 0 : } else if (size == sizeof(long long)) {
705 : 0 : long long v = va_arg(ap, long long);
706 : :
707 [ # # ]: 0 : if (buf0 != NULL) {
708 : 0 : if (Z_CBPRINTF_VA_STACK_LL_DBL_MEMCPY) {
709 : : memcpy((void *)buf, (uint8_t *)&v, sizeof(long long));
710 : : } else {
711 : 0 : *(long long *)buf = v;
712 : : }
713 : : }
714 : 0 : buf += sizeof(long long);
715 : : } else {
716 : 0 : __ASSERT(false, "unexpected size %u", size);
717 : : return -EINVAL;
718 : : }
719 : : }
720 : :
721 : : /*
722 : : * We remember the size of the argument list as a multiple of
723 : : * sizeof(int) and limit it to a 8-bit field. That means 1020 bytes
724 : : * worth of va_list, or about 127 arguments on a 64-bit system
725 : : * (twice that on 32-bit systems). That ought to be good enough.
726 : : */
727 [ - + ]: 418 : if ((BUF_OFFSET / sizeof(int)) > 255) {
728 : 0 : __ASSERT(false, "too many format args");
729 : : return -EINVAL;
730 : : }
731 : :
732 : : /*
733 : : * If all we wanted was to count required buffer size
734 : : * then we have it now.
735 : : */
736 [ + + ]: 418 : if (buf0 == NULL) {
737 : 209 : return BUF_OFFSET + len - CBPRINTF_PACKAGE_ALIGNMENT;
738 : : }
739 : :
740 : : /* Clear our buffer header. We made room for it initially. */
741 : 209 : *(char **)buf0 = NULL;
742 : :
743 : : /* Record end of argument list. */
744 : 209 : pkg_hdr->desc.len = BUF_OFFSET / sizeof(int);
745 : :
746 [ - + ]: 209 : if (rws_pos_en) {
747 : : /* Strings are appended, update location counter. */
748 : 0 : pkg_hdr->desc.str_cnt = 0;
749 : 0 : pkg_hdr->desc.rw_str_cnt = s_rw_cnt;
750 : : } else {
751 : : /* Strings are appended, update append counter. */
752 : 209 : pkg_hdr->desc.str_cnt = s_rw_cnt;
753 : 209 : pkg_hdr->desc.rw_str_cnt = 0;
754 : : }
755 : :
756 : 209 : pkg_hdr->desc.ro_str_cnt = s_ro_cnt;
757 : :
758 : : #ifdef CONFIG_CBPRINTF_PACKAGE_HEADER_STORE_CREATION_FLAGS
759 : : pkg_hdr->desc.pkg_flags = flags;
760 : : #endif
761 : :
762 : : /* Store strings pointer locations of read only strings. */
763 [ - + ]: 209 : if (s_ro_cnt != 0U) {
764 [ # # ]: 0 : for (i = 0; i < s_idx; i++) {
765 [ # # ]: 0 : if (!(str_ptr_pos[i] & STR_POS_RO_FLAG)) {
766 : 0 : continue;
767 : : }
768 : :
769 : 0 : uint8_t pos = str_ptr_pos[i] & STR_POS_MASK;
770 : :
771 : : /* make sure it fits */
772 [ # # ]: 0 : if ((BUF_OFFSET + 1) > len) {
773 : : return -ENOSPC;
774 : : }
775 : : /* store the pointer position prefix */
776 : 0 : *(uint8_t *)buf = pos;
777 : 0 : ++buf;
778 : : }
779 : : }
780 : :
781 : : /* Store strings prefixed by their pointer location. */
782 [ + + ]: 514 : for (i = 0; i < s_idx; i++) {
783 : : /* Process only RW strings. */
784 [ - + - - ]: 305 : if (s_ro_cnt && str_ptr_pos[i] & STR_POS_RO_FLAG) {
785 : 0 : continue;
786 : : }
787 : :
788 [ - + ]: 305 : if (rws_pos_en) {
789 : 0 : size = 0;
790 : 0 : *(uint8_t *)buf = str_ptr_arg[i];
791 : 0 : ++buf;
792 : : } else {
793 : : /* retrieve the string pointer */
794 : 305 : s = *(char **)(buf0 + str_ptr_pos[i] * sizeof(int));
795 : : /* clear the in-buffer pointer (less entropy if compressed) */
796 : 305 : *(char **)(buf0 + str_ptr_pos[i] * sizeof(int)) = NULL;
797 : : /* find the string length including terminating '\0' */
798 : 305 : size = strlen(s) + 1;
799 : : }
800 : :
801 : : /* make sure it fits */
802 [ - + ]: 305 : if ((BUF_OFFSET + 1 + size) > len) {
803 : : return -ENOSPC;
804 : : }
805 : : /* store the pointer position prefix */
806 : 305 : *(uint8_t *)buf = str_ptr_pos[i];
807 : 305 : ++buf;
808 : : /* copy the string with its terminating '\0' */
809 : 305 : memcpy((void *)buf, (uint8_t *)s, size);
810 : 305 : buf += size;
811 : : }
812 : :
813 : : /*
814 : : * TODO: remove pointers for appended strings since they're useless.
815 : : * TODO: explore leveraging same mechanism to remove alignment padding
816 : : */
817 : :
818 : 209 : return BUF_OFFSET;
819 : :
820 : : #undef BUF_OFFSET
821 : : #undef STR_POS_RO_FLAG
822 : : #undef STR_POS_MASK
823 : : }
824 : :
825 : 0 : int cbprintf_package(void *packaged, size_t len, uint32_t flags,
826 : : const char *format, ...)
827 : : {
828 : 0 : va_list ap;
829 : 0 : int ret;
830 : :
831 : 0 : va_start(ap, format);
832 : 0 : ret = cbvprintf_package(packaged, len, flags, format, ap);
833 : 0 : va_end(ap);
834 : 0 : return ret;
835 : : }
836 : :
837 : 209 : int cbpprintf_external(cbprintf_cb out,
838 : : cbvprintf_external_formatter_func formatter,
839 : : void *ctx, void *packaged)
840 : : {
841 : 209 : uint8_t *buf = packaged;
842 : 209 : struct cbprintf_package_hdr_ext *hdr = packaged;
843 : 209 : char *s, **ps;
844 : 209 : unsigned int i, args_size, s_nbr, ros_nbr, rws_nbr, s_idx;
845 : :
846 [ + - ]: 209 : if (buf == NULL) {
847 : : return -EINVAL;
848 : : }
849 : :
850 : : /* Retrieve the size of the arg list and number of strings. */
851 : 209 : args_size = hdr->hdr.desc.len * sizeof(int);
852 : 209 : s_nbr = hdr->hdr.desc.str_cnt;
853 : 209 : ros_nbr = hdr->hdr.desc.ro_str_cnt;
854 : 209 : rws_nbr = hdr->hdr.desc.rw_str_cnt;
855 : :
856 : : /* Locate the string table */
857 : 209 : s = (char *)(buf + args_size + ros_nbr + 2 * rws_nbr);
858 : :
859 : : /*
860 : : * Patch in string pointers.
861 : : */
862 [ + + ]: 514 : for (i = 0; i < s_nbr; i++) {
863 : : /* Locate pointer location for this string */
864 : 305 : s_idx = *(uint8_t *)s;
865 : 305 : ++s;
866 : 305 : ps = (char **)(buf + s_idx * sizeof(int));
867 : : /* update the pointer with current string location */
868 : 305 : *ps = s;
869 : : /* move to next string */
870 : 305 : s += strlen(s) + 1;
871 : : }
872 : :
873 : : /* Skip past the header */
874 : 209 : buf += sizeof(*hdr);
875 : :
876 : : /* Turn this into a va_list and print it */
877 : 209 : return cbprintf_via_va_list(out, formatter, ctx, hdr->fmt, buf);
878 : : }
879 : :
880 : : /* Function checks if character might be format specifier. Check is relaxed since
881 : : * compiler ensures that correct format specifier is used so it is enough to check
882 : : * that character is not one of potential modifier (e.g. number, dot, etc.).
883 : : */
884 : 0 : static bool is_fmt_spec(char c)
885 : : {
886 : 0 : return (c >= 64) && (c <= 122);
887 : : }
888 : :
889 : : /* Function checks if nth argument is a pointer (%p). Returns true if yes. Returns
890 : : * false if not or if string does not have nth argument.
891 : : */
892 : 0 : bool is_ptr(const char *fmt, int n)
893 : : {
894 : 0 : char c;
895 : 0 : bool mod = false;
896 : 0 : int cnt = 0;
897 : :
898 [ # # ]: 0 : while ((c = *fmt++) != '\0') {
899 [ # # ]: 0 : if (mod) {
900 [ # # ]: 0 : if (cnt == n) {
901 [ # # ]: 0 : if (c == 'p') {
902 : : return true;
903 [ # # ]: 0 : } else if (is_fmt_spec(c)) {
904 : : return false;
905 : : }
906 [ # # ]: 0 : } else if (is_fmt_spec(c)) {
907 : 0 : cnt++;
908 : 0 : mod = false;
909 : : }
910 : : }
911 [ # # ]: 0 : if (c == '%') {
912 : 0 : mod = !mod;
913 : : }
914 : : }
915 : :
916 : : return false;
917 : : }
918 : :
919 : 0 : int cbprintf_package_convert(void *in_packaged,
920 : : size_t in_len,
921 : : cbprintf_convert_cb cb,
922 : : void *ctx,
923 : : uint32_t flags,
924 : : uint16_t *strl,
925 : : size_t strl_len)
926 : : {
927 [ # # ]: 0 : __ASSERT_NO_MSG(in_packaged != NULL);
928 : :
929 : 0 : uint8_t *buf = in_packaged;
930 : 0 : uint32_t *buf32 = in_packaged;
931 : 0 : unsigned int args_size, ros_nbr, rws_nbr;
932 : 0 : bool rw_cpy;
933 : 0 : bool ro_cpy;
934 : 0 : struct cbprintf_package_desc *in_desc = in_packaged;
935 : 0 : int out_len;
936 : 0 : int rv;
937 : :
938 [ # # ]: 0 : in_len = in_len != 0 ? in_len : get_package_len(in_packaged);
939 : :
940 : : /* Get number of RO string indexes in the package and check if copying
941 : : * includes appending those strings.
942 : : */
943 : 0 : ros_nbr = in_desc->ro_str_cnt;
944 [ # # # # ]: 0 : ro_cpy = ros_nbr && (flags & CBPRINTF_PACKAGE_CONVERT_RO_STR);
945 : :
946 : : /* Get number of RW string indexes in the package and check if copying
947 : : * includes appending those strings.
948 : : */
949 : 0 : rws_nbr = in_desc->rw_str_cnt;
950 [ # # # # ]: 0 : rw_cpy = rws_nbr > 0 && (flags & CBPRINTF_PACKAGE_CONVERT_RW_STR);
951 : :
952 : :
953 : : /* If flags are not set or appending request without rw string indexes
954 : : * present is chosen, just do a simple copy (or length calculation).
955 : : * Assuming that it is the most common case.
956 : : */
957 [ # # ]: 0 : if (!rw_cpy && !ro_cpy) {
958 [ # # ]: 0 : if (cb) {
959 : 0 : (void)cb(in_packaged, in_len, ctx);
960 : 0 : (void)cb(NULL, 0, ctx);
961 : : }
962 : 0 : return in_len;
963 : : }
964 : :
965 : 0 : args_size = in_desc->len * sizeof(int);
966 : : /* Pointer to array with string locations. Array starts with read-only
967 : : * string locations.
968 : : */
969 : 0 : const char *fmt = *(const char **)(buf + sizeof(void *));
970 : 0 : uint8_t *rw_str_pos = &buf[args_size + ros_nbr];
971 : 0 : uint32_t keep_loc_mask;
972 : 0 : uint32_t append_mask;
973 : 0 : size_t keep_loc_cnt = 0;
974 : 0 : size_t append_cnt = 0;
975 : 0 : size_t rw_loc_cnt = 0;
976 : :
977 : : /* As we want to use bit mask to keep that data, assert if 32 bit mask is not enough. */
978 [ # # ]: 0 : __ASSERT_NO_MSG(ros_nbr + 2 * rws_nbr <= 32);
979 : 0 : if (ros_nbr + 2 * rws_nbr > 32) {
980 : : return -ENOSPC;
981 : : }
982 : :
983 : : /* Figure out what indexes to keep and what strings to append. */
984 [ # # ]: 0 : if (flags & CBPRINTF_PACKAGE_CONVERT_KEEP_RO_STR) {
985 : : /* Read-only strings locations are kept in the package. */
986 : 0 : keep_loc_mask = BIT_MASK(ros_nbr);
987 : 0 : keep_loc_cnt += ros_nbr;
988 : 0 : append_mask = 0;
989 [ # # ]: 0 : } else if (flags & CBPRINTF_PACKAGE_CONVERT_RO_STR) {
990 : : /* Read-only strings locations are appended to the package. */
991 : 0 : append_mask = BIT_MASK(ros_nbr);
992 : 0 : keep_loc_mask = 0;
993 : 0 : append_cnt += ros_nbr;
994 : : } else {
995 : : /* Read-only strings locations are discarded. */
996 : : keep_loc_mask = 0;
997 : : append_mask = 0;
998 : : }
999 : :
1000 : : /* Figure out which supposed RW strings are read-only and which are read-write.
1001 : : * Optionally, check if %p argument is used for a string and warn if it is.
1002 : : * Build a mask with all bytes that should be kept in the output package.
1003 : : */
1004 [ # # ]: 0 : for (unsigned int i = 0; i < rws_nbr; i++) {
1005 : 0 : uint8_t arg_idx = *rw_str_pos++;
1006 : 0 : uint8_t arg_pos = *rw_str_pos++;
1007 : 0 : const char *str = *(const char **)&buf32[arg_pos];
1008 : 0 : bool is_ro = ptr_in_rodata(str);
1009 : :
1010 [ # # # # ]: 0 : if (IS_ENABLED(CONFIG_CBPRINTF_CONVERT_CHECK_PTR) && cb && is_ptr(fmt, arg_idx)) {
1011 : 0 : LOG_WRN("(unsigned) char * used for %%p argument. "
1012 : : "It's recommended to cast it to void * because "
1013 : : "it may cause misbehavior in certain "
1014 : : "configurations. String:\"%s\" argument:%d", fmt, arg_idx);
1015 [ # # ]: 0 : } else if (is_ro) {
1016 [ # # ]: 0 : if (flags & CBPRINTF_PACKAGE_CONVERT_RO_STR) {
1017 : 0 : append_mask |= BIT(2 * i + 1 + ros_nbr);
1018 : 0 : append_cnt++;
1019 [ # # ]: 0 : } else if (flags & CBPRINTF_PACKAGE_CONVERT_KEEP_RO_STR) {
1020 : 0 : keep_loc_mask |= BIT(2 * i + 1 + ros_nbr);
1021 : 0 : keep_loc_cnt++;
1022 : : }
1023 [ # # ]: 0 : } else if (flags & CBPRINTF_PACKAGE_CONVERT_RW_STR) {
1024 : 0 : append_mask |= BIT(2 * i + 1 + ros_nbr);
1025 : 0 : append_cnt++;
1026 : : } else {
1027 : : /* Keep read-write string locations and argument index. */
1028 : 0 : keep_loc_mask |= BIT_MASK(2) << (2 * i + ros_nbr);
1029 : 0 : rw_loc_cnt++;
1030 : : }
1031 : : }
1032 : :
1033 : 0 : struct cbprintf_package_desc out_desc;
1034 : :
1035 : 0 : out_desc.len = in_desc->len;
1036 : 0 : out_desc.str_cnt = in_desc->str_cnt + append_cnt;
1037 : 0 : out_desc.rw_str_cnt = rw_loc_cnt;
1038 : 0 : out_desc.ro_str_cnt = keep_loc_cnt;
1039 : : /* Copy package header and arguments. */
1040 [ # # ]: 0 : if (cb) {
1041 : 0 : rv = cb(&out_desc, sizeof(out_desc), ctx);
1042 [ # # ]: 0 : if (rv < 0) {
1043 : : return rv;
1044 : : }
1045 : 0 : rv = cb(buf + sizeof(out_desc), args_size - sizeof(out_desc), ctx);
1046 [ # # ]: 0 : if (rv < 0) {
1047 : : return rv;
1048 : : }
1049 : : }
1050 : 0 : out_len = args_size;
1051 : :
1052 : 0 : uint8_t *loc_pos = &buf[args_size];
1053 : :
1054 : : /* Copy read-only string locations. */
1055 [ # # ]: 0 : while (keep_loc_mask != 0) {
1056 : 0 : uint32_t bit = __builtin_ctz(keep_loc_mask);
1057 : 0 : uint8_t loc = loc_pos[bit];
1058 : :
1059 : 0 : keep_loc_mask &= ~BIT(bit);
1060 [ # # ]: 0 : if (cb) {
1061 : 0 : rv = cb(&loc, 1, ctx);
1062 [ # # ]: 0 : if (rv < 0) {
1063 : 0 : return rv;
1064 : : }
1065 : : }
1066 : 0 : out_len++;
1067 : : }
1068 : :
1069 : : size_t strl_cnt = 0;
1070 : :
1071 : : /* Copy read-write string locations. */
1072 [ # # ]: 0 : while (append_mask != 0) {
1073 : 0 : uint32_t bit = __builtin_ctz(append_mask);
1074 : 0 : uint8_t loc = loc_pos[bit];
1075 : 0 : const char *str = *(const char **)&buf32[loc];
1076 : 0 : int len = 0;
1077 : :
1078 : 0 : append_mask &= ~BIT(bit);
1079 [ # # ]: 0 : if (cb) {
1080 : 0 : rv = cb(&loc, 1, ctx);
1081 [ # # ]: 0 : if (rv < 0) {
1082 : 0 : return rv;
1083 : : }
1084 [ # # ]: 0 : if (strl && strl_cnt < strl_len) {
1085 : 0 : len = strl[strl_cnt++];
1086 : : }
1087 : : }
1088 : 0 : out_len++;
1089 : :
1090 : 0 : len = append_string(cb, ctx, str, len);
1091 [ # # ]: 0 : if (len < 0) {
1092 : 0 : return len;
1093 : : }
1094 : 0 : out_len += len;
1095 : : /* If possible store calculated string length. */
1096 [ # # # # ]: 0 : if (!cb && strl && strl_cnt < strl_len) {
1097 : 0 : strl[strl_cnt++] = (uint16_t)len;
1098 : : }
1099 : : }
1100 : :
1101 : : /* Copy strings that were already appended to the input package. */
1102 : 0 : size_t strs_len = in_len - (args_size + ros_nbr + 2 * rws_nbr);
1103 : :
1104 [ # # ]: 0 : if (strs_len > 0) {
1105 [ # # ]: 0 : if (cb) {
1106 : 0 : rv = cb(&buf[args_size + ros_nbr + 2 * rws_nbr], strs_len, ctx);
1107 [ # # ]: 0 : if (rv < 0) {
1108 : : return rv;
1109 : : }
1110 : : }
1111 : 0 : out_len += strs_len;
1112 : : }
1113 : :
1114 : : /* Empty call (can be interpreted as flushing) */
1115 [ # # ]: 0 : if (cb) {
1116 : 0 : (void)cb(NULL, 0, ctx);
1117 : : }
1118 : :
1119 : : return out_len;
1120 : : }
|