services/formatted_output.html · services/formatted_output.rst 공식 원문 ↗

Zephyr 3.7.0 · OS Services · Cbprintf

Formatted Output

작은 embedded system에서 C99 format을 callback으로 출력하고 argument state를 안전하게 package합니다.

Official pathservices/formatted_output.html
Source fileservices/formatted_output.rst
Source versionZephyr 3.7.0
TranslationFull · reviewed

본문 기준: Zephyr 3.7.0 LTS3 · 이후 유지보수 패치는 별도입니다.

Part 1

요약·해설

Formatter Kconfig, transient·self-contained variant, alignment, static packaging의 char pointer 위험과 package memory layout을 설명합니다.

Formatter

cbprintf

Deferred

Package + va_list layout

Safety

Alignment · pointer checks

Part 2

접을 수 있는 영어 원문 전체

영어 원문 전체 펼치기
원문 SHA-256 89858038CDFE04BFB4910BF68F510664BE5D83611F2B785240456374AB873B20
.. _formatted_output:

Formatted Output
################

Applications as well as Zephyr itself requires infrastructure to format
values for user consumption.  The standard C99 library ``*printf()``
functionality fulfills this need for streaming output devices or memory
buffers, but in an embedded system devices may not accept streamed data
and memory may not be available to store the formatted output.

Internal Zephyr API traditionally provided this both for
:c:func:`printk` and for Zephyr's internal minimal libc, but with
separate internal interfaces.  Logging, tracing, shell, and other
applications made use of either these APIs or standard libc routines
based on build options.

The :c:func:`cbprintf` public APIs convert C99 format strings and
arguments, providing output produced one character at a time through a
callback mechanism, replacing the original internal functions and
providing support for almost all C99 format specifications.  Existing
use of ``s*printf()`` C libraries in Zephyr can be converted to
:c:func:`snprintfcb()` to avoid pulling in libc implementations.

Several Kconfig options control the set of features that are enabled,
allowing some control over features and memory usage:

* :kconfig:option:`CONFIG_CBPRINTF_FULL_INTEGRAL`
  or :kconfig:option:`CONFIG_CBPRINTF_REDUCED_INTEGRAL`
* :kconfig:option:`CONFIG_CBPRINTF_FP_SUPPORT`
* :kconfig:option:`CONFIG_CBPRINTF_FP_A_SUPPORT`
* :kconfig:option:`CONFIG_CBPRINTF_FP_ALWAYS_A`
* :kconfig:option:`CONFIG_CBPRINTF_N_SPECIFIER`

:kconfig:option:`CONFIG_CBPRINTF_LIBC_SUBSTS` can be used to provide functions
that behave like standard libc functions but use the selected cbprintf
formatter rather than pulling in another formatter from libc.

In addition :kconfig:option:`CONFIG_CBPRINTF_NANO` can be used to revert back to
the very space-optimized but limited formatter used for :c:func:`printk`
before this capability was added.

.. _cbprintf_packaging:

Cbprintf Packaging
******************

Typically, strings are formatted synchronously when a function from ``printf``
family is called. However, there are cases when it is beneficial that formatting
is deferred. In that case, a state (format string and arguments) must be captured.
Such state forms a self-contained package which contains format string and
arguments. Additionally, package may contain copies of strings which are
part of a format string (format string or any ``%s`` argument). Package primary
content resembles va_list stack frame thus standard formatting functions are
used to process a package. Since package contains data which is processed as
va_list frame, strict alignment must be maintained. Due to required padding,
size of the package depends on alignment. When package is copied, it should be
copied to a memory block with the same alignment as origin.

Package can have following variants:

* **Self-contained** - non read-only strings appended to the package. String can be
  formatted from such package as long as there is access to read-only string
  locations. Package may contain information where read-only strings are located
  within the package. That information can be used to convert packet to fully
  self-contained package.
* **Fully self-contained** - all strings are appended to the package. String can be
  formatted from such package without any external data.
* **Transient**- only arguments are stored. Package contain information
  where pointers to non read-only strings are located within the package. Optionally,
  it may contain read-only string location information. String can be formatted
  from such package as long as non read-only strings are still valid and read-only
  strings are accessible. Alternatively, package can be converted to **self-contained**
  package or **fully self-contained** if information about read-only string
  locations is present in the package.

Package can be created using two methods:

* runtime - using :c:func:`cbprintf_package` or :c:func:`cbvprintf_package`. This
  method scans format string and based on detected format specifiers builds the
  package.
* static - types of arguments are detected at compile time by the preprocessor
  and package is created as simple assignments to a provided memory. This method
  is significantly faster than runtime (more than 15 times) but has following
  limitations: requires ``_Generic`` keyword (C11 feature) to be supported by
  the compiler and cannot distinguish between ``%p`` and ``%s`` if char pointer
  is used. It treats all (unsigned) char pointers as ``%s`` thus it will attempt
  to append string to a package. It can be handled correctly during conversion
  from **transient** package to **self-contained** package using
  :c:macro:`CBPRINTF_PACKAGE_CONVERT_PTR_CHECK` flag. However, it requires access
  to the format string and it is not always possible thus it is recommended to
  cast char pointers used for ``%p`` to ``void *``. There is a logging warning
  generated by :c:func:`cbprintf_package_convert` called with
  :c:macro:`CBPRINTF_PACKAGE_CONVERT_PTR_CHECK` flag when char pointer is used with
  ``%p``.


Several Kconfig options control behavior of the packaging:

* :kconfig:option:`CONFIG_CBPRINTF_PACKAGE_LONGDOUBLE`
* :kconfig:option:`CONFIG_CBPRINTF_STATIC_PACKAGE_CHECK_ALIGNMENT`

Cbprintf package conversion
===========================

It is possible to convert package to a variant which contains more information, e.g
**transient** package can be converted to **self-contained**. Conversion to
**fully self-contained** package is possible if :c:macro:`CBPRINTF_PACKAGE_ADD_RO_STR_POS`
flag was used when package was created.

:c:func:`cbprintf_package_copy` is used to calculate space needed for the new
package and to copy and convert a package.

Cbprintf package format
=======================

Format of the package contains paddings which are platform specific. Package consists
of header which contains size of package (excluding appended strings) and number of
appended strings. It is followed by the arguments which contains alignment paddings
and resembles *va_list* stack frame. It is followed by data associated with character
pointer arguments used by the string which are not appended to the string (but may
be appended later by :c:func:`cbprinf_package_convert`). Finally, package, optionally,
contains appended strings. Each string contains 1 byte header which contains index
of the location where address argument is stored. During packaging address is set
to null and before string formatting it is updated to point to the current string
location within the package. Updating address argument must happen just before string
formatting since address changes whenever package is copied.

+------------------+-------------------------------------------------------------------------+
| Header           | 1 byte: Argument list size including header and *fmt* (in 32 bit words) |
|                  +-------------------------------------------------------------------------+
| sizeof(void \*)  | 1 byte: Number of strings appended to the package                       |
|                  +-------------------------------------------------------------------------+
|                  | 1 byte: Number of read-only string argument locations                   |
|                  +-------------------------------------------------------------------------+
|                  | 1 byte: Number of transient string argument locations                   |
|                  +-------------------------------------------------------------------------+
|                  | platform specific padding to sizeof(void \*)                            |
+------------------+-------------------------------------------------------------------------+
| Arguments        | Pointer to *fmt* (or null if *fmt* is appended to the package)          |
|                  +-------------------------------------------------------------------------+
|                  | (optional padding for platform specific alignment)                      |
|                  +-------------------------------------------------------------------------+
|                  | argument 0                                                              |
|                  +-------------------------------------------------------------------------+
|                  | (optional padding for platform specific alignment)                      |
|                  +-------------------------------------------------------------------------+
|                  | argument 1                                                              |
|                  +-------------------------------------------------------------------------+
|                  | ...                                                                     |
+------------------+-------------------------------------------------------------------------+
| String location  | Indexes of words within the package where read-only strings are located |
| information      +-------------------------------------------------------------------------+
| (optional)       | Pairs of argument index and argument location index where transient     |
|                  | strings are located                                                     |
+------------------+-------------------------------------------------------------------------+
| Appended         | 1 byte: Index within the package to the location of associated argument |
| strings          +-------------------------------------------------------------------------+
| (optional)       | Null terminated string                                                  |
|                  +-------------------------------------------------------------------------+
|                  | ...                                                                     |
+------------------+-------------------------------------------------------------------------+

.. warning::

  If :kconfig:option:`CONFIG_MINIMAL_LIBC` is selected in combination with
  :kconfig:option:`CONFIG_CBPRINTF_NANO` formatting with C standard library
  functions like ``printf`` or ``snprintf`` is limited.  Among other
  things the ``%n`` specifier, most format flags, precision control, and
  floating point are not supported.

.. _cbprintf_packaging_limitations:

Limitations and recommendations
===============================

* C11 ``_Generic`` support is required by the compiler to use static (fast) packaging.
* It is recommended to cast any character pointer used with ``%p`` format specifier to
  other pointer type (e.g. ``void *``). If format string is not accessible then only
  static packaging is possible and it will append all detected strings. Character pointer
  used for ``%p`` will be considered as string pointer. Copying from unexpected location
  can have serious consequences (e.g., memory fault or security violation).

API Reference
*************

.. doxygengroup:: cbprintf_apis

Part 3

한국어 전문 번역

Application과 Zephyr 자체에는 사람이 읽을 수 있도록 값을 format하는 기반 기능이 필요합니다. 표준 C99 library의 *printf() 계열은 streaming output device나 memory buffer에서 이 요구를 충족하지만, embedded system에서는 device가 stream data를 받지 못하거나 formatted output을 저장할 memory가 없을 수 있습니다.

기존 Zephyr internal API는 printk와 Zephyr minimal libc에 이 기능을 각각 별도 internal interface로 제공했습니다. Logging, tracing, shell과 다른 application은 build option에 따라 이 API나 표준 libc routine을 사용했습니다.

Public cbprintf API는 C99 format string과 argument를 변환하고 callback을 통해 한 번에 한 character씩 output합니다. 이 API는 예전 internal function을 대체하며 거의 모든 C99 format specification을 지원합니다. Zephyr에서 s*printf() C library를 사용하던 code는 snprintfcb()로 바꾸면 libc formatter implementation 전체를 끌어오지 않아도 됩니다.

활성화할 기능과 memory usage는 다음 Kconfig option으로 조절합니다.

  • CONFIG_CBPRINTF_FULL_INTEGRAL 또는 CONFIG_CBPRINTF_REDUCED_INTEGRAL
  • CONFIG_CBPRINTF_FP_SUPPORT
  • CONFIG_CBPRINTF_FP_A_SUPPORT
  • CONFIG_CBPRINTF_FP_ALWAYS_A
  • CONFIG_CBPRINTF_N_SPECIFIER

CONFIG_CBPRINTF_LIBC_SUBSTS는 표준 libc function처럼 동작하지만 별도 libc formatter 대신 선택한 cbprintf formatter를 쓰는 function을 제공합니다. CONFIG_CBPRINTF_NANO를 사용하면 이 기능이 도입되기 전 printk가 사용하던, 매우 작은 대신 제한적인 formatter로 돌아갈 수 있습니다.

Cbprintf Packaging

보통 printf family function을 호출하면 string을 동기적으로 format합니다. Format 작업을 뒤로 미루는 편이 유리한 경우에는 format string과 argument로 이루어진 state를 먼저 capture해야 합니다. 이 state가 self-contained package입니다. Package에는 format string과 argument가 들어가고, format string 자체나 %s argument에 쓰이는 string copy도 포함할 수 있습니다.

Package의 주요 내용은 va_list stack frame과 비슷하므로 standard formatting function으로 처리할 수 있습니다. va_list frame처럼 해석되는 data이기 때문에 alignment를 엄격히 유지해야 합니다. 필요한 padding 때문에 package size는 alignment에 따라 달라지며, package를 복사할 때도 원본과 같은 alignment의 memory block을 사용해야 합니다.

Package variant는 다음과 같습니다.

  • Self-contained: Read-only가 아닌 string을 package 뒤에 append합니다. Read-only string location에 접근할 수 있는 동안 format할 수 있습니다. Package 안의 read-only string 위치 정보가 있으면 fully self-contained package로 변환할 수 있습니다.
  • Fully self-contained: 모든 string을 package에 append합니다. 외부 data 없이도 string을 format할 수 있습니다.
  • Transient: Argument만 저장합니다. Read-only가 아닌 string pointer가 package 안 어디에 있는지 나타내는 정보가 들어 있고, read-only string location 정보도 선택적으로 포함할 수 있습니다. 외부 string이 아직 유효하고 접근 가능한 동안만 바로 format할 수 있으며, 필요한 위치 정보가 있으면 self-contained 또는 fully self-contained package로 변환할 수 있습니다.

Package 생성 방법은 두 가지입니다.

  • Runtime: cbprintf_package() 또는 cbvprintf_package()가 format string을 scan하고 발견한 format specifier를 바탕으로 package를 만듭니다.
  • Static: Preprocessor가 compile time에 argument type을 판별하고 제공된 memory에 단순 assignment로 package를 만듭니다. Runtime 방식보다 15배 이상 빠르지만 compiler가 C11 _Generic을 지원해야 합니다. 또한 character pointer를 썼을 때 %p와 %s를 구별하지 못해 모든 char *를 string으로 보고 append하려 합니다.

Transient package를 self-contained package로 변환할 때 CBPRINTF_PACKAGE_CONVERT_PTR_CHECK flag를 사용하면 character pointer의 %p 문제를 올바르게 처리할 수 있습니다. 그러나 이 검사는 format string에 접근할 수 있어야 합니다. 따라서 %p에 쓰는 character pointer는 void *로 cast하는 것이 좋습니다. 이 flag로 cbprintf_package_convert()를 호출했을 때 %p와 character pointer 조합이 발견되면 logging warning이 발생합니다.

Packaging 동작은 CONFIG_CBPRINTF_PACKAGE_LONGDOUBLE과 CONFIG_CBPRINTF_STATIC_PACKAGE_CHECK_ALIGNMENT으로 제어합니다.

Cbprintf package 변환

Package는 더 많은 정보를 담는 variant로 변환할 수 있습니다. 예를 들어 transient package를 self-contained package로 바꿀 수 있습니다. Package를 만들 때 CBPRINTF_PACKAGE_ADD_RO_STR_POS flag를 사용했다면 fully self-contained package로도 변환할 수 있습니다.

cbprintf_package_copy()는 새 package에 필요한 공간을 계산하고 package를 복사하면서 변환하는 데 사용합니다.

Cbprintf package format

Package format에는 platform-specific padding이 들어갑니다. Header에는 append된 string을 제외한 package size와 append된 string 개수가 있습니다. 그 뒤의 argument 영역은 alignment padding을 포함하며 va_list stack frame과 비슷합니다. 이어서 아직 append되지 않은 character pointer argument 관련 위치 정보가 오고, 마지막에는 optional appended string이 옵니다.

각 appended string은 연결된 address argument가 저장된 위치 index를 담은 1-byte header를 가집니다. Packaging 중에는 address를 null로 두고, 실제 formatting 직전에 package 안 현재 string 위치를 가리키도록 갱신합니다. Package를 복사할 때마다 address가 달라지므로 이 갱신은 반드시 formatting 직전에 해야 합니다.

Cbprintf package memory layout
Header
sizeof(void *)
1 byte: Header와 fmt를 포함한 argument list size, 32-bit word 단위
1 byte: Package에 append된 string 개수
1 byte: Read-only string argument location 개수
1 byte: Transient string argument location 개수
sizeof(void *)까지 platform-specific padding
Argumentsfmt pointer. fmt가 package에 append됐으면 null
Platform-specific alignment를 위한 optional padding
Argument 0
Platform-specific alignment를 위한 optional padding
Argument 1
...
String location information
(optional)
Read-only string이 위치한 package 내부 word index
Transient string의 argument index와 argument location index pair
Appended strings
(optional)
1 byte: 연결된 argument가 저장된 package 내부 location index
Null-terminated string
...

제한과 권장 사항

  • Static fast packaging을 사용하려면 compiler의 C11 _Generic 지원이 필요합니다.
  • %p format specifier에 character pointer를 쓸 때는 void * 같은 다른 pointer type으로 cast하는 것이 좋습니다. Format string에 접근할 수 없으면 static packaging은 그 pointer를 string으로 오인해 예상하지 못한 위치에서 memory를 복사할 수 있으며, memory fault나 security violation으로 이어질 수 있습니다.

API Reference

Formatted output과 package 관련 API는 cbprintf_apis Doxygen group에 정의돼 있습니다.

Source

출처

영어 원문에는 문단, 문서 지시문, 표, 코드, 코드 심벌, 경로를 그대로 보존했습니다.