Debian Codegraph @

crt/s2n/scripts/s2n_safety_macros.py

raw symbols SCIP
1 import textwrap
2
3 copyright = """
4 /*
5 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License").
8 * You may not use this file except in compliance with the License.
9 * A copy of the License is located at
10 *
11 * http://aws.amazon.com/apache2.0
12 *
13 * or in the "license" file accompanying this file. This file is distributed
14 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
15 * express or implied. See the License for the specific language governing
16 * permissions and limitations under the License.
17 */
18 """
19
20 header = copyright + """
21 #pragma once
22
23 /**
24 * DO NOT DIRECTLY MODIFY THIS FILE:
25 *
26 * The code in this file is generated from scripts/s2n_safety_macros.py and any modifications
27 * should be in there.
28 */
29
30 /* clang-format off */
31
32 #include "error/s2n_errno.h"
33 #include "utils/s2n_ensure.h"
34 #include "utils/s2n_result.h"
35
36 /**
37 * The goal of s2n_safety is to provide helpers to perform common
38 * checks, which help with code readability.
39 */
40
41 /* Success signal value for OpenSSL functions */
42 #define _OSSL_SUCCESS 1
43
44 """
45
46 POSIX = dict(
47 name="POSIX",
48 is_ok="(result) > S2N_FAILURE",
49 ok="S2N_SUCCESS",
50 error="S2N_FAILURE",
51 ret="int",
52 ret_doc="`int` (POSIX error signal)",
53 expect_ok="EXPECT_SUCCESS",
54 expect_err="EXPECT_FAILURE_WITH_ERRNO",
55 )
56
57 PTR = dict(
58 name="PTR",
59 is_ok="(result) != NULL",
60 ok='"ok"',
61 error="NULL",
62 ret="const char*",
63 ret_doc="a pointer",
64 expect_ok="EXPECT_NOT_NULL",
65 expect_err="EXPECT_NULL_WITH_ERRNO",
66 )
67
68 RESULT = dict(
69 name="RESULT",
70 is_ok="s2n_result_is_ok(result)",
71 ok="S2N_RESULT_OK",
72 error="S2N_RESULT_ERROR",
73 ret="s2n_result",
74 ret_doc="`S2N_RESULT`",
75 expect_ok="EXPECT_OK",
76 expect_err="EXPECT_ERROR_WITH_ERRNO",
77 )
78
79 DEFAULT = dict(
80 name="",
81 is_ok=RESULT['is_ok'],
82 ok=RESULT['ok'],
83 error=RESULT['error'],
84 ret=RESULT['ret'],
85 expect_ok=RESULT['expect_ok'],
86 expect_err=RESULT['expect_err'],
87 )
88
89 # TODO add DEFAULT and remove RESULT once all PR branches are up-to-date
90 CONTEXTS = [RESULT, POSIX, PTR]
91
92 max_prefix_len = max(map(lambda c: len(c['name']), CONTEXTS))
93
94
95 def cmp_check(op):
96 return '__S2N_ENSURE((a) ' + op + ' (b), {bail}(S2N_ERR_SAFETY))'
97
98 # TODO ensure type compatibility
99 # return '''\\
100 # do {{ \\
101 # static_assert(__builtin_types_compatible_p(__typeof(a), __typeof(b)), "types do not match"); \\
102 # __typeof(a) __tmp_a = ( a ); \\
103 # __typeof(b) __tmp_b = ( b ); \\
104 # __S2N_ENSURE(__tmp_a ''' + op + ''' __tmp_b, {bail}(S2N_ERR_SAFETY)); \\
105 # }} while(0)
106 # '''
107
108
109 MACROS = {
110 'BAIL(error)': dict(
111 doc='Sets the global `s2n_errno` to `error` and returns with an `{error}`',
112 impl='do {{ _S2N_ERROR((error)); __S2N_ENSURE_CHECKED_RETURN({error}); }} while (0)',
113 harness='''
114 static {ret} {bail}_harness()
115 {{
116 {bail}(S2N_ERR_SAFETY);
117 return {ok};
118 }}
119 ''',
120 tests=[
121 '{expect_err}({bail}_harness(), S2N_ERR_SAFETY);'
122 ],
123 ),
124 'ENSURE(condition, error)': dict(
125 doc='Ensures the `condition` is `true`, otherwise the function will `{bail}` with `error`',
126 impl='__S2N_ENSURE((condition), {bail}(error))',
127 harness='''
128 static {ret} {prefix}ENSURE_harness(bool is_ok)
129 {{
130 {prefix}ENSURE(is_ok, S2N_ERR_SAFETY);
131 return {ok};
132 }}
133 ''',
134 tests=[
135 '{expect_ok}({prefix}ENSURE_harness(true));',
136 '{expect_err}({prefix}ENSURE_harness(false), S2N_ERR_SAFETY);'
137 ],
138 ),
139 'DEBUG_ENSURE(condition, error)': dict(
140 doc='''
141 Ensures the `condition` is `true`, otherwise the function will `{bail}` with `error`
142
143 NOTE: The condition will _only_ be checked when the code is compiled in debug mode.
144 In release mode, the check is removed.
145 ''',
146 impl='__S2N_ENSURE_DEBUG((condition), {bail}(error))',
147 harness='''
148 static {ret} {prefix}DEBUG_ENSURE_harness(bool is_ok)
149 {{
150 {prefix}DEBUG_ENSURE(is_ok, S2N_ERR_SAFETY);
151 return {ok};
152 }}
153 ''',
154 tests=[
155 '{expect_ok}({prefix}DEBUG_ENSURE_harness(true));',
156 '#ifdef NDEBUG',
157 '{expect_ok}({prefix}DEBUG_ENSURE_harness(false));',
158 '#else',
159 '{expect_err}({prefix}DEBUG_ENSURE_harness(false), S2N_ERR_SAFETY);',
160 '#endif',
161 ],
162 ),
163 'ENSURE_OK(result, error)': dict(
164 doc='''
165 Ensures `{is_ok}`, otherwise the function will `{bail}` with `error`
166
167 This can be useful for overriding the global `s2n_errno`
168 ''',
169 impl='__S2N_ENSURE({is_ok}, {bail}(error))',
170 harness='''
171 static {ret} {prefix}ENSURE_OK_harness(bool is_ok)
172 {{
173 {prefix}ENSURE_OK({prefix}ENSURE_harness(is_ok), S2N_ERR_IO);
174 return {ok};
175 }}
176 ''',
177 tests=[
178 '{expect_ok}({prefix}ENSURE_OK_harness(true));',
179 '{expect_err}({prefix}ENSURE_OK_harness(false), S2N_ERR_IO);'
180 ],
181 ),
182 'ENSURE_GTE(a, b)': dict(
183 doc='''
184 Ensures `a` is greater than or equal to `b`, otherwise the function will `{bail}` with a `S2N_ERR_SAFETY` error
185 ''',
186 impl=cmp_check('>='),
187 harness='''
188 static {ret} {prefix}ENSURE_GTE_harness_uint32(uint32_t a, uint32_t b)
189 {{
190 {prefix}ENSURE_GTE(a, b);
191 /* test the inverse */
192 {prefix}ENSURE_LTE(b, a);
193 return {ok};
194 }}
195
196 static {ret} {prefix}ENSURE_GTE_harness_int32(int32_t a, int32_t b)
197 {{
198 {prefix}ENSURE_GTE(a, b);
199 /* test the inverse */
200 {prefix}ENSURE_LTE(b, a);
201 return {ok};
202 }}
203 ''',
204 tests=[
205 '{expect_ok}({prefix}ENSURE_GTE_harness_uint32(0, 0));',
206 '{expect_ok}({prefix}ENSURE_GTE_harness_uint32(1, 0));',
207 '{expect_err}({prefix}ENSURE_GTE_harness_uint32(0, 1), S2N_ERR_SAFETY);',
208 '{expect_ok}({prefix}ENSURE_GTE_harness_int32(-1, -2));',
209 '{expect_ok}({prefix}ENSURE_GTE_harness_int32(-1, -1));',
210 '{expect_err}({prefix}ENSURE_GTE_harness_int32(-2, -1), S2N_ERR_SAFETY);',
211 ],
212 ),
213 'ENSURE_LTE(a, b)': dict(
214 doc='''
215 Ensures `a` is less than or equal to `b`, otherwise the function will `{bail}` with a `S2N_ERR_SAFETY` error
216 ''',
217 impl=cmp_check('<='),
218 harness='''
219 static {ret} {prefix}ENSURE_LTE_harness_uint32(uint32_t a, uint32_t b)
220 {{
221 {prefix}ENSURE_LTE(a, b);
222 /* test the inverse */
223 {prefix}ENSURE_GTE(b, a);
224 return {ok};
225 }}
226
227 static {ret} {prefix}ENSURE_LTE_harness_int32(int32_t a, int32_t b)
228 {{
229 {prefix}ENSURE_LTE(a, b);
230 /* test the inverse */
231 {prefix}ENSURE_GTE(b, a);
232 return {ok};
233 }}
234 ''',
235 tests=[
236 '{expect_ok}({prefix}ENSURE_LTE_harness_uint32(0, 0));',
237 '{expect_ok}({prefix}ENSURE_LTE_harness_uint32(0, 1));',
238 '{expect_err}({prefix}ENSURE_LTE_harness_uint32(1, 0), S2N_ERR_SAFETY);',
239 '{expect_ok}({prefix}ENSURE_LTE_harness_int32(-2, -1));',
240 '{expect_ok}({prefix}ENSURE_LTE_harness_int32(-1, -1));',
241 '{expect_err}({prefix}ENSURE_LTE_harness_int32(-1, -2), S2N_ERR_SAFETY);',
242 ],
243 ),
244 'ENSURE_GT(a, b)': dict(
245 doc='''
246 Ensures `a` is greater than `b`, otherwise the function will `{bail}` with a `S2N_ERR_SAFETY` error
247 ''',
248 impl=cmp_check('>'),
249 harness='''
250 static {ret} {prefix}ENSURE_GT_harness_uint32(uint32_t a, uint32_t b)
251 {{
252 {prefix}ENSURE_GT(a, b);
253 /* test the inverse */
254 {prefix}ENSURE_LT(b, a);
255 return {ok};
256 }}
257
258 static {ret} {prefix}ENSURE_GT_harness_int32(int32_t a, int32_t b)
259 {{
260 {prefix}ENSURE_GT(a, b);
261 /* test the inverse */
262 {prefix}ENSURE_LT(b, a);
263 return {ok};
264 }}
265 ''',
266 tests=[
267 '{expect_err}({prefix}ENSURE_GT_harness_uint32(0, 0), S2N_ERR_SAFETY);',
268 '{expect_ok}({prefix}ENSURE_GT_harness_uint32(1, 0));',
269 '{expect_err}({prefix}ENSURE_GT_harness_uint32(0, 1), S2N_ERR_SAFETY);',
270 '{expect_ok}({prefix}ENSURE_GT_harness_int32(-1, -2));',
271 '{expect_err}({prefix}ENSURE_GT_harness_int32(-1, -1), S2N_ERR_SAFETY);',
272 '{expect_err}({prefix}ENSURE_GT_harness_int32(-2, -1), S2N_ERR_SAFETY);',
273 ],
274 ),
275 'ENSURE_LT(a, b)': dict(
276 doc='''
277 Ensures `a` is less than `b`, otherwise the function will `{bail}` with a `S2N_ERR_SAFETY` error
278 ''',
279 impl=cmp_check('<'),
280 harness='''
281 static {ret} {prefix}ENSURE_LT_harness_uint32(uint32_t a, uint32_t b)
282 {{
283 {prefix}ENSURE_LT(a, b);
284 /* test the inverse */
285 {prefix}ENSURE_GT(b, a);
286 return {ok};
287 }}
288
289 static {ret} {prefix}ENSURE_LT_harness_int32(int32_t a, int32_t b)
290 {{
291 {prefix}ENSURE_LT(a, b);
292 /* test the inverse */
293 {prefix}ENSURE_GT(b, a);
294 return {ok};
295 }}
296 ''',
297 tests=[
298 '{expect_err}({prefix}ENSURE_LT_harness_uint32(0, 0), S2N_ERR_SAFETY);',
299 '{expect_ok}({prefix}ENSURE_LT_harness_uint32(0, 1));',
300 '{expect_err}({prefix}ENSURE_LT_harness_uint32(1, 0), S2N_ERR_SAFETY);',
301 '{expect_ok}({prefix}ENSURE_LT_harness_int32(-2, -1));',
302 '{expect_err}({prefix}ENSURE_LT_harness_int32(-1, -1), S2N_ERR_SAFETY);',
303 '{expect_err}({prefix}ENSURE_LT_harness_int32(-1, -2), S2N_ERR_SAFETY);',
304 ],
305 ),
306 'ENSURE_EQ(a, b)': dict(
307 doc='''
308 Ensures `a` is equal to `b`, otherwise the function will `{bail}` with a `S2N_ERR_SAFETY` error
309 ''',
310 impl=cmp_check('=='),
311 harness='''
312 static {ret} {prefix}ENSURE_EQ_harness_uint32(uint32_t a, uint32_t b)
313 {{
314 {prefix}ENSURE_EQ(a, b);
315 {prefix}ENSURE_EQ(b, a);
316 return {ok};
317 }}
318
319 static {ret} {prefix}ENSURE_EQ_harness_int32(int32_t a, int32_t b)
320 {{
321 {prefix}ENSURE_EQ(a, b);
322 {prefix}ENSURE_EQ(b, a);
323 return {ok};
324 }}
325 ''',
326 tests=[
327 '{expect_ok}({prefix}ENSURE_EQ_harness_uint32(0, 0));',
328 '{expect_err}({prefix}ENSURE_EQ_harness_uint32(1, 0), S2N_ERR_SAFETY);',
329 '{expect_ok}({prefix}ENSURE_EQ_harness_int32(-1, -1));',
330 '{expect_err}({prefix}ENSURE_EQ_harness_int32(-2, -1), S2N_ERR_SAFETY);',
331 ],
332 ),
333 'ENSURE_NE(a, b)': dict(
334 doc='''
335 Ensures `a` is not equal to `b`, otherwise the function will `{bail}` with a `S2N_ERR_SAFETY` error
336 ''',
337 impl=cmp_check('!='),
338 harness='''
339 static {ret} {prefix}ENSURE_NE_harness_uint32(uint32_t a, uint32_t b)
340 {{
341 {prefix}ENSURE_NE(a, b);
342 {prefix}ENSURE_NE(b, a);
343 return {ok};
344 }}
345
346 static {ret} {prefix}ENSURE_NE_harness_int32(int32_t a, int32_t b)
347 {{
348 {prefix}ENSURE_NE(a, b);
349 {prefix}ENSURE_NE(b, a);
350 return {ok};
351 }}
352 ''',
353 tests=[
354 '{expect_ok}({prefix}ENSURE_NE_harness_uint32(1, 0));',
355 '{expect_err}({prefix}ENSURE_NE_harness_uint32(0, 0), S2N_ERR_SAFETY);',
356 '{expect_ok}({prefix}ENSURE_NE_harness_int32(-2, -1));',
357 '{expect_err}({prefix}ENSURE_NE_harness_int32(-1, -1), S2N_ERR_SAFETY);',
358 ],
359 ),
360 'ENSURE_INCLUSIVE_RANGE(min, n, max)': dict(
361 doc='Ensures `min <= n <= max`, otherwise the function will `{bail}` with `S2N_ERR_SAFETY`',
362 impl=''' \\
363 do {{ \\
364 __typeof(n) __tmp_n = ( n ); \\
365 __typeof(n) __tmp_min = ( min ); \\
366 __typeof(n) __tmp_max = ( max ); \\
367 {prefix}ENSURE_GTE(__tmp_n, __tmp_min); \\
368 {prefix}ENSURE_LTE(__tmp_n, __tmp_max); \\
369 }} while(0)''',
370 harness='''
371 static {ret} {prefix}ENSURE_INCLUSIVE_RANGE_harness_uint32(uint32_t a, uint32_t b, uint32_t c)
372 {{
373 {prefix}ENSURE_INCLUSIVE_RANGE(a, b, c);
374 return {ok};
375 }}
376
377 static {ret} {prefix}ENSURE_INCLUSIVE_RANGE_harness_int32(int32_t a, int32_t b, int32_t c)
378 {{
379 {prefix}ENSURE_INCLUSIVE_RANGE(a, b, c);
380 return {ok};
381 }}
382 ''',
383 tests=[
384 '{expect_err}({prefix}ENSURE_INCLUSIVE_RANGE_harness_uint32(1, 0, 2), S2N_ERR_SAFETY);',
385 '{expect_ok}({prefix}ENSURE_INCLUSIVE_RANGE_harness_uint32(1, 1, 2));',
386 '{expect_ok}({prefix}ENSURE_INCLUSIVE_RANGE_harness_uint32(1, 2, 2));',
387 '{expect_err}({prefix}ENSURE_INCLUSIVE_RANGE_harness_uint32(1, 3, 2), S2N_ERR_SAFETY);',
388
389 '{expect_err}({prefix}ENSURE_INCLUSIVE_RANGE_harness_int32(-2, -3, -1), S2N_ERR_SAFETY);',
390 '{expect_ok}({prefix}ENSURE_INCLUSIVE_RANGE_harness_int32(-2, -2, -1));',
391 '{expect_ok}({prefix}ENSURE_INCLUSIVE_RANGE_harness_int32(-2, -1, -1));',
392 '{expect_err}({prefix}ENSURE_INCLUSIVE_RANGE_harness_int32(-2, 0, -1), S2N_ERR_SAFETY);',
393 ],
394 ),
395 'ENSURE_EXCLUSIVE_RANGE(min, n, max)': dict(
396 doc='Ensures `min < n < max`, otherwise the function will `{bail}` with `S2N_ERR_SAFETY`',
397 impl=''' \\
398 do {{ \\
399 __typeof(n) __tmp_n = ( n ); \\
400 __typeof(n) __tmp_min = ( min ); \\
401 __typeof(n) __tmp_max = ( max ); \\
402 {prefix}ENSURE_GT(__tmp_n, __tmp_min); \\
403 {prefix}ENSURE_LT(__tmp_n, __tmp_max); \\
404 }} while(0)''',
405 harness='''
406 static {ret} {prefix}ENSURE_EXCLUSIVE_RANGE_harness_uint32(uint32_t a, uint32_t b, uint32_t c)
407 {{
408 {prefix}ENSURE_EXCLUSIVE_RANGE(a, b, c);
409 return {ok};
410 }}
411
412 static {ret} {prefix}ENSURE_EXCLUSIVE_RANGE_harness_int32(int32_t a, int32_t b, int32_t c)
413 {{
414 {prefix}ENSURE_EXCLUSIVE_RANGE(a, b, c);
415 return {ok};
416 }}
417 ''',
418 tests=[
419 '{expect_err}({prefix}ENSURE_EXCLUSIVE_RANGE_harness_uint32(1, 0, 3), S2N_ERR_SAFETY);',
420 '{expect_err}({prefix}ENSURE_EXCLUSIVE_RANGE_harness_uint32(1, 1, 3), S2N_ERR_SAFETY);',
421 '{expect_ok}({prefix}ENSURE_EXCLUSIVE_RANGE_harness_uint32(1, 2, 3));',
422 '{expect_err}({prefix}ENSURE_EXCLUSIVE_RANGE_harness_uint32(1, 3, 3), S2N_ERR_SAFETY);',
423 '{expect_err}({prefix}ENSURE_EXCLUSIVE_RANGE_harness_uint32(1, 4, 3), S2N_ERR_SAFETY);',
424
425 '{expect_err}({prefix}ENSURE_EXCLUSIVE_RANGE_harness_int32(-3, -4, -1), S2N_ERR_SAFETY);',
426 '{expect_err}({prefix}ENSURE_EXCLUSIVE_RANGE_harness_int32(-3, -3, -1), S2N_ERR_SAFETY);',
427 '{expect_ok}({prefix}ENSURE_EXCLUSIVE_RANGE_harness_int32(-3, -2, -1));',
428 '{expect_err}({prefix}ENSURE_EXCLUSIVE_RANGE_harness_int32(-3, -1, -1), S2N_ERR_SAFETY);',
429 '{expect_err}({prefix}ENSURE_EXCLUSIVE_RANGE_harness_int32(-3, 0, -1), S2N_ERR_SAFETY);',
430 ],
431 ),
432 'ENSURE_REF(x)': dict(
433 doc='Ensures `x` is a readable reference, otherwise the function will `{bail}` with `S2N_ERR_NULL`',
434 impl='__S2N_ENSURE(S2N_OBJECT_PTR_IS_READABLE(x), {bail}(S2N_ERR_NULL))',
435 harness='''
436 static {ret} {prefix}ENSURE_REF_harness(const char* str)
437 {{
438 {prefix}ENSURE_REF(str);
439 return {ok};
440 }}
441 ''',
442 tests=[
443 '{expect_ok}({prefix}ENSURE_REF_harness(""));',
444 '{expect_ok}({prefix}ENSURE_REF_harness("ok"));',
445 '{expect_err}({prefix}ENSURE_REF_harness(NULL), S2N_ERR_NULL);',
446 ],
447 ),
448 'ENSURE_MUT(x)': dict(
449 doc='Ensures `x` is a mutable reference, otherwise the function will `{bail}` with `S2N_ERR_NULL`',
450 impl='__S2N_ENSURE(S2N_OBJECT_PTR_IS_WRITABLE(x), {bail}(S2N_ERR_NULL))',
451 harness='''
452 static {ret} {prefix}ENSURE_MUT_harness(uint32_t* v)
453 {{
454 {prefix}ENSURE_MUT(v);
455 return {ok};
456 }}
457 ''',
458 tests=[
459 'uint32_t {prefix}ensure_mut_test = 0;',
460 '{expect_ok}({prefix}ENSURE_MUT_harness(&{prefix}ensure_mut_test));',
461 '{prefix}ensure_mut_test = 1;',
462 '{expect_ok}({prefix}ENSURE_MUT_harness(&{prefix}ensure_mut_test));',
463 '{expect_err}({prefix}ENSURE_MUT_harness(NULL), S2N_ERR_NULL);',
464 ],
465 ),
466 'PRECONDITION(result)': dict(
467 doc='''
468 Ensures the `result` is `S2N_RESULT_OK`, otherwise the function will return an error signal
469
470 `{prefix}PRECONDITION` should be used at the beginning of a function to make assertions about
471 the provided arguments. By default, it is functionally equivalent to `{prefix}GUARD_RESULT(result)`
472 but can be altered by a testing environment to provide additional guarantees.
473 ''',
474 impl='{prefix}GUARD_RESULT(__S2N_ENSURE_PRECONDITION((result)))',
475 harness='''
476 static S2N_RESULT {prefix}PRECONDITION_harness_check(bool is_ok)
477 {{
478 RESULT_ENSURE(is_ok, S2N_ERR_SAFETY);
479 return S2N_RESULT_OK;
480 }}
481
482 static {ret} {prefix}PRECONDITION_harness(s2n_result result)
483 {{
484 {prefix}PRECONDITION(result);
485 return {ok};
486 }}
487 ''',
488 tests=[
489 '{expect_ok}({prefix}PRECONDITION_harness({prefix}PRECONDITION_harness_check(true)));',
490 '{expect_err}({prefix}PRECONDITION_harness({prefix}PRECONDITION_harness_check(false)), S2N_ERR_SAFETY);',
491 ],
492 ),
493 'POSTCONDITION(result)': dict(
494 doc='''
495 Ensures the `result` is `S2N_RESULT_OK`, otherwise the function will return an error signal
496
497 NOTE: The condition will _only_ be checked when the code is compiled in debug mode.
498 In release mode, the check is removed.
499
500 `{prefix}POSTCONDITION` should be used at the end of a function to make assertions about
501 the resulting state. In debug mode, it is functionally equivalent to `{prefix}GUARD_RESULT(result)`.
502 In production builds, it becomes a no-op. This can also be altered by a testing environment
503 to provide additional guarantees.
504 ''',
505 impl='{prefix}GUARD_RESULT(__S2N_ENSURE_POSTCONDITION((result)))',
506 harness='''
507 static S2N_RESULT {prefix}POSTCONDITION_harness_check(bool is_ok)
508 {{
509 RESULT_ENSURE(is_ok, S2N_ERR_SAFETY);
510 return S2N_RESULT_OK;
511 }}
512
513 static {ret} {prefix}POSTCONDITION_harness(s2n_result result)
514 {{
515 {prefix}POSTCONDITION(result);
516 return {ok};
517 }}
518 ''',
519 tests=[
520 '{expect_ok}({prefix}POSTCONDITION_harness({prefix}POSTCONDITION_harness_check(true)));',
521 '#ifdef NDEBUG',
522 '{expect_ok}({prefix}POSTCONDITION_harness({prefix}POSTCONDITION_harness_check(false)));',
523 '#else',
524 '{expect_err}({prefix}POSTCONDITION_harness({prefix}POSTCONDITION_harness_check(false)), S2N_ERR_SAFETY);',
525 '#endif',
526 ],
527 ),
528 'CHECKED_MEMCPY(destination, source, len)': dict(
529 doc='''
530 Performs a safer memcpy.
531
532 The following checks are performed:
533
534 * `destination` is non-null
535 * `source` is non-null
536
537 Callers will still need to ensure the following:
538
539 * The size of the data pointed to by both the `destination` and `source` parameters,
540 shall be at least `len` bytes.
541 ''',
542 impl='__S2N_ENSURE_SAFE_MEMMOVE((destination), (source), (len), {prefix}ENSURE_REF)',
543 harness='''
544 static {ret} {prefix}CHECKED_MEMCPY_harness(uint32_t* dest, uint32_t* source, size_t len)
545 {{
546 {prefix}CHECKED_MEMCPY(dest, source, len);
547 return {ok};
548 }}
549 ''',
550 tests=[
551 'uint32_t {prefix}_checked_memcpy_dest = 1;',
552 'uint32_t {prefix}_checked_memcpy_source = 2;',
553 '{expect_ok}({prefix}CHECKED_MEMCPY_harness(&{prefix}_checked_memcpy_dest, &{prefix}_checked_memcpy_source, 0));',
554 'EXPECT_EQUAL({prefix}_checked_memcpy_dest, 1);',
555 '{expect_err}({prefix}CHECKED_MEMCPY_harness(NULL, &{prefix}_checked_memcpy_source, 4), S2N_ERR_NULL);',
556 '{expect_err}({prefix}CHECKED_MEMCPY_harness(&{prefix}_checked_memcpy_dest, NULL, 4), S2N_ERR_NULL);',
557 '{expect_ok}({prefix}CHECKED_MEMCPY_harness(&{prefix}_checked_memcpy_dest, &{prefix}_checked_memcpy_source, 4));',
558 'EXPECT_EQUAL({prefix}_checked_memcpy_dest, {prefix}_checked_memcpy_source);'
559 ],
560 ),
561 'CHECKED_MEMSET(destination, value, len)': dict(
562 doc='''
563 Performs a safer memset
564
565 The following checks are performed:
566
567 * `destination` is non-null
568
569 Callers will still need to ensure the following:
570
571 * The size of the data pointed to by the `destination` parameter shall be at least
572 `len` bytes.
573 ''',
574 impl='__S2N_ENSURE_SAFE_MEMSET((destination), (value), (len), {prefix}ENSURE_REF)',
575 harness='''
576 static {ret} {prefix}CHECKED_MEMSET_harness(uint32_t* dest, uint8_t value, size_t len)
577 {{
578 {prefix}CHECKED_MEMSET(dest, value, len);
579 return {ok};
580 }}
581 ''',
582 tests=[
583 'uint32_t {prefix}_checked_memset_dest = 1;',
584 '{expect_ok}({prefix}CHECKED_MEMSET_harness(&{prefix}_checked_memset_dest, 0x42, 0));',
585 'EXPECT_EQUAL({prefix}_checked_memset_dest, 1);',
586 '{expect_err}({prefix}CHECKED_MEMSET_harness(NULL, 0x42, 1), S2N_ERR_NULL);',
587 '{expect_ok}({prefix}CHECKED_MEMSET_harness(&{prefix}_checked_memset_dest, 0x42, 4));',
588 'EXPECT_EQUAL({prefix}_checked_memset_dest, 0x42424242);'
589 ],
590 ),
591 'GUARD(result)': dict(
592 doc='Ensures `{is_ok}`, otherwise the function will return `{error}`',
593 impl='__S2N_ENSURE({is_ok}, __S2N_ENSURE_CHECKED_RETURN({error}))',
594 harness='''
595 static {ret} {prefix}GUARD_harness({ret} result)
596 {{
597 {prefix}GUARD(result);
598 return {ok};
599 }}
600 ''',
601 tests=[
602 '{expect_ok}({prefix}GUARD_harness({prefix}ENSURE_harness(true)));',
603 '{expect_err}({prefix}GUARD_harness({prefix}ENSURE_harness(false)), S2N_ERR_SAFETY);',
604 ],
605 ),
606 'GUARD_OSSL(result, error)': dict(
607 doc='Ensures `result == _OSSL_SUCCESS`, otherwise the function will `{bail}` with `error`',
608 impl='__S2N_ENSURE((result) == _OSSL_SUCCESS, {bail}(error))',
609 harness='''
610 static {ret} {prefix}GUARD_OSSL_harness(int result, int error)
611 {{
612 {prefix}GUARD_OSSL(result, error);
613 return {ok};
614 }}
615 ''',
616 tests=[
617 '{expect_ok}({prefix}GUARD_OSSL_harness(1, S2N_ERR_SAFETY));',
618 '{expect_err}({prefix}GUARD_OSSL_harness(0, S2N_ERR_SAFETY), S2N_ERR_SAFETY);',
619 ],
620 ),
621 }
622
623 max_macro_len = max(map(len, MACROS.keys())) + 8
624
625
626 def push_macro(args):
627 macro_indent = ' ' * (max_macro_len - len(args['macro']))
628
629 h = ""
630 h += '/**\n'
631
632 for line in args['doc'].split('\n'):
633 h += ' *'
634 if len(line) > 0:
635 h += ' ' + line
636 h += '\n'
637
638 h += ' */\n'
639 h += '#define '
640 h += args['prefix']
641 h += args['macro']
642 h += args['indent']
643 h += macro_indent
644 h += args['impl'].format_map(args)
645 h += '\n\n'
646
647 return h
648
649
650 for context in CONTEXTS:
651 # initialize contexts
652 if len(context['name']) > 0:
653 context['prefix'] = context['name'] + '_'
654 context['suffix'] = '_' + context['name']
655 else:
656 context['prefix'] = ''
657 context['suffix'] = ''
658
659 context['indent'] = ' ' * (max_prefix_len - len(context['prefix']))
660 context['bail'] = '{prefix}BAIL'.format_map(context)
661
662 harnesses = ""
663 docs = """
664 [//]: # (DO NOT DIRECTLY MODIFY THIS FILE:)
665 [//]: # (The code in this file is generated from scripts/s2n_safety_macros.py and any modifications)
666 [//]: # (should be in there.)
667
668 # S2N Safety Macros
669 """
670 checks = []
671 deprecation_message = "DEPRECATED: all methods (except those in s2n.h) should return s2n_result."
672
673
674 def push_doc(args):
675 args['doc'] = textwrap.dedent(args['doc']).format_map(args).strip()
676
677 return textwrap.dedent("""
678 ### {prefix}{macro}
679
680 {doc}
681
682 """).format_map(args)
683
684
685 for context in CONTEXTS:
686 docs += textwrap.dedent("""
687 ## Macros for functions that return {ret_doc}
688
689 """).format_map(context)
690
691 for name, value in MACROS.items():
692 args = {'macro': name}
693 args.update(context)
694 args.update(value)
695
696 args['doc'] = textwrap.dedent(args['doc']).strip()
697 if context['ret'] != DEFAULT['ret']:
698 args['doc'] = (deprecation_message + "\n\n" + args['doc'])
699
700 docs += push_doc(args)
701 header += push_macro(args)
702
703 harness = value.get('harness', None)
704 if harness != None:
705 harnesses += textwrap.dedent(harness).format_map(context)
706 checks.append('/* ' + context['prefix'] + name + ' */')
707 assert len(value['tests']) > 0, "{} is missing tests".format(name)
708 for check in value['tests']:
709 checks.append(check.format_map(context))
710 checks.append('')
711
712 for other in CONTEXTS:
713 if len(other['suffix']) > 0:
714 doc = 'Ensures `{is_ok}`, otherwise the function will return `{error}`'
715 if other == PTR:
716 doc += '\n\nDoes not set s2n_errno to S2N_ERR_NULL, so is NOT a direct replacement for {prefix}ENSURE_REF.'
717 if context['ret'] != DEFAULT['ret']:
718 doc = (deprecation_message + "\n\n" + doc)
719
720 if other == context:
721 continue
722
723 impl = '__S2N_ENSURE({is_ok}, __S2N_ENSURE_CHECKED_RETURN({error}))'
724 args = {
725 'prefix': context['prefix'],
726 'suffix': other['suffix'],
727 'is_ok': other['is_ok'],
728 'ok': other['ok'],
729 'error': context['error'],
730 'indent': context['indent'],
731 'doc': doc,
732 'impl': impl,
733 }
734 args['macro'] = 'GUARD{suffix}(result)'.format_map(args)
735 docs += push_doc(args)
736 header += push_macro(args)
737
738
739 def cleanup(contents):
740 # Remove any unnecessary generated "X_GUARD_X"s, like "RESULT_GUARD_RESULT"
741 for context in CONTEXTS:
742 x_guard = "{name}_GUARD".format_map(context)
743 x_guard_x = "{name}_GUARD_{name}".format_map(context)
744 contents = contents.replace(x_guard_x, x_guard)
745 return contents
746
747
748 def write(f, contents):
749 contents = cleanup(contents)
750 with open(f, "w") as header_file:
751 header_file.write(contents)
752
753
754 write("utils/s2n_safety_macros.h", header)
755
756 test = copyright + '''
757 /* clang-format off */
758
759 #include "s2n_test.h"
760
761 #include "utils/s2n_safety.h"
762
763 /**
764 * DO NOT DIRECTLY MODIFY THIS FILE:
765 *
766 * The code in this file is generated from scripts/s2n_safety_macros.py and any modifications
767 * should be in there.
768 */
769
770 /* harnesses */
771 '''
772 test += harnesses
773 test += '''
774 int main(int argc, char **argv)
775 {
776 BEGIN_TEST();
777
778 '''
779 for check in checks:
780 if len(check) > 0:
781 test += ' ' + check
782 test += '\n'
783
784 test += '''
785 END_TEST();
786 return S2N_SUCCESS;
787 }
788 '''
789
790 write("tests/unit/s2n_safety_macros_test.c", test)
791
792 write("docs/SAFETY-MACROS.md", docs)