1/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2 * All rights reserved.
3 *
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
7 *
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to.  The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14 *
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
21 *
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the copyright
26 *    notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 *    notice, this list of conditions and the following disclaimer in the
29 *    documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 *    must display the following acknowledgement:
32 *    "This product includes cryptographic software written by
33 *     Eric Young (eay@cryptsoft.com)"
34 *    The word 'cryptographic' can be left out if the rouines from the library
35 *    being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 *    the apps directory (application code) you must include an acknowledgement:
38 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39 *
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 * SUCH DAMAGE.
51 *
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed.  i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
56 */
57/* ====================================================================
58 * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
59 *
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
62 * are met:
63 *
64 * 1. Redistributions of source code must retain the above copyright
65 *    notice, this list of conditions and the following disclaimer.
66 *
67 * 2. Redistributions in binary form must reproduce the above copyright
68 *    notice, this list of conditions and the following disclaimer in
69 *    the documentation and/or other materials provided with the
70 *    distribution.
71 *
72 * 3. All advertising materials mentioning features or use of this
73 *    software must display the following acknowledgment:
74 *    "This product includes software developed by the OpenSSL Project
75 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76 *
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 *    endorse or promote products derived from this software without
79 *    prior written permission. For written permission, please contact
80 *    openssl-core@openssl.org.
81 *
82 * 5. Products derived from this software may not be called "OpenSSL"
83 *    nor may "OpenSSL" appear in their names without prior written
84 *    permission of the OpenSSL Project.
85 *
86 * 6. Redistributions of any form whatsoever must retain the following
87 *    acknowledgment:
88 *    "This product includes software developed by the OpenSSL Project
89 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90 *
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
104 *
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com).  This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com). */
108
109#include <openssl/err.h>
110
111#include <assert.h>
112#include <errno.h>
113#include <inttypes.h>
114#include <string.h>
115
116#if defined(OPENSSL_WINDOWS)
117#pragma warning(push, 3)
118#include <windows.h>
119#pragma warning(pop)
120#endif
121
122#include <openssl/mem.h>
123#include <openssl/thread.h>
124
125#include "../internal.h"
126
127
128extern const uint32_t kOpenSSLFunctionValues[];
129extern const size_t kOpenSSLFunctionValuesLen;
130extern const char kOpenSSLFunctionStringData[];
131
132extern const uint32_t kOpenSSLReasonValues[];
133extern const size_t kOpenSSLReasonValuesLen;
134extern const char kOpenSSLReasonStringData[];
135
136/* err_clear_data frees the optional |data| member of the given error. */
137static void err_clear_data(struct err_error_st *error) {
138  if ((error->flags & ERR_FLAG_MALLOCED) != 0) {
139    OPENSSL_free(error->data);
140  }
141  error->data = NULL;
142  error->flags &= ~ERR_FLAG_MALLOCED;
143}
144
145/* err_clear clears the given queued error. */
146static void err_clear(struct err_error_st *error) {
147  err_clear_data(error);
148  memset(error, 0, sizeof(struct err_error_st));
149}
150
151/* global_next_library contains the next custom library value to return. */
152static int global_next_library = ERR_NUM_LIBS;
153
154/* global_next_library_mutex protects |global_next_library| from concurrent
155 * updates. */
156static struct CRYPTO_STATIC_MUTEX global_next_library_mutex =
157    CRYPTO_STATIC_MUTEX_INIT;
158
159static void err_state_free(void *statep) {
160  ERR_STATE *state = statep;
161
162  if (state == NULL) {
163    return;
164  }
165
166  unsigned i;
167  for (i = 0; i < ERR_NUM_ERRORS; i++) {
168    err_clear(&state->errors[i]);
169  }
170  OPENSSL_free(state->to_free);
171  OPENSSL_free(state);
172}
173
174/* err_get_state gets the ERR_STATE object for the current thread. */
175static ERR_STATE *err_get_state(void) {
176  ERR_STATE *state = CRYPTO_get_thread_local(OPENSSL_THREAD_LOCAL_ERR);
177  if (state == NULL) {
178    state = OPENSSL_malloc(sizeof(ERR_STATE));
179    if (state == NULL) {
180      return NULL;
181    }
182    memset(state, 0, sizeof(ERR_STATE));
183    if (!CRYPTO_set_thread_local(OPENSSL_THREAD_LOCAL_ERR, state,
184                                 err_state_free)) {
185      return NULL;
186    }
187  }
188
189  return state;
190}
191
192static uint32_t get_error_values(int inc, int top, const char **file, int *line,
193                                 const char **data, int *flags) {
194  unsigned i = 0;
195  ERR_STATE *state;
196  struct err_error_st *error;
197  uint32_t ret;
198
199  state = err_get_state();
200  if (state == NULL || state->bottom == state->top) {
201    return 0;
202  }
203
204  if (top) {
205    assert(!inc);
206    /* last error */
207    i = state->top;
208  } else {
209    i = (state->bottom + 1) % ERR_NUM_ERRORS;
210  }
211
212  error = &state->errors[i];
213  ret = error->packed;
214
215  if (file != NULL && line != NULL) {
216    if (error->file == NULL) {
217      *file = "NA";
218      *line = 0;
219    } else {
220      *file = error->file;
221      *line = error->line;
222    }
223  }
224
225  if (data != NULL) {
226    if (error->data == NULL) {
227      *data = "";
228      if (flags != NULL) {
229        *flags = 0;
230      }
231    } else {
232      *data = error->data;
233      if (flags != NULL) {
234        *flags = error->flags & ERR_FLAG_PUBLIC_MASK;
235      }
236      /* If this error is being removed, take ownership of data from
237       * the error. The semantics are such that the caller doesn't
238       * take ownership either. Instead the error system takes
239       * ownership and retains it until the next call that affects the
240       * error queue. */
241      if (inc) {
242        if (error->flags & ERR_FLAG_MALLOCED) {
243          OPENSSL_free(state->to_free);
244          state->to_free = error->data;
245        }
246        error->data = NULL;
247        error->flags = 0;
248      }
249    }
250  }
251
252  if (inc) {
253    assert(!top);
254    err_clear(error);
255    state->bottom = i;
256  }
257
258  return ret;
259}
260
261uint32_t ERR_get_error(void) {
262  return get_error_values(1, 0, NULL, NULL, NULL, NULL);
263}
264
265uint32_t ERR_get_error_line(const char **file, int *line) {
266  return get_error_values(1, 0, file, line, NULL, NULL);
267}
268
269uint32_t ERR_get_error_line_data(const char **file, int *line,
270                                 const char **data, int *flags) {
271  return get_error_values(1, 0, file, line, data, flags);
272}
273
274uint32_t ERR_peek_error(void) {
275  return get_error_values(0, 0, NULL, NULL, NULL, NULL);
276}
277
278uint32_t ERR_peek_error_line(const char **file, int *line) {
279  return get_error_values(0, 0, file, line, NULL, NULL);
280}
281
282uint32_t ERR_peek_error_line_data(const char **file, int *line,
283                                  const char **data, int *flags) {
284  return get_error_values(0, 0, file, line, data, flags);
285}
286
287uint32_t ERR_peek_last_error(void) {
288  return get_error_values(0, 1, NULL, NULL, NULL, NULL);
289}
290
291uint32_t ERR_peek_last_error_line(const char **file, int *line) {
292  return get_error_values(0, 1, file, line, NULL, NULL);
293}
294
295uint32_t ERR_peek_last_error_line_data(const char **file, int *line,
296                                       const char **data, int *flags) {
297  return get_error_values(0, 1, file, line, data, flags);
298}
299
300void ERR_clear_error(void) {
301  ERR_STATE *const state = err_get_state();
302  unsigned i;
303
304  if (state == NULL) {
305    return;
306  }
307
308  for (i = 0; i < ERR_NUM_ERRORS; i++) {
309    err_clear(&state->errors[i]);
310  }
311  OPENSSL_free(state->to_free);
312  state->to_free = NULL;
313
314  state->top = state->bottom = 0;
315}
316
317void ERR_remove_thread_state(const CRYPTO_THREADID *tid) {
318  if (tid != NULL) {
319    assert(0);
320    return;
321  }
322
323  ERR_clear_error();
324}
325
326int ERR_get_next_error_library(void) {
327  int ret;
328
329  CRYPTO_STATIC_MUTEX_lock_write(&global_next_library_mutex);
330  ret = global_next_library++;
331  CRYPTO_STATIC_MUTEX_unlock(&global_next_library_mutex);
332
333  return ret;
334}
335
336void ERR_remove_state(unsigned long pid) {
337  ERR_clear_error();
338}
339
340void ERR_clear_system_error(void) {
341  errno = 0;
342}
343
344char *ERR_error_string(uint32_t packed_error, char *ret) {
345  static char buf[ERR_ERROR_STRING_BUF_LEN];
346
347  if (ret == NULL) {
348    /* TODO(fork): remove this. */
349    ret = buf;
350  }
351
352#if !defined(NDEBUG)
353  /* This is aimed to help catch callers who don't provide
354   * |ERR_ERROR_STRING_BUF_LEN| bytes of space. */
355  memset(ret, 0, ERR_ERROR_STRING_BUF_LEN);
356#endif
357
358  ERR_error_string_n(packed_error, ret, ERR_ERROR_STRING_BUF_LEN);
359
360  return ret;
361}
362
363void ERR_error_string_n(uint32_t packed_error, char *buf, size_t len) {
364  char lib_buf[64], func_buf[64], reason_buf[64];
365  const char *lib_str, *func_str, *reason_str;
366  unsigned lib, func, reason;
367
368  if (len == 0) {
369    return;
370  }
371
372  lib = ERR_GET_LIB(packed_error);
373  func = ERR_GET_FUNC(packed_error);
374  reason = ERR_GET_REASON(packed_error);
375
376  lib_str = ERR_lib_error_string(packed_error);
377  func_str = ERR_func_error_string(packed_error);
378  reason_str = ERR_reason_error_string(packed_error);
379
380  if (lib_str == NULL) {
381    BIO_snprintf(lib_buf, sizeof(lib_buf), "lib(%u)", lib);
382    lib_str = lib_buf;
383  }
384
385  if (func_str == NULL) {
386    BIO_snprintf(func_buf, sizeof(func_buf), "func(%u)", func);
387    func_str = func_buf;
388  }
389
390  if (reason_str == NULL) {
391    BIO_snprintf(reason_buf, sizeof(reason_buf), "reason(%u)", reason);
392    reason_str = reason_buf;
393  }
394
395  BIO_snprintf(buf, len, "error:%08" PRIx32 ":%s:%s:%s",
396               packed_error, lib_str, func_str, reason_str);
397
398  if (strlen(buf) == len - 1) {
399    /* output may be truncated; make sure we always have 5 colon-separated
400     * fields, i.e. 4 colons. */
401    static const unsigned num_colons = 4;
402    unsigned i;
403    char *s = buf;
404
405    if (len <= num_colons) {
406      /* In this situation it's not possible to ensure that the correct number
407       * of colons are included in the output. */
408      return;
409    }
410
411    for (i = 0; i < num_colons; i++) {
412      char *colon = strchr(s, ':');
413      char *last_pos = &buf[len - 1] - num_colons + i;
414
415      if (colon == NULL || colon > last_pos) {
416        /* set colon |i| at last possible position (buf[len-1] is the
417         * terminating 0). If we're setting this colon, then all whole of the
418         * rest of the string must be colons in order to have the correct
419         * number. */
420        memset(last_pos, ':', num_colons - i);
421        break;
422      }
423
424      s = colon + 1;
425    }
426  }
427}
428
429// err_string_cmp is a compare function for searching error values with
430// |bsearch| in |err_string_lookup|.
431static int err_string_cmp(const void *a, const void *b) {
432  const uint32_t a_key = *((const uint32_t*) a) >> 15;
433  const uint32_t b_key = *((const uint32_t*) b) >> 15;
434
435  if (a_key < b_key) {
436    return -1;
437  } else if (a_key > b_key) {
438    return 1;
439  } else {
440    return 0;
441  }
442}
443
444/* err_string_lookup looks up the string associated with |lib| and |key| in
445 * |values| and |string_data|. It returns the string or NULL if not found. */
446static const char *err_string_lookup(uint32_t lib, uint32_t key,
447                                     const uint32_t *values,
448                                     size_t num_values,
449                                     const char *string_data) {
450  /* |values| points to data in err_data.h, which is generated by
451   * err_data_generate.go. It's an array of uint32_t values. Each value has the
452   * following structure:
453   *   | lib  |    key    |    offset     |
454   *   |6 bits|  11 bits  |    15 bits    |
455   *
456   * The |lib| value is a library identifier: one of the |ERR_LIB_*| values.
457   * The |key| is either a function or a reason code, depending on the context.
458   * The |offset| is the number of bytes from the start of |string_data| where
459   * the (NUL terminated) string for this value can be found.
460   *
461   * Values are sorted based on treating the |lib| and |key| part as an
462   * unsigned integer. */
463  if (lib >= (1 << 6) || key >= (1 << 11)) {
464    return NULL;
465  }
466  uint32_t search_key = lib << 26 | key << 15;
467  const uint32_t *result = bsearch(&search_key, values, num_values,
468                                   sizeof(uint32_t), err_string_cmp);
469  if (result == NULL) {
470    return NULL;
471  }
472
473  return &string_data[(*result) & 0x7fff];
474}
475
476static const char *const kLibraryNames[ERR_NUM_LIBS] = {
477    "invalid library (0)",
478    "unknown library",                            /* ERR_LIB_NONE */
479    "system library",                             /* ERR_LIB_SYS */
480    "bignum routines",                            /* ERR_LIB_BN */
481    "RSA routines",                               /* ERR_LIB_RSA */
482    "Diffie-Hellman routines",                    /* ERR_LIB_DH */
483    "public key routines",                        /* ERR_LIB_EVP */
484    "memory buffer routines",                     /* ERR_LIB_BUF */
485    "object identifier routines",                 /* ERR_LIB_OBJ */
486    "PEM routines",                               /* ERR_LIB_PEM */
487    "DSA routines",                               /* ERR_LIB_DSA */
488    "X.509 certificate routines",                 /* ERR_LIB_X509 */
489    "ASN.1 encoding routines",                    /* ERR_LIB_ASN1 */
490    "configuration file routines",                /* ERR_LIB_CONF */
491    "common libcrypto routines",                  /* ERR_LIB_CRYPTO */
492    "elliptic curve routines",                    /* ERR_LIB_EC */
493    "SSL routines",                               /* ERR_LIB_SSL */
494    "BIO routines",                               /* ERR_LIB_BIO */
495    "PKCS7 routines",                             /* ERR_LIB_PKCS7 */
496    "PKCS8 routines",                             /* ERR_LIB_PKCS8 */
497    "X509 V3 routines",                           /* ERR_LIB_X509V3 */
498    "random number generator",                    /* ERR_LIB_RAND */
499    "ENGINE routines",                            /* ERR_LIB_ENGINE */
500    "OCSP routines",                              /* ERR_LIB_OCSP */
501    "UI routines",                                /* ERR_LIB_UI */
502    "COMP routines",                              /* ERR_LIB_COMP */
503    "ECDSA routines",                             /* ERR_LIB_ECDSA */
504    "ECDH routines",                              /* ERR_LIB_ECDH */
505    "HMAC routines",                              /* ERR_LIB_HMAC */
506    "Digest functions",                           /* ERR_LIB_DIGEST */
507    "Cipher functions",                           /* ERR_LIB_CIPHER */
508    "User defined functions",                     /* ERR_LIB_USER */
509    "HKDF functions",                             /* ERR_LIB_HKDF */
510};
511
512const char *ERR_lib_error_string(uint32_t packed_error) {
513  const uint32_t lib = ERR_GET_LIB(packed_error);
514
515  if (lib >= ERR_NUM_LIBS) {
516    return NULL;
517  }
518  return kLibraryNames[lib];
519}
520
521const char *ERR_func_error_string(uint32_t packed_error) {
522  const uint32_t lib = ERR_GET_LIB(packed_error);
523  const uint32_t func = ERR_GET_FUNC(packed_error);
524
525  if (lib == ERR_LIB_SYS) {
526    switch (func) {
527      case SYS_F_fopen:
528        return "fopen";
529      case SYS_F_fclose:
530        return "fclose";
531      case SYS_F_fread:
532        return "fread";
533      case SYS_F_fwrite:
534        return "fwrite";
535      case SYS_F_socket:
536        return "socket";
537      case SYS_F_setsockopt:
538        return "setsockopt";
539      case SYS_F_connect:
540        return "connect";
541      case SYS_F_getaddrinfo:
542        return "getaddrinfo";
543      default:
544        return NULL;
545    }
546  }
547
548  return err_string_lookup(ERR_GET_LIB(packed_error),
549                           ERR_GET_FUNC(packed_error), kOpenSSLFunctionValues,
550                           kOpenSSLFunctionValuesLen,
551                           kOpenSSLFunctionStringData);
552}
553
554const char *ERR_reason_error_string(uint32_t packed_error) {
555  const uint32_t lib = ERR_GET_LIB(packed_error);
556  const uint32_t reason = ERR_GET_REASON(packed_error);
557
558  if (lib == ERR_LIB_SYS) {
559    if (reason < 127) {
560      return strerror(reason);
561    }
562    return NULL;
563  }
564
565  if (reason < ERR_NUM_LIBS) {
566    return kLibraryNames[reason];
567  }
568
569  if (reason < 100) {
570    switch (reason) {
571      case ERR_R_MALLOC_FAILURE:
572        return "malloc failure";
573      case ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED:
574        return "function should not have been called";
575      case ERR_R_PASSED_NULL_PARAMETER:
576        return "passed a null parameter";
577      case ERR_R_INTERNAL_ERROR:
578        return "internal error";
579      case ERR_R_OVERFLOW:
580        return "overflow";
581      default:
582        return NULL;
583    }
584  }
585
586  return err_string_lookup(lib, reason, kOpenSSLReasonValues,
587                           kOpenSSLReasonValuesLen, kOpenSSLReasonStringData);
588}
589
590void ERR_print_errors_cb(ERR_print_errors_callback_t callback, void *ctx) {
591  char buf[ERR_ERROR_STRING_BUF_LEN];
592  char buf2[1024];
593  const char *file, *data;
594  int line, flags;
595  uint32_t packed_error;
596
597  /* thread_hash is the least-significant bits of the |ERR_STATE| pointer value
598   * for this thread. */
599  const unsigned long thread_hash = (uintptr_t) err_get_state();
600
601  for (;;) {
602    packed_error = ERR_get_error_line_data(&file, &line, &data, &flags);
603    if (packed_error == 0) {
604      break;
605    }
606
607    ERR_error_string_n(packed_error, buf, sizeof(buf));
608    BIO_snprintf(buf2, sizeof(buf2), "%lu:%s:%s:%d:%s\n", thread_hash, buf,
609                 file, line, (flags & ERR_FLAG_STRING) ? data : "");
610    if (callback(buf2, strlen(buf2), ctx) <= 0) {
611      break;
612    }
613  }
614}
615
616static int print_errors_to_file(const char* msg, size_t msg_len, void* ctx) {
617  assert(msg[msg_len] == '\0');
618  FILE* fp = ctx;
619  int res = fputs(msg, fp);
620  return res < 0 ? 0 : 1;
621}
622
623void ERR_print_errors_fp(FILE *file) {
624  ERR_print_errors_cb(print_errors_to_file, file);
625}
626
627/* err_set_error_data sets the data on the most recent error. The |flags|
628 * argument is a combination of the |ERR_FLAG_*| values. */
629static void err_set_error_data(char *data, int flags) {
630  ERR_STATE *const state = err_get_state();
631  struct err_error_st *error;
632
633  if (state == NULL || state->top == state->bottom) {
634    if (flags & ERR_FLAG_MALLOCED) {
635      OPENSSL_free(data);
636    }
637    return;
638  }
639
640  error = &state->errors[state->top];
641
642  err_clear_data(error);
643  error->data = data;
644  error->flags = flags;
645}
646
647void ERR_put_error(int library, int func, int reason, const char *file,
648                   unsigned line) {
649  ERR_STATE *const state = err_get_state();
650  struct err_error_st *error;
651
652  if (state == NULL) {
653    return;
654  }
655
656  if (library == ERR_LIB_SYS && reason == 0) {
657#if defined(WIN32)
658    reason = GetLastError();
659#else
660    reason = errno;
661#endif
662  }
663
664  state->top = (state->top + 1) % ERR_NUM_ERRORS;
665  if (state->top == state->bottom) {
666    state->bottom = (state->bottom + 1) % ERR_NUM_ERRORS;
667  }
668
669  error = &state->errors[state->top];
670  err_clear(error);
671  error->file = file;
672  error->line = line;
673  error->packed = ERR_PACK(library, func, reason);
674}
675
676/* ERR_add_error_data_vdata takes a variable number of const char* pointers,
677 * concatenates them and sets the result as the data on the most recent
678 * error. */
679static void err_add_error_vdata(unsigned num, va_list args) {
680  size_t alloced, new_len, len = 0, substr_len;
681  char *buf;
682  const char *substr;
683  unsigned i;
684
685  alloced = 80;
686  buf = OPENSSL_malloc(alloced + 1);
687  if (buf == NULL) {
688    return;
689  }
690
691  for (i = 0; i < num; i++) {
692    substr = va_arg(args, const char *);
693    if (substr == NULL) {
694      continue;
695    }
696
697    substr_len = strlen(substr);
698    new_len = len + substr_len;
699    if (new_len > alloced) {
700      char *new_buf;
701
702      if (alloced + 20 + 1 < alloced) {
703        /* overflow. */
704        OPENSSL_free(buf);
705        return;
706      }
707
708      alloced = new_len + 20;
709      new_buf = OPENSSL_realloc(buf, alloced + 1);
710      if (new_buf == NULL) {
711        OPENSSL_free(buf);
712        return;
713      }
714      buf = new_buf;
715    }
716
717    memcpy(buf + len, substr, substr_len);
718    len = new_len;
719  }
720
721  buf[len] = 0;
722  err_set_error_data(buf, ERR_FLAG_MALLOCED | ERR_FLAG_STRING);
723}
724
725void ERR_add_error_data(unsigned count, ...) {
726  va_list args;
727  va_start(args, count);
728  err_add_error_vdata(count, args);
729  va_end(args);
730}
731
732void ERR_add_error_dataf(const char *format, ...) {
733  va_list ap;
734  char *buf;
735  static const unsigned buf_len = 256;
736
737  /* A fixed-size buffer is used because va_copy (which would be needed in
738   * order to call vsnprintf twice and measure the buffer) wasn't defined until
739   * C99. */
740  buf = OPENSSL_malloc(buf_len + 1);
741  if (buf == NULL) {
742    return;
743  }
744
745  va_start(ap, format);
746  BIO_vsnprintf(buf, buf_len, format, ap);
747  buf[buf_len] = 0;
748  va_end(ap);
749
750  err_set_error_data(buf, ERR_FLAG_MALLOCED | ERR_FLAG_STRING);
751}
752
753int ERR_set_mark(void) {
754  ERR_STATE *const state = err_get_state();
755
756  if (state == NULL || state->bottom == state->top) {
757    return 0;
758  }
759  state->errors[state->top].flags |= ERR_FLAG_MARK;
760  return 1;
761}
762
763int ERR_pop_to_mark(void) {
764  ERR_STATE *const state = err_get_state();
765
766  if (state == NULL) {
767    return 0;
768  }
769
770  while (state->bottom != state->top) {
771    struct err_error_st *error = &state->errors[state->top];
772
773    if ((error->flags & ERR_FLAG_MARK) != 0) {
774      error->flags &= ~ERR_FLAG_MARK;
775      return 1;
776    }
777
778    err_clear(error);
779    if (state->top == 0) {
780      state->top = ERR_NUM_ERRORS - 1;
781    } else {
782      state->top--;
783    }
784  }
785
786  return 0;
787}
788
789void ERR_load_crypto_strings(void) {}
790
791void ERR_free_strings(void) {}
792
793void ERR_load_BIO_strings(void) {}
794
795void ERR_load_ERR_strings(void) {}
796