1 // Copyright 2020 The Pigweed Authors
2 //
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
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
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
13 // the License.
14 #pragma once
15 
16 #ifdef __cplusplus
17 
18 #include <cstddef>
19 #include <cstdint>
20 
21 #else
22 
23 #include <assert.h>
24 #include <stddef.h>
25 #include <stdint.h>
26 
27 #endif  // __cplusplus
28 
29 #include "pw_preprocessor/arguments.h"
30 #include "pw_preprocessor/compiler.h"
31 #include "pw_preprocessor/concat.h"
32 #include "pw_preprocessor/util.h"
33 #include "pw_tokenizer/internal/argument_types.h"
34 #include "pw_tokenizer/internal/tokenize_string.h"
35 
36 /// The type of the 32-bit token used in place of a string. Also available as
37 /// `pw::tokenizer::Token`.
38 typedef uint32_t pw_tokenizer_Token;
39 
40 // Strings may optionally be tokenized to a domain. Strings in different
41 // domains can be processed separately by the token database tools. Each domain
42 // in use must have a corresponding section declared in the linker script. See
43 // `pw_tokenizer_linker_sections.ld` for more details.
44 //
45 // The default domain is an empty string.
46 #define PW_TOKENIZER_DEFAULT_DOMAIN ""
47 
48 /// Converts a string literal to a `pw_tokenizer_Token` (`uint32_t`) token in a
49 /// standalone statement. C and C++ compatible. In C++, the string may be a
50 /// literal or a constexpr char array, including function variables like
51 /// `__func__`. In C, the argument must be a string literal. In either case, the
52 /// string must be null terminated, but may contain any characters (including
53 /// '\0').
54 ///
55 /// @code
56 ///
57 ///   constexpr uint32_t token = PW_TOKENIZE_STRING("Any string literal!");
58 ///
59 /// @endcode
60 #define PW_TOKENIZE_STRING(string_literal) \
61   PW_TOKENIZE_STRING_DOMAIN(PW_TOKENIZER_DEFAULT_DOMAIN, string_literal)
62 
63 /// Converts a string literal to a ``uint32_t`` token within an expression.
64 /// Requires C++.
65 ///
66 /// @code
67 ///
68 ///   DoSomething(PW_TOKENIZE_STRING_EXPR("Succeed"));
69 ///
70 /// @endcode
71 #define PW_TOKENIZE_STRING_EXPR(string_literal)                               \
72   [&] {                                                                       \
73     constexpr uint32_t lambda_ret_token = PW_TOKENIZE_STRING(string_literal); \
74     return lambda_ret_token;                                                  \
75   }()
76 
77 /// Tokenizes a string literal in a standalone statement using the specified
78 /// @rstref{domain <module-pw_tokenizer-domains>}. C and C++ compatible.
79 #define PW_TOKENIZE_STRING_DOMAIN(domain, string_literal) \
80   PW_TOKENIZE_STRING_MASK(domain, UINT32_MAX, string_literal)
81 
82 /// Tokenizes a string literal using the specified @rstref{domain
83 /// <module-pw_tokenizer-domains>} within an expression. Requires C++.
84 #define PW_TOKENIZE_STRING_DOMAIN_EXPR(domain, string_literal) \
85   [&] {                                                        \
86     constexpr uint32_t lambda_ret_token =                      \
87         PW_TOKENIZE_STRING_DOMAIN(domain, string_literal);     \
88     return lambda_ret_token;                                   \
89   }()
90 
91 /// Tokenizes a string literal in a standalone statement using the specified
92 /// @rstref{domain <module-pw_tokenizer-domains>} and @rstref{bit mask
93 /// <module-pw_tokenizer-masks>}. C and C++ compatible.
94 #define PW_TOKENIZE_STRING_MASK(domain, mask, string_literal)                \
95   /* assign to a variable */ _PW_TOKENIZER_MASK_TOKEN(mask, string_literal); \
96                                                                              \
97   static_assert(0 < (mask) && (mask) <= UINT32_MAX,                          \
98                 "Tokenizer masks must be non-zero uint32_t values.");        \
99                                                                              \
100   _PW_TOKENIZER_RECORD_ORIGINAL_STRING(                                      \
101       _PW_TOKENIZER_MASK_TOKEN(mask, string_literal), domain, string_literal)
102 
103 /// Tokenizes a string literal using the specified @rstref{domain
104 /// <module-pw_tokenizer-domains>} and @rstref{bit mask
105 /// <module-pw_tokenizer-masks>} within an expression. Requires C++.
106 #define PW_TOKENIZE_STRING_MASK_EXPR(domain, mask, string_literal) \
107   [&] {                                                            \
108     constexpr uint32_t lambda_ret_token =                          \
109         PW_TOKENIZE_STRING_MASK(domain, mask, string_literal);     \
110     return lambda_ret_token;                                       \
111   }()
112 
113 #define _PW_TOKENIZER_MASK_TOKEN(mask, string_literal) \
114   ((pw_tokenizer_Token)(mask)&PW_TOKENIZER_STRING_TOKEN(string_literal))
115 
116 /// Encodes a tokenized string and arguments to the provided buffer. The size of
117 /// the buffer is passed via a pointer to a `size_t`. After encoding is
118 /// complete, the `size_t` is set to the number of bytes written to the buffer.
119 ///
120 /// The macro's arguments are equivalent to the following function signature:
121 ///
122 /// @code
123 ///
124 ///   TokenizeToBuffer(void* buffer,
125 ///                    size_t* buffer_size_pointer,
126 ///                    const char* format,
127 ///                    ...);  // printf-style arguments
128 /// @endcode
129 ///
130 /// For example, the following encodes a tokenized string with a temperature to
131 /// a buffer. The buffer is passed to a function to send the message over a
132 /// UART.
133 ///
134 /// @code
135 ///
136 ///   uint8_t buffer[32];
137 ///   size_t size_bytes = sizeof(buffer);
138 ///   PW_TOKENIZE_TO_BUFFER(
139 ///       buffer, &size_bytes, "Temperature (C): %0.2f", temperature_c);
140 ///   MyProject_EnqueueMessageForUart(buffer, size);
141 ///
142 /// @endcode
143 ///
144 /// While `PW_TOKENIZE_TO_BUFFER` is very flexible, it must be passed a buffer,
145 /// which increases its code size footprint at the call site.
146 #define PW_TOKENIZE_TO_BUFFER(buffer, buffer_size_pointer, format, ...) \
147   PW_TOKENIZE_TO_BUFFER_DOMAIN(PW_TOKENIZER_DEFAULT_DOMAIN,             \
148                                buffer,                                  \
149                                buffer_size_pointer,                     \
150                                format,                                  \
151                                __VA_ARGS__)
152 
153 /// Same as @c_macro{PW_TOKENIZE_TO_BUFFER}, but tokenizes to the specified
154 /// @rstref{domain <module-pw_tokenizer-domains>}.
155 #define PW_TOKENIZE_TO_BUFFER_DOMAIN(                 \
156     domain, buffer, buffer_size_pointer, format, ...) \
157   PW_TOKENIZE_TO_BUFFER_MASK(                         \
158       domain, UINT32_MAX, buffer, buffer_size_pointer, format, __VA_ARGS__)
159 
160 /// Same as @c_macro{PW_TOKENIZE_TO_BUFFER_DOMAIN}, but applies a
161 /// @rstref{bit mask <module-pw_tokenizer-masks>} to the token.
162 #define PW_TOKENIZE_TO_BUFFER_MASK(                               \
163     domain, mask, buffer, buffer_size_pointer, format, ...)       \
164   do {                                                            \
165     PW_TOKENIZE_FORMAT_STRING(domain, mask, format, __VA_ARGS__); \
166     _pw_tokenizer_ToBuffer(buffer,                                \
167                            buffer_size_pointer,                   \
168                            _pw_tokenizer_token,                   \
169                            PW_TOKENIZER_ARG_TYPES(__VA_ARGS__)    \
170                                PW_COMMA_ARGS(__VA_ARGS__));       \
171   } while (0)
172 
173 /// Converts a series of arguments to a compact format that replaces the format
174 /// string literal. Evaluates to a `pw_tokenizer_ArgTypes` value.
175 ///
176 /// Depending on the size of `pw_tokenizer_ArgTypes`, the bottom 4 or 6 bits
177 /// store the number of arguments and the remaining bits store the types, two
178 /// bits per type. The arguments are not evaluated; only their types are used.
179 #define PW_TOKENIZER_ARG_TYPES(...) \
180   PW_DELEGATE_BY_ARG_COUNT(_PW_TOKENIZER_TYPES_, __VA_ARGS__)
181 
182 PW_EXTERN_C_START
183 
184 // These functions encode the tokenized strings. These should not be called
185 // directly. Instead, use the corresponding PW_TOKENIZE_TO_* macros above.
186 void _pw_tokenizer_ToBuffer(void* buffer,
187                             size_t* buffer_size_bytes,  // input and output arg
188                             pw_tokenizer_Token token,
189                             pw_tokenizer_ArgTypes types,
190                             ...);
191 
192 // This empty function allows the compiler to check the format string.
193 static inline void pw_tokenizer_CheckFormatString(const char* format, ...)
194     PW_PRINTF_FORMAT(1, 2);
195 
pw_tokenizer_CheckFormatString(const char * format,...)196 static inline void pw_tokenizer_CheckFormatString(const char* format, ...) {
197   (void)format;
198 }
199 
200 PW_EXTERN_C_END
201 
202 /// Tokenizes a format string with optional arguments and sets the
203 /// `_pw_tokenizer_token` variable to the token. Must be used in its own scope,
204 /// since the same variable is used in every invocation.
205 ///
206 /// The tokenized string uses the specified @rstref{tokenization domain
207 /// <module-pw_tokenizer-domains>}.  Use `PW_TOKENIZER_DEFAULT_DOMAIN` for the
208 /// default. The token also may be masked; use `UINT32_MAX` to keep all bits.
209 ///
210 /// This macro checks that the printf-style format string matches the arguments,
211 /// stores the format string in a special section, and calculates the string's
212 /// token at compile time.
213 // clang-format off
214 #define PW_TOKENIZE_FORMAT_STRING(domain, mask, format, ...)                  \
215   if (0) { /* Do not execute to prevent double evaluation of the arguments. */ \
216     pw_tokenizer_CheckFormatString(format PW_COMMA_ARGS(__VA_ARGS__));         \
217   }                                                                            \
218                                                                                \
219   /* Check that the macro is invoked with a supported number of arguments. */  \
220   static_assert(                                                               \
221       PW_FUNCTION_ARG_COUNT(__VA_ARGS__) <= PW_TOKENIZER_MAX_SUPPORTED_ARGS,   \
222       "Tokenized strings cannot have more than "                               \
223       PW_STRINGIFY(PW_TOKENIZER_MAX_SUPPORTED_ARGS) " arguments; "             \
224       PW_STRINGIFY(PW_FUNCTION_ARG_COUNT(__VA_ARGS__))                         \
225       " arguments were used for " #format " (" #__VA_ARGS__ ")");              \
226                                                                                \
227   /* Tokenize the string to a pw_tokenizer_Token at compile time. */           \
228   static _PW_TOKENIZER_CONST pw_tokenizer_Token _pw_tokenizer_token =          \
229       _PW_TOKENIZER_MASK_TOKEN(mask, format);                                  \
230                                                                                \
231   _PW_TOKENIZER_RECORD_ORIGINAL_STRING(_pw_tokenizer_token, domain, format)
232 
233 // clang-format on
234 
235 // Creates unique names to use for tokenized string entries and linker sections.
236 #define _PW_TOKENIZER_UNIQUE(prefix) PW_CONCAT(prefix, __LINE__, _, __COUNTER__)
237 
238 #ifdef __cplusplus
239 
240 #define _PW_TOKENIZER_CONST constexpr
241 
242 #define _PW_TOKENIZER_RECORD_ORIGINAL_STRING(token, domain, string)            \
243   alignas(1) static constexpr auto _PW_TOKENIZER_SECTION _PW_TOKENIZER_UNIQUE( \
244       _pw_tokenizer_string_entry_) =                                           \
245       ::pw::tokenizer::internal::MakeEntry(token, domain, string)
246 
247 namespace pw {
248 namespace tokenizer {
249 
250 using Token = ::pw_tokenizer_Token;
251 
252 }  // namespace tokenizer
253 }  // namespace pw
254 
255 #else
256 
257 #define _PW_TOKENIZER_CONST const
258 
259 #define _PW_TOKENIZER_RECORD_ORIGINAL_STRING(token, domain, string) \
260   _Alignas(1) static const _PW_TOKENIZER_STRING_ENTRY(token, domain, string)
261 
262 #endif  // __cplusplus
263 
264 // _PW_TOKENIZER_SECTION places the tokenized strings in a special .pw_tokenizer
265 // linker section. Host-side decoding tools read the strings and tokens from
266 // this section to build a database of tokenized strings.
267 //
268 // This section should be declared as type INFO so that it is excluded from the
269 // final binary. To declare the section, as well as the .pw_tokenizer.info
270 // metadata section, add the following to the linker script's SECTIONS command:
271 //
272 //   .pw_tokenizer.info 0x0 (INFO) :
273 //   {
274 //     KEEP(*(.pw_tokenizer.info))
275 //   }
276 //
277 //   .pw_tokenizer.entries 0x0 (INFO) :
278 //   {
279 //     KEEP(*(.pw_tokenizer.entries.*))
280 //   }
281 //
282 // A linker script snippet that provides these sections is provided in the file
283 // pw_tokenizer_linker_sections.ld. This file may be directly included into
284 // existing linker scripts.
285 //
286 // The tokenized string sections can also be managed without linker script
287 // modifications, though this is not recommended. The section can be extracted
288 // and removed from the ELF with objcopy:
289 //
290 //   objcopy --only-section .pw_tokenizer.* <ORIGINAL_ELF> <OUTPUT_ELF>
291 //   objcopy --remove-section .pw_tokenizer.* <ORIGINAL_ELF>
292 //
293 // OUTPUT_ELF will be an ELF with only the tokenized strings, and the original
294 // ELF file will have the sections removed.
295 //
296 // Without the above linker script modifications, the section garbage collection
297 // option (--gc-sections) removes the tokenized string sections. To avoid
298 // editing the target linker script, a separate metadata ELF can be linked
299 // without --gc-sections to preserve the tokenized data.
300 //
301 // pw_tokenizer is intended for use with ELF files only. Mach-O files (macOS
302 // executables) do not support section names longer than 16 characters, so a
303 // short, unused section name is used on macOS.
304 #ifdef __APPLE__
305 #define _PW_TOKENIZER_SECTION \
306   PW_KEEP_IN_SECTION(PW_STRINGIFY(_PW_TOKENIZER_UNIQUE(.pw.)))
307 #else
308 #define _PW_TOKENIZER_SECTION \
309   PW_KEEP_IN_SECTION(PW_STRINGIFY(_PW_TOKENIZER_UNIQUE(.pw_tokenizer.entries.)))
310 #endif  // __APPLE__
311