Debian Codegraph @

debian/rust-vendor/aws-lc-sys/aws-lc/crypto/err/err.c

raw
1 // Copyright (C) 1995-1998 Eric Young ([email protected])
2 // Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
4
5 // `strdup` was only officially added in C23:
6 // * https://en.cppreference.com/w/c/string/byte/strdup
7 // The following macros are needed to ensure its definition
8 // is provided by the headers.
9 #ifdef __STDC_ALLOC_LIB__
10 #define __STDC_WANT_LIB_EXT2__ 1
11 #else
12 #define _POSIX_C_SOURCE 200809L
13 #endif
14
15 // Ensure we can't call OPENSSL_malloc circularly.
16 #define _BORINGSSL_PROHIBIT_OPENSSL_MALLOC
17 #include <openssl/err.h>
18
19 #include <assert.h>
20 #include <errno.h>
21
22 #ifndef __STDC_FORMAT_MACROS
23 #define __STDC_FORMAT_MACROS
24 #endif
25 #include <inttypes.h>
26 #include <limits.h>
27 #include <stdarg.h>
28 #include <string.h>
29
30 #if defined(OPENSSL_WINDOWS)
31 OPENSSL_MSVC_PRAGMA(warning(push, 3))
32 #include <windows.h>
33 OPENSSL_MSVC_PRAGMA(warning(pop))
34 #endif
35
36 #include <openssl/mem.h>
37 #include <openssl/thread.h>
38
39 #include "../internal.h"
40 #include "./internal.h"
41
42
43 struct err_error_st {
44 // file contains the filename where the error occurred.
45 const char *file;
46 // data contains a NUL-terminated string with optional data. It is allocated
47 // with system |malloc| and must be freed with |free| (not |OPENSSL_free|)
48 char *data;
49 // packed contains the error library and reason, as packed by ERR_PACK.
50 uint32_t packed;
51 // line contains the line number where the error occurred.
52 uint16_t line;
53 // mark indicates a reversion point in the queue. See |ERR_pop_to_mark|.
54 unsigned mark : 1;
55 };
56
57 // ERR_STATE contains the per-thread, error queue.
58 typedef struct err_state_st {
59 // errors contains up to ERR_NUM_ERRORS - 1 most recent errors, organised as a
60 // ring buffer.
61 struct err_error_st errors[ERR_NUM_ERRORS];
62 // top contains the index of the most recent error. If |top| equals |bottom|
63 // then the queue is empty.
64 unsigned top;
65 // bottom contains the index before the least recent error in the queue.
66 unsigned bottom;
67
68 // to_free, if not NULL, contains a pointer owned by this structure that was
69 // previously a |data| pointer of one of the elements of |errors|.
70 void *to_free;
71 } ERR_STATE;
72
73 extern const uint32_t kOpenSSLReasonValues[];
74 extern const size_t kOpenSSLReasonValuesLen;
75 extern const char kOpenSSLReasonStringData[];
76
77 static char *strdup_libc_malloc(const char *str) {
78 // |strdup| is not in C until C23, so MSVC triggers deprecation warnings, and
79 // glibc and musl gate it on a feature macro. Reimplementing it is easier.
80 size_t len = strlen(str);
81 char *ret = malloc(len + 1);
82 if (ret != NULL) {
83 memcpy(ret, str, len + 1);
84 }
85 return ret;
86 }
87
88 // err_clear clears the given queued error.
89 static void err_clear(struct err_error_st *error) {
90 free(error->data);
91 OPENSSL_memset(error, 0, sizeof(struct err_error_st));
92 }
93
94 static void err_copy(struct err_error_st *dst, const struct err_error_st *src) {
95 err_clear(dst);
96 dst->file = src->file;
97 if (src->data != NULL) {
98 // We can't use OPENSSL_strdup because we don't want to call OPENSSL_malloc,
99 // which can affect the error stack.
100 dst->data = strdup_libc_malloc(src->data);
101 }
102 dst->packed = src->packed;
103 dst->line = src->line;
104 }
105
106
107 // global_next_library contains the next custom library value to return.
108 static int global_next_library = ERR_NUM_LIBS;
109
110 // global_next_library_mutex protects |global_next_library| from concurrent
111 // updates.
112 static struct CRYPTO_STATIC_MUTEX global_next_library_mutex =
113 CRYPTO_STATIC_MUTEX_INIT;
114
115 static void err_state_free(void *statep) {
116 ERR_STATE *state = statep;
117
118 if (state == NULL) {
119 return;
120 }
121
122 for (unsigned i = 0; i < ERR_NUM_ERRORS; i++) {
123 err_clear(&state->errors[i]);
124 }
125 free(state->to_free);
126 free(state);
127 }
128
129 // err_get_state gets the ERR_STATE object for the current thread.
130 static ERR_STATE *err_get_state(void) {
131 ERR_STATE *state = CRYPTO_get_thread_local(OPENSSL_THREAD_LOCAL_ERR);
132 if (state == NULL) {
133 state = malloc(sizeof(ERR_STATE));
134 if (state == NULL) {
135 return NULL;
136 }
137 OPENSSL_memset(state, 0, sizeof(ERR_STATE));
138 if (!CRYPTO_set_thread_local(OPENSSL_THREAD_LOCAL_ERR, state,
139 err_state_free)) {
140 return NULL;
141 }
142 }
143
144 return state;
145 }
146
147 static uint32_t get_error_values(int inc, int top, const char **file, int *line,
148 const char **data, int *flags) {
149 unsigned i = 0;
150 ERR_STATE *state;
151 struct err_error_st *error;
152 uint32_t ret;
153
154 state = err_get_state();
155 if (state == NULL || state->bottom == state->top) {
156 return 0;
157 }
158
159 if (top) {
160 assert(!inc);
161 // last error
162 i = state->top;
163 } else {
164 i = (state->bottom + 1) % ERR_NUM_ERRORS;
165 }
166
167 error = &state->errors[i];
168 ret = error->packed;
169
170 if (file != NULL && line != NULL) {
171 if (error->file == NULL) {
172 *file = "NA";
173 *line = 0;
174 } else {
175 *file = error->file;
176 *line = error->line;
177 }
178 }
179
180 if (data != NULL) {
181 if (error->data == NULL) {
182 *data = "";
183 if (flags != NULL) {
184 *flags = 0;
185 }
186 } else {
187 *data = error->data;
188 if (flags != NULL) {
189 // Without |ERR_FLAG_MALLOCED|, rust-openssl assumes the string has a
190 // static lifetime. In both cases, we retain ownership of the string,
191 // and the caller is not expected to free it.
192 *flags = ERR_FLAG_STRING | ERR_FLAG_MALLOCED;
193 }
194 // If this error is being removed, take ownership of data from
195 // the error. The semantics are such that the caller doesn't
196 // take ownership either. Instead the error system takes
197 // ownership and retains it until the next call that affects the
198 // error queue.
199 if (inc) {
200 if (error->data != NULL) {
201 free(state->to_free);
202 state->to_free = error->data;
203 }
204 error->data = NULL;
205 }
206 }
207 }
208
209 if (inc) {
210 assert(!top);
211 err_clear(error);
212 state->bottom = i;
213 }
214
215 return ret;
216 }
217
218 uint32_t ERR_get_error(void) {
219 return get_error_values(1 /* inc */, 0 /* bottom */, NULL, NULL, NULL, NULL);
220 }
221
222 uint32_t ERR_get_error_line(const char **file, int *line) {
223 return get_error_values(1 /* inc */, 0 /* bottom */, file, line, NULL, NULL);
224 }
225
226 uint32_t ERR_get_error_line_data(const char **file, int *line,
227 const char **data, int *flags) {
228 return get_error_values(1 /* inc */, 0 /* bottom */, file, line, data, flags);
229 }
230
231 uint32_t ERR_peek_error(void) {
232 return get_error_values(0 /* peek */, 0 /* bottom */, NULL, NULL, NULL, NULL);
233 }
234
235 uint32_t ERR_peek_error_line(const char **file, int *line) {
236 return get_error_values(0 /* peek */, 0 /* bottom */, file, line, NULL, NULL);
237 }
238
239 uint32_t ERR_peek_error_line_data(const char **file, int *line,
240 const char **data, int *flags) {
241 return get_error_values(0 /* peek */, 0 /* bottom */, file, line, data,
242 flags);
243 }
244
245 uint32_t ERR_peek_last_error(void) {
246 return get_error_values(0 /* peek */, 1 /* top */, NULL, NULL, NULL, NULL);
247 }
248
249 uint32_t ERR_peek_last_error_line(const char **file, int *line) {
250 return get_error_values(0 /* peek */, 1 /* top */, file, line, NULL, NULL);
251 }
252
253 uint32_t ERR_peek_last_error_line_data(const char **file, int *line,
254 const char **data, int *flags) {
255 return get_error_values(0 /* peek */, 1 /* top */, file, line, data, flags);
256 }
257
258 void ERR_clear_error(void) {
259 ERR_STATE *const state = err_get_state();
260 unsigned i;
261
262 if (state == NULL) {
263 return;
264 }
265
266 for (i = 0; i < ERR_NUM_ERRORS; i++) {
267 err_clear(&state->errors[i]);
268 }
269 free(state->to_free);
270 state->to_free = NULL;
271
272 state->top = state->bottom = 0;
273 }
274
275 void ERR_remove_thread_state(const CRYPTO_THREADID *tid) {
276 if (tid != NULL) {
277 assert(0);
278 return;
279 }
280
281 ERR_clear_error();
282 }
283
284 int ERR_get_next_error_library(void) {
285 int ret;
286
287 CRYPTO_STATIC_MUTEX_lock_write(&global_next_library_mutex);
288 ret = global_next_library++;
289 CRYPTO_STATIC_MUTEX_unlock_write(&global_next_library_mutex);
290
291 return ret;
292 }
293
294 void ERR_remove_state(unsigned long pid) {
295 ERR_clear_error();
296 }
297
298 void ERR_clear_system_error(void) {
299 errno = 0;
300 }
301
302 // err_string_cmp is a compare function for searching error values with
303 // |bsearch| in |err_string_lookup|.
304 static int err_string_cmp(const void *a, const void *b) {
305 const uint32_t a_key = *((const uint32_t*) a) >> 15;
306 const uint32_t b_key = *((const uint32_t*) b) >> 15;
307
308 if (a_key < b_key) {
309 return -1;
310 } else if (a_key > b_key) {
311 return 1;
312 } else {
313 return 0;
314 }
315 }
316
317 // err_string_lookup looks up the string associated with |lib| and |key| in
318 // |values| and |string_data|. It returns the string or NULL if not found.
319 static const char *err_string_lookup(uint32_t lib, uint32_t key,
320 const uint32_t *values,
321 size_t num_values,
322 const char *string_data) {
323 // |values| points to data in err_data.h, which is generated by
324 // err_data_generate.go. It's an array of uint32_t values. Each value has the
325 // following structure:
326 // | lib | key | offset |
327 // |6 bits| 11 bits | 15 bits |
328 //
329 // The |lib| value is a library identifier: one of the |ERR_LIB_*| values.
330 // The |key| is a reason code, depending on the context.
331 // The |offset| is the number of bytes from the start of |string_data| where
332 // the (NUL terminated) string for this value can be found.
333 //
334 // Values are sorted based on treating the |lib| and |key| part as an
335 // unsigned integer.
336 if (lib >= (1 << 6) || key >= (1 << 11)) {
337 return NULL;
338 }
339 uint32_t search_key = lib << 26 | key << 15;
340 const uint32_t *result = bsearch(&search_key, values, num_values,
341 sizeof(uint32_t), err_string_cmp);
342 if (result == NULL) {
343 return NULL;
344 }
345
346 return &string_data[(*result) & 0x7fff];
347 }
348
349 static const char *const kLibraryNames[ERR_NUM_LIBS] = {
350 "invalid library (0)",
351 "unknown library", // ERR_LIB_NONE
352 "system library", // ERR_LIB_SYS
353 "bignum routines", // ERR_LIB_BN
354 "RSA routines", // ERR_LIB_RSA
355 "Diffie-Hellman routines", // ERR_LIB_DH
356 "public key routines", // ERR_LIB_EVP
357 "memory buffer routines", // ERR_LIB_BUF
358 "object identifier routines", // ERR_LIB_OBJ
359 "PEM routines", // ERR_LIB_PEM
360 "DSA routines", // ERR_LIB_DSA
361 "X.509 certificate routines", // ERR_LIB_X509
362 "ASN.1 encoding routines", // ERR_LIB_ASN1
363 "configuration file routines", // ERR_LIB_CONF
364 "common libcrypto routines", // ERR_LIB_CRYPTO
365 "elliptic curve routines", // ERR_LIB_EC
366 "SSL routines", // ERR_LIB_SSL
367 "BIO routines", // ERR_LIB_BIO
368 "PKCS7 routines", // ERR_LIB_PKCS7
369 "PKCS8 routines", // ERR_LIB_PKCS8
370 "X509 V3 routines", // ERR_LIB_X509V3
371 "random number generator", // ERR_LIB_RAND
372 "ENGINE routines", // ERR_LIB_ENGINE
373 "OCSP routines", // ERR_LIB_OCSP
374 "UI routines", // ERR_LIB_UI
375 "COMP routines", // ERR_LIB_COMP
376 "ECDSA routines", // ERR_LIB_ECDSA
377 "ECDH routines", // ERR_LIB_ECDH
378 "HMAC routines", // ERR_LIB_HMAC
379 "Digest functions", // ERR_LIB_DIGEST
380 "Cipher functions", // ERR_LIB_CIPHER
381 "HKDF functions", // ERR_LIB_HKDF
382 "Trust Token functions", // ERR_LIB_TRUST_TOKEN
383 "User defined functions", // ERR_LIB_USER
384 };
385
386 static const char *err_lib_error_string(uint32_t packed_error) {
387 const uint32_t lib = ERR_GET_LIB(packed_error);
388
389 if (lib >= ERR_NUM_LIBS) {
390 return NULL;
391 }
392 return kLibraryNames[lib];
393 }
394
395 const char *ERR_lib_error_string(uint32_t packed_error) {
396 const char *ret = err_lib_error_string(packed_error);
397 return ret == NULL ? "unknown library" : ret;
398 }
399
400 const char *ERR_func_error_string(uint32_t packed_error) {
401 return "OPENSSL_internal";
402 }
403
404 static const char *err_reason_error_string(uint32_t packed_error) {
405 const uint32_t lib = ERR_GET_LIB(packed_error);
406 const uint32_t reason = ERR_GET_REASON(packed_error);
407
408 if (lib == ERR_LIB_SYS) {
409 if (reason < 127) {
410 return strerror(reason);
411 }
412 return NULL;
413 }
414
415 if (reason < ERR_NUM_LIBS) {
416 return kLibraryNames[reason];
417 }
418
419 if (reason < 100) {
420 switch (reason) {
421 case ERR_R_MALLOC_FAILURE:
422 return "malloc failure";
423 case ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED:
424 return "function should not have been called";
425 case ERR_R_PASSED_NULL_PARAMETER:
426 return "passed a null parameter";
427 case ERR_R_INTERNAL_ERROR:
428 return "internal error";
429 case ERR_R_OVERFLOW:
430 return "overflow";
431 default:
432 return NULL;
433 }
434 }
435
436 return err_string_lookup(lib, reason, kOpenSSLReasonValues,
437 kOpenSSLReasonValuesLen, kOpenSSLReasonStringData);
438 }
439
440 const char *ERR_reason_error_string(uint32_t packed_error) {
441 const char *ret = err_reason_error_string(packed_error);
442 return ret == NULL ? "unknown error" : ret;
443 }
444
445 char *ERR_error_string(uint32_t packed_error, char *ret) {
446 static char buf[ERR_ERROR_STRING_BUF_LEN];
447
448 if (ret == NULL) {
449 // TODO(fork): remove this.
450 ret = buf;
451 }
452
453 #if !defined(NDEBUG)
454 // This is aimed to help catch callers who don't provide
455 // |ERR_ERROR_STRING_BUF_LEN| bytes of space.
456 OPENSSL_memset(ret, 0, ERR_ERROR_STRING_BUF_LEN);
457 #endif
458
459 return ERR_error_string_n(packed_error, ret, ERR_ERROR_STRING_BUF_LEN);
460 }
461
462 char *ERR_error_string_n(uint32_t packed_error, char *buf, size_t len) {
463 if (len == 0) {
464 return NULL;
465 }
466
467 unsigned lib = ERR_GET_LIB(packed_error);
468 unsigned reason = ERR_GET_REASON(packed_error);
469
470 const char *lib_str = err_lib_error_string(packed_error);
471 const char *reason_str = err_reason_error_string(packed_error);
472
473 char lib_buf[32], reason_buf[32];
474 if (lib_str == NULL) {
475 snprintf(lib_buf, sizeof(lib_buf), "lib(%u)", lib);
476 lib_str = lib_buf;
477 }
478
479 if (reason_str == NULL) {
480 snprintf(reason_buf, sizeof(reason_buf), "reason(%u)", reason);
481 reason_str = reason_buf;
482 }
483
484 int ret = snprintf(buf, len, "error:%08" PRIx32 ":%s:OPENSSL_internal:%s",
485 packed_error, lib_str, reason_str);
486 if (ret >= 0 && (size_t)ret >= len) {
487 // The output was truncated; make sure we always have 5 colon-separated
488 // fields, i.e. 4 colons.
489 static const unsigned num_colons = 4;
490 unsigned i;
491 char *s = buf;
492
493 if (len <= num_colons) {
494 // In this situation it's not possible to ensure that the correct number
495 // of colons are included in the output.
496 return buf;
497 }
498
499 for (i = 0; i < num_colons; i++) {
500 char *colon = strchr(s, ':');
501 char *last_pos = &buf[len - 1] - num_colons + i;
502
503 if (colon == NULL || colon > last_pos) {
504 // set colon |i| at last possible position (buf[len-1] is the
505 // terminating 0). If we're setting this colon, then all whole of the
506 // rest of the string must be colons in order to have the correct
507 // number.
508 OPENSSL_memset(last_pos, ':', num_colons - i);
509 break;
510 }
511
512 s = colon + 1;
513 }
514 }
515
516 return buf;
517 }
518
519 void ERR_print_errors_cb(ERR_print_errors_callback_t callback, void *ctx) {
520 char buf[ERR_ERROR_STRING_BUF_LEN];
521 char buf2[1024];
522 const char *file, *data;
523 int line, flags;
524 uint32_t packed_error;
525
526 // thread_hash is the least-significant bits of the |ERR_STATE| pointer value
527 // for this thread.
528 const unsigned long thread_hash = (uintptr_t) err_get_state();
529
530 for (;;) {
531 packed_error = ERR_get_error_line_data(&file, &line, &data, &flags);
532 if (packed_error == 0) {
533 break;
534 }
535
536 ERR_error_string_n(packed_error, buf, sizeof(buf));
537 snprintf(buf2, sizeof(buf2), "%lu:%s:%s:%d:%s\n", thread_hash, buf, file,
538 line, (flags & ERR_FLAG_STRING) ? data : "");
539 if (callback(buf2, strlen(buf2), ctx) <= 0) {
540 break;
541 }
542 }
543 }
544
545 static int print_errors_to_file(const char* msg, size_t msg_len, void* ctx) {
546 assert(msg[msg_len] == '\0');
547 FILE* fp = ctx;
548 int res = fputs(msg, fp);
549 return res < 0 ? 0 : 1;
550 }
551
552 void ERR_print_errors_fp(FILE *file) {
553 ERR_print_errors_cb(print_errors_to_file, file);
554 }
555
556 // err_set_error_data sets the data on the most recent error.
557 static void err_set_error_data(char *data) {
558 ERR_STATE *const state = err_get_state();
559 struct err_error_st *error;
560
561 if (state == NULL || state->top == state->bottom) {
562 free(data);
563 return;
564 }
565
566 error = &state->errors[state->top];
567
568 free(error->data);
569 error->data = data;
570 }
571
572 void ERR_put_error(int library, int unused, int reason, const char *file,
573 unsigned line) {
574 ERR_STATE *const state = err_get_state();
575 struct err_error_st *error;
576
577 if (state == NULL) {
578 return;
579 }
580
581 if (library == ERR_LIB_SYS && reason == 0) {
582 #if defined(OPENSSL_WINDOWS)
583 reason = GetLastError();
584 #else
585 reason = errno;
586 #endif
587 }
588
589 state->top = (state->top + 1) % ERR_NUM_ERRORS;
590 if (state->top == state->bottom) {
591 state->bottom = (state->bottom + 1) % ERR_NUM_ERRORS;
592 }
593
594 error = &state->errors[state->top];
595 err_clear(error);
596 error->file = file;
597 error->line = line;
598 error->packed = ERR_PACK(library, reason);
599 }
600
601 // ERR_add_error_data_vdata takes a variable number of const char* pointers,
602 // concatenates them and sets the result as the data on the most recent
603 // error.
604 static void err_add_error_vdata(unsigned num, va_list args) {
605 size_t total_size = 0;
606 const char *substr;
607 char *buf;
608
609 va_list args_copy;
610 va_copy(args_copy, args);
611 for (size_t i = 0; i < num; i++) {
612 substr = va_arg(args_copy, const char *);
613 if (substr == NULL) {
614 continue;
615 }
616 size_t substr_len = strlen(substr);
617 if (SIZE_MAX - total_size < substr_len) {
618 va_end(args_copy);
619 return; // Would overflow.
620 }
621 total_size += substr_len;
622 }
623 va_end(args_copy);
624 if (total_size == SIZE_MAX) {
625 return; // Would overflow.
626 }
627 total_size += 1; // NUL terminator.
628 if ((buf = malloc(total_size)) == NULL) {
629 return;
630 }
631 buf[0] = '\0';
632 for (size_t i = 0; i < num; i++) {
633 substr = va_arg(args, const char *);
634 if (substr == NULL) {
635 continue;
636 }
637 if (OPENSSL_strlcat(buf, substr, total_size) >= total_size) {
638 assert(0); // should not be possible.
639 }
640 }
641 err_set_error_data(buf);
642 }
643
644 void ERR_add_error_data(unsigned count, ...) {
645 va_list args;
646 va_start(args, count);
647 err_add_error_vdata(count, args);
648 va_end(args);
649 }
650
651 void ERR_add_error_dataf(const char *format, ...) {
652 char *buf = NULL;
653 va_list ap;
654
655 va_start(ap, format);
656 if (OPENSSL_vasprintf_internal(&buf, format, ap, /*system_malloc=*/1) == -1) {
657 va_end(ap);
658 return;
659 }
660 va_end(ap);
661
662 err_set_error_data(buf);
663 }
664
665 void ERR_set_error_data(char *data, int flags) {
666 if (!(flags & ERR_FLAG_STRING)) {
667 // We do not support non-string error data.
668 assert(0);
669 return;
670 }
671 // We can not use OPENSSL_strdup because we don't want to call OPENSSL_malloc,
672 // which can affect the error stack.
673 char *copy = strdup_libc_malloc(data);
674 if (copy != NULL) {
675 err_set_error_data(copy);
676 }
677 if (flags & ERR_FLAG_MALLOCED) {
678 // We can not take ownership of |data| directly because it is allocated with
679 // |OPENSSL_malloc| and we will free it with system |free| later.
680 OPENSSL_free(data);
681 }
682 }
683
684 int ERR_set_mark(void) {
685 ERR_STATE *const state = err_get_state();
686
687 if (state == NULL || state->bottom == state->top) {
688 return 0;
689 }
690 state->errors[state->top].mark = 1;
691 return 1;
692 }
693
694 int ERR_pop_to_mark(void) {
695 ERR_STATE *const state = err_get_state();
696
697 if (state == NULL) {
698 return 0;
699 }
700
701 while (state->bottom != state->top) {
702 struct err_error_st *error = &state->errors[state->top];
703
704 if (error->mark) {
705 error->mark = 0;
706 return 1;
707 }
708
709 err_clear(error);
710 if (state->top == 0) {
711 state->top = ERR_NUM_ERRORS - 1;
712 } else {
713 state->top--;
714 }
715 }
716
717 return 0;
718 }
719
720 void ERR_load_CRYPTO_strings(void) {}
721
722 void ERR_load_crypto_strings(void) {}
723
724 void ERR_free_strings(void) {}
725
726 void ERR_load_BIO_strings(void) {}
727
728 void ERR_load_ERR_strings(void) {}
729
730 void ERR_load_RAND_strings(void) {}
731
732 struct err_save_state_st {
733 struct err_error_st *errors;
734 size_t num_errors;
735 };
736
737 void ERR_SAVE_STATE_free(ERR_SAVE_STATE *state) {
738 if (state == NULL) {
739 return;
740 }
741 for (size_t i = 0; i < state->num_errors; i++) {
742 err_clear(&state->errors[i]);
743 }
744 free(state->errors);
745 free(state);
746 }
747
748 ERR_SAVE_STATE *ERR_save_state(void) {
749 ERR_STATE *const state = err_get_state();
750 if (state == NULL || state->top == state->bottom) {
751 return NULL;
752 }
753
754 ERR_SAVE_STATE *ret = malloc(sizeof(ERR_SAVE_STATE));
755 if (ret == NULL) {
756 return NULL;
757 }
758
759 // Errors are stored in the range (bottom, top].
760 size_t num_errors = state->top >= state->bottom
761 ? state->top - state->bottom
762 : ERR_NUM_ERRORS + state->top - state->bottom;
763 assert(num_errors < ERR_NUM_ERRORS);
764 ret->errors = malloc(num_errors * sizeof(struct err_error_st));
765 if (ret->errors == NULL) {
766 free(ret);
767 return NULL;
768 }
769 OPENSSL_memset(ret->errors, 0, num_errors * sizeof(struct err_error_st));
770 ret->num_errors = num_errors;
771
772 for (size_t i = 0; i < num_errors; i++) {
773 size_t j = (state->bottom + i + 1) % ERR_NUM_ERRORS;
774 err_copy(&ret->errors[i], &state->errors[j]);
775 }
776 return ret;
777 }
778
779 void ERR_restore_state(const ERR_SAVE_STATE *state) {
780 if (state == NULL || state->num_errors == 0) {
781 ERR_clear_error();
782 return;
783 }
784
785 if (state->num_errors >= ERR_NUM_ERRORS) {
786 abort();
787 }
788
789 ERR_STATE *const dst = err_get_state();
790 if (dst == NULL) {
791 return;
792 }
793
794 for (size_t i = 0; i < state->num_errors; i++) {
795 err_copy(&dst->errors[i], &state->errors[i]);
796 }
797 dst->top = (unsigned)(state->num_errors - 1);
798 dst->bottom = ERR_NUM_ERRORS - 1;
799 }