Coverage Report

Created: 2024-11-21 07:03

/src/boringssl/crypto/err/err.c
Line
Count
Source (jump to first uncovered line)
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
// Ensure we can't call OPENSSL_malloc circularly.
110
#define _BORINGSSL_PROHIBIT_OPENSSL_MALLOC
111
#include <openssl/err.h>
112
113
#include <assert.h>
114
#include <errno.h>
115
#include <inttypes.h>
116
#include <limits.h>
117
#include <stdarg.h>
118
#include <string.h>
119
120
#if defined(OPENSSL_WINDOWS)
121
OPENSSL_MSVC_PRAGMA(warning(push, 3))
122
#include <windows.h>
123
OPENSSL_MSVC_PRAGMA(warning(pop))
124
#endif
125
126
#include <openssl/mem.h>
127
#include <openssl/thread.h>
128
129
#include "../internal.h"
130
#include "./internal.h"
131
132
133
struct err_error_st {
134
  // file contains the filename where the error occurred.
135
  const char *file;
136
  // data contains a NUL-terminated string with optional data. It is allocated
137
  // with system |malloc| and must be freed with |free| (not |OPENSSL_free|)
138
  char *data;
139
  // packed contains the error library and reason, as packed by ERR_PACK.
140
  uint32_t packed;
141
  // line contains the line number where the error occurred.
142
  uint16_t line;
143
  // mark indicates a reversion point in the queue. See |ERR_pop_to_mark|.
144
  unsigned mark : 1;
145
};
146
147
// ERR_STATE contains the per-thread, error queue.
148
typedef struct err_state_st {
149
  // errors contains up to ERR_NUM_ERRORS - 1 most recent errors, organised as a
150
  // ring buffer.
151
  struct err_error_st errors[ERR_NUM_ERRORS];
152
  // top contains the index of the most recent error. If |top| equals |bottom|
153
  // then the queue is empty.
154
  unsigned top;
155
  // bottom contains the index before the least recent error in the queue.
156
  unsigned bottom;
157
158
  // to_free, if not NULL, contains a pointer owned by this structure that was
159
  // previously a |data| pointer of one of the elements of |errors|.
160
  void *to_free;
161
} ERR_STATE;
162
163
extern const uint32_t kOpenSSLReasonValues[];
164
extern const size_t kOpenSSLReasonValuesLen;
165
extern const char kOpenSSLReasonStringData[];
166
167
0
static char *strdup_libc_malloc(const char *str) {
168
  // |strdup| is not in C until C23, so MSVC triggers deprecation warnings, and
169
  // glibc and musl gate it on a feature macro. Reimplementing it is easier.
170
0
  size_t len = strlen(str);
171
0
  char *ret = malloc(len + 1);
172
0
  if (ret != NULL) {
173
0
    memcpy(ret, str, len + 1);
174
0
  }
175
0
  return ret;
176
0
}
177
178
// err_clear clears the given queued error.
179
5.61k
static void err_clear(struct err_error_st *error) {
180
5.61k
  free(error->data);
181
5.61k
  OPENSSL_memset(error, 0, sizeof(struct err_error_st));
182
5.61k
}
183
184
0
static void err_copy(struct err_error_st *dst, const struct err_error_st *src) {
185
0
  err_clear(dst);
186
0
  dst->file = src->file;
187
0
  if (src->data != NULL) {
188
    // We can't use OPENSSL_strdup because we don't want to call OPENSSL_malloc,
189
    // which can affect the error stack.
190
0
    dst->data = strdup_libc_malloc(src->data);
191
0
  }
192
0
  dst->packed = src->packed;
193
0
  dst->line = src->line;
194
0
}
195
196
197
// global_next_library contains the next custom library value to return.
198
static int global_next_library = ERR_NUM_LIBS;
199
200
// global_next_library_mutex protects |global_next_library| from concurrent
201
// updates.
202
static CRYPTO_MUTEX global_next_library_mutex = CRYPTO_MUTEX_INIT;
203
204
0
static void err_state_free(void *statep) {
205
0
  ERR_STATE *state = statep;
206
207
0
  if (state == NULL) {
208
0
    return;
209
0
  }
210
211
0
  for (unsigned i = 0; i < ERR_NUM_ERRORS; i++) {
212
0
    err_clear(&state->errors[i]);
213
0
  }
214
0
  free(state->to_free);
215
0
  free(state);
216
0
}
217
218
// err_get_state gets the ERR_STATE object for the current thread.
219
5.20k
static ERR_STATE *err_get_state(void) {
220
5.20k
  ERR_STATE *state = CRYPTO_get_thread_local(OPENSSL_THREAD_LOCAL_ERR);
221
5.20k
  if (state == NULL) {
222
2
    state = malloc(sizeof(ERR_STATE));
223
2
    if (state == NULL) {
224
0
      return NULL;
225
0
    }
226
2
    OPENSSL_memset(state, 0, sizeof(ERR_STATE));
227
2
    if (!CRYPTO_set_thread_local(OPENSSL_THREAD_LOCAL_ERR, state,
228
2
                                 err_state_free)) {
229
0
      return NULL;
230
0
    }
231
2
  }
232
233
5.20k
  return state;
234
5.20k
}
235
236
static uint32_t get_error_values(int inc, int top, const char **file, int *line,
237
                                 const char **data, int *flags) {
238
  unsigned i = 0;
239
  ERR_STATE *state;
240
  struct err_error_st *error;
241
  uint32_t ret;
242
243
  state = err_get_state();
244
  if (state == NULL || state->bottom == state->top) {
245
    return 0;
246
  }
247
248
  if (top) {
249
    assert(!inc);
250
    // last error
251
    i = state->top;
252
  } else {
253
    i = (state->bottom + 1) % ERR_NUM_ERRORS;
254
  }
255
256
  error = &state->errors[i];
257
  ret = error->packed;
258
259
  if (file != NULL && line != NULL) {
260
    if (error->file == NULL) {
261
      *file = "NA";
262
      *line = 0;
263
    } else {
264
      *file = error->file;
265
      *line = error->line;
266
    }
267
  }
268
269
  if (data != NULL) {
270
    if (error->data == NULL) {
271
      *data = "";
272
      if (flags != NULL) {
273
        *flags = 0;
274
      }
275
    } else {
276
      *data = error->data;
277
      if (flags != NULL) {
278
        // Without |ERR_FLAG_MALLOCED|, rust-openssl assumes the string has a
279
        // static lifetime. In both cases, we retain ownership of the string,
280
        // and the caller is not expected to free it.
281
        *flags = ERR_FLAG_STRING | ERR_FLAG_MALLOCED;
282
      }
283
      // If this error is being removed, take ownership of data from
284
      // the error. The semantics are such that the caller doesn't
285
      // take ownership either. Instead the error system takes
286
      // ownership and retains it until the next call that affects the
287
      // error queue.
288
      if (inc) {
289
        if (error->data != NULL) {
290
          free(state->to_free);
291
          state->to_free = error->data;
292
        }
293
        error->data = NULL;
294
      }
295
    }
296
  }
297
298
  if (inc) {
299
    assert(!top);
300
    err_clear(error);
301
    state->bottom = i;
302
  }
303
304
  return ret;
305
}
306
307
0
uint32_t ERR_get_error(void) {
308
0
  return get_error_values(1 /* inc */, 0 /* bottom */, NULL, NULL, NULL, NULL);
309
0
}
310
311
0
uint32_t ERR_get_error_line(const char **file, int *line) {
312
0
  return get_error_values(1 /* inc */, 0 /* bottom */, file, line, NULL, NULL);
313
0
}
314
315
uint32_t ERR_get_error_line_data(const char **file, int *line,
316
0
                                 const char **data, int *flags) {
317
0
  return get_error_values(1 /* inc */, 0 /* bottom */, file, line, data, flags);
318
0
}
319
320
0
uint32_t ERR_peek_error(void) {
321
0
  return get_error_values(0 /* peek */, 0 /* bottom */, NULL, NULL, NULL, NULL);
322
0
}
323
324
0
uint32_t ERR_peek_error_line(const char **file, int *line) {
325
0
  return get_error_values(0 /* peek */, 0 /* bottom */, file, line, NULL, NULL);
326
0
}
327
328
uint32_t ERR_peek_error_line_data(const char **file, int *line,
329
0
                                  const char **data, int *flags) {
330
0
  return get_error_values(0 /* peek */, 0 /* bottom */, file, line, data,
331
0
                          flags);
332
0
}
333
334
8
uint32_t ERR_peek_last_error(void) {
335
8
  return get_error_values(0 /* peek */, 1 /* top */, NULL, NULL, NULL, NULL);
336
8
}
337
338
0
uint32_t ERR_peek_last_error_line(const char **file, int *line) {
339
0
  return get_error_values(0 /* peek */, 1 /* top */, file, line, NULL, NULL);
340
0
}
341
342
uint32_t ERR_peek_last_error_line_data(const char **file, int *line,
343
0
                                       const char **data, int *flags) {
344
0
  return get_error_values(0 /* peek */, 1 /* top */, file, line, data, flags);
345
0
}
346
347
23
void ERR_clear_error(void) {
348
23
  ERR_STATE *const state = err_get_state();
349
23
  unsigned i;
350
351
23
  if (state == NULL) {
352
0
    return;
353
0
  }
354
355
391
  for (i = 0; i < ERR_NUM_ERRORS; i++) {
356
368
    err_clear(&state->errors[i]);
357
368
  }
358
23
  free(state->to_free);
359
23
  state->to_free = NULL;
360
361
23
  state->top = state->bottom = 0;
362
23
}
363
364
0
void ERR_remove_thread_state(const CRYPTO_THREADID *tid) {
365
0
  if (tid != NULL) {
366
0
    assert(0);
367
0
    return;
368
0
  }
369
370
0
  ERR_clear_error();
371
0
}
372
373
0
int ERR_get_next_error_library(void) {
374
0
  int ret;
375
376
0
  CRYPTO_MUTEX_lock_write(&global_next_library_mutex);
377
0
  ret = global_next_library++;
378
0
  CRYPTO_MUTEX_unlock_write(&global_next_library_mutex);
379
380
0
  return ret;
381
0
}
382
383
0
void ERR_remove_state(unsigned long pid) {
384
0
  ERR_clear_error();
385
0
}
386
387
0
void ERR_clear_system_error(void) {
388
0
  errno = 0;
389
0
}
390
391
// err_string_cmp is a compare function for searching error values with
392
// |bsearch| in |err_string_lookup|.
393
0
static int err_string_cmp(const void *a, const void *b) {
394
0
  const uint32_t a_key = *((const uint32_t*) a) >> 15;
395
0
  const uint32_t b_key = *((const uint32_t*) b) >> 15;
396
397
0
  if (a_key < b_key) {
398
0
    return -1;
399
0
  } else if (a_key > b_key) {
400
0
    return 1;
401
0
  } else {
402
0
    return 0;
403
0
  }
404
0
}
405
406
// err_string_lookup looks up the string associated with |lib| and |key| in
407
// |values| and |string_data|. It returns the string or NULL if not found.
408
static const char *err_string_lookup(uint32_t lib, uint32_t key,
409
                                     const uint32_t *values,
410
                                     size_t num_values,
411
0
                                     const char *string_data) {
412
  // |values| points to data in err_data.h, which is generated by
413
  // err_data_generate.go. It's an array of uint32_t values. Each value has the
414
  // following structure:
415
  //   | lib  |    key    |    offset     |
416
  //   |6 bits|  11 bits  |    15 bits    |
417
  //
418
  // The |lib| value is a library identifier: one of the |ERR_LIB_*| values.
419
  // The |key| is a reason code, depending on the context.
420
  // The |offset| is the number of bytes from the start of |string_data| where
421
  // the (NUL terminated) string for this value can be found.
422
  //
423
  // Values are sorted based on treating the |lib| and |key| part as an
424
  // unsigned integer.
425
0
  if (lib >= (1 << 6) || key >= (1 << 11)) {
426
0
    return NULL;
427
0
  }
428
0
  uint32_t search_key = lib << 26 | key << 15;
429
0
  const uint32_t *result = bsearch(&search_key, values, num_values,
430
0
                                   sizeof(uint32_t), err_string_cmp);
431
0
  if (result == NULL) {
432
0
    return NULL;
433
0
  }
434
435
0
  return &string_data[(*result) & 0x7fff];
436
0
}
437
438
typedef struct library_name_st {
439
  const char *str;
440
  const char *symbol;
441
  const char *reason_symbol;
442
} LIBRARY_NAME;
443
444
static const LIBRARY_NAME kLibraryNames[ERR_NUM_LIBS] = {
445
    {"invalid library (0)", NULL, NULL},
446
    {"unknown library", "NONE", "NONE_LIB"},
447
    {"system library", "SYS", "SYS_LIB"},
448
    {"bignum routines", "BN", "BN_LIB"},
449
    {"RSA routines", "RSA", "RSA_LIB"},
450
    {"Diffie-Hellman routines", "DH", "DH_LIB"},
451
    {"public key routines", "EVP", "EVP_LIB"},
452
    {"memory buffer routines", "BUF", "BUF_LIB"},
453
    {"object identifier routines", "OBJ", "OBJ_LIB"},
454
    {"PEM routines", "PEM", "PEM_LIB"},
455
    {"DSA routines", "DSA", "DSA_LIB"},
456
    {"X.509 certificate routines", "X509", "X509_LIB"},
457
    {"ASN.1 encoding routines", "ASN1", "ASN1_LIB"},
458
    {"configuration file routines", "CONF", "CONF_LIB"},
459
    {"common libcrypto routines", "CRYPTO", "CRYPTO_LIB"},
460
    {"elliptic curve routines", "EC", "EC_LIB"},
461
    {"SSL routines", "SSL", "SSL_LIB"},
462
    {"BIO routines", "BIO", "BIO_LIB"},
463
    {"PKCS7 routines", "PKCS7", "PKCS7_LIB"},
464
    {"PKCS8 routines", "PKCS8", "PKCS8_LIB"},
465
    {"X509 V3 routines", "X509V3", "X509V3_LIB"},
466
    {"random number generator", "RAND", "RAND_LIB"},
467
    {"ENGINE routines", "ENGINE", "ENGINE_LIB"},
468
    {"OCSP routines", "OCSP", "OCSP_LIB"},
469
    {"UI routines", "UI", "UI_LIB"},
470
    {"COMP routines", "COMP", "COMP_LIB"},
471
    {"ECDSA routines", "ECDSA", "ECDSA_LIB"},
472
    {"ECDH routines", "ECDH", "ECDH_LIB"},
473
    {"HMAC routines", "HMAC", "HMAC_LIB"},
474
    {"Digest functions", "DIGEST", "DIGEST_LIB"},
475
    {"Cipher functions", "CIPHER", "CIPHER_LIB"},
476
    {"HKDF functions", "HKDF", "HKDF_LIB"},
477
    {"Trust Token functions", "TRUST_TOKEN", "TRUST_TOKEN_LIB"},
478
    {"User defined functions", "USER", "USER_LIB"},
479
};
480
481
0
static const char *err_lib_error_string(uint32_t packed_error) {
482
0
  const uint32_t lib = ERR_GET_LIB(packed_error);
483
0
  return lib >= ERR_NUM_LIBS ? NULL : kLibraryNames[lib].str;
484
0
}
485
486
0
const char *ERR_lib_error_string(uint32_t packed_error) {
487
0
  const char *ret = err_lib_error_string(packed_error);
488
0
  return ret == NULL ? "unknown library" : ret;
489
0
}
490
491
0
const char *ERR_lib_symbol_name(uint32_t packed_error) {
492
0
  const uint32_t lib = ERR_GET_LIB(packed_error);
493
0
  return lib >= ERR_NUM_LIBS ? NULL : kLibraryNames[lib].symbol;
494
0
}
495
496
0
const char *ERR_func_error_string(uint32_t packed_error) {
497
0
  return "OPENSSL_internal";
498
0
}
499
500
0
static const char *err_reason_error_string(uint32_t packed_error, int symbol) {
501
0
  const uint32_t lib = ERR_GET_LIB(packed_error);
502
0
  const uint32_t reason = ERR_GET_REASON(packed_error);
503
504
0
  if (lib == ERR_LIB_SYS) {
505
0
    if (!symbol && reason < 127) {
506
0
      return strerror(reason);
507
0
    }
508
0
    return NULL;
509
0
  }
510
511
0
  if (reason < ERR_NUM_LIBS) {
512
0
    return symbol ? kLibraryNames[reason].reason_symbol
513
0
                  : kLibraryNames[reason].str;
514
0
  }
515
516
0
  if (reason < 100) {
517
    // TODO(davidben): All our other reason strings match the symbol name. Only
518
    // the common ones differ. Should we just consistently return the symbol
519
    // name?
520
0
    switch (reason) {
521
0
      case ERR_R_MALLOC_FAILURE:
522
0
        return symbol ? "MALLOC_FAILURE" : "malloc failure";
523
0
      case ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED:
524
0
        return symbol ? "SHOULD_NOT_HAVE_BEEN_CALLED"
525
0
                      : "function should not have been called";
526
0
      case ERR_R_PASSED_NULL_PARAMETER:
527
0
        return symbol ? "PASSED_NULL_PARAMETER" : "passed a null parameter";
528
0
      case ERR_R_INTERNAL_ERROR:
529
0
        return symbol ? "INTERNAL_ERROR" : "internal error";
530
0
      case ERR_R_OVERFLOW:
531
0
        return symbol ? "OVERFLOW" : "overflow";
532
0
      default:
533
0
        return NULL;
534
0
    }
535
0
  }
536
537
  // Unlike OpenSSL, BoringSSL's reason strings already match symbol name, so we
538
  // do not need to check |symbol|.
539
0
  return err_string_lookup(lib, reason, kOpenSSLReasonValues,
540
0
                           kOpenSSLReasonValuesLen, kOpenSSLReasonStringData);
541
0
}
542
543
0
const char *ERR_reason_error_string(uint32_t packed_error) {
544
0
  const char *ret = err_reason_error_string(packed_error, /*symbol=*/0);
545
0
  return ret == NULL ? "unknown error" : ret;
546
0
}
547
548
0
const char *ERR_reason_symbol_name(uint32_t packed_error) {
549
0
  return err_reason_error_string(packed_error, /*symbol=*/1);
550
0
}
551
552
0
char *ERR_error_string(uint32_t packed_error, char *ret) {
553
0
  static char buf[ERR_ERROR_STRING_BUF_LEN];
554
555
0
  if (ret == NULL) {
556
    // TODO(fork): remove this.
557
0
    ret = buf;
558
0
  }
559
560
0
#if !defined(NDEBUG)
561
  // This is aimed to help catch callers who don't provide
562
  // |ERR_ERROR_STRING_BUF_LEN| bytes of space.
563
0
  OPENSSL_memset(ret, 0, ERR_ERROR_STRING_BUF_LEN);
564
0
#endif
565
566
0
  return ERR_error_string_n(packed_error, ret, ERR_ERROR_STRING_BUF_LEN);
567
0
}
568
569
0
char *ERR_error_string_n(uint32_t packed_error, char *buf, size_t len) {
570
0
  if (len == 0) {
571
0
    return NULL;
572
0
  }
573
574
0
  unsigned lib = ERR_GET_LIB(packed_error);
575
0
  unsigned reason = ERR_GET_REASON(packed_error);
576
577
0
  const char *lib_str = err_lib_error_string(packed_error);
578
0
  const char *reason_str = err_reason_error_string(packed_error, /*symbol=*/0);
579
580
0
  char lib_buf[32], reason_buf[32];
581
0
  if (lib_str == NULL) {
582
0
    snprintf(lib_buf, sizeof(lib_buf), "lib(%u)", lib);
583
0
    lib_str = lib_buf;
584
0
  }
585
586
0
  if (reason_str == NULL) {
587
0
    snprintf(reason_buf, sizeof(reason_buf), "reason(%u)", reason);
588
0
    reason_str = reason_buf;
589
0
  }
590
591
0
  int ret = snprintf(buf, len, "error:%08" PRIx32 ":%s:OPENSSL_internal:%s",
592
0
                     packed_error, lib_str, reason_str);
593
0
  if (ret >= 0 && (size_t)ret >= len) {
594
    // The output was truncated; make sure we always have 5 colon-separated
595
    // fields, i.e. 4 colons.
596
0
    static const unsigned num_colons = 4;
597
0
    unsigned i;
598
0
    char *s = buf;
599
600
0
    if (len <= num_colons) {
601
      // In this situation it's not possible to ensure that the correct number
602
      // of colons are included in the output.
603
0
      return buf;
604
0
    }
605
606
0
    for (i = 0; i < num_colons; i++) {
607
0
      char *colon = strchr(s, ':');
608
0
      char *last_pos = &buf[len - 1] - num_colons + i;
609
610
0
      if (colon == NULL || colon > last_pos) {
611
        // set colon |i| at last possible position (buf[len-1] is the
612
        // terminating 0). If we're setting this colon, then all whole of the
613
        // rest of the string must be colons in order to have the correct
614
        // number.
615
0
        OPENSSL_memset(last_pos, ':', num_colons - i);
616
0
        break;
617
0
      }
618
619
0
      s = colon + 1;
620
0
    }
621
0
  }
622
623
0
  return buf;
624
0
}
625
626
0
void ERR_print_errors_cb(ERR_print_errors_callback_t callback, void *ctx) {
627
0
  char buf[ERR_ERROR_STRING_BUF_LEN];
628
0
  char buf2[1024];
629
0
  const char *file, *data;
630
0
  int line, flags;
631
0
  uint32_t packed_error;
632
633
  // thread_hash is the least-significant bits of the |ERR_STATE| pointer value
634
  // for this thread.
635
0
  const unsigned long thread_hash = (uintptr_t) err_get_state();
636
637
0
  for (;;) {
638
0
    packed_error = ERR_get_error_line_data(&file, &line, &data, &flags);
639
0
    if (packed_error == 0) {
640
0
      break;
641
0
    }
642
643
0
    ERR_error_string_n(packed_error, buf, sizeof(buf));
644
0
    snprintf(buf2, sizeof(buf2), "%lu:%s:%s:%d:%s\n", thread_hash, buf, file,
645
0
             line, (flags & ERR_FLAG_STRING) ? data : "");
646
0
    if (callback(buf2, strlen(buf2), ctx) <= 0) {
647
0
      break;
648
0
    }
649
0
  }
650
0
}
651
652
0
static int print_errors_to_file(const char* msg, size_t msg_len, void* ctx) {
653
0
  assert(msg[msg_len] == '\0');
654
0
  FILE* fp = ctx;
655
0
  int res = fputs(msg, fp);
656
0
  return res < 0 ? 0 : 1;
657
0
}
658
659
0
void ERR_print_errors_fp(FILE *file) {
660
0
  ERR_print_errors_cb(print_errors_to_file, file);
661
0
}
662
663
// err_set_error_data sets the data on the most recent error.
664
0
static void err_set_error_data(char *data) {
665
0
  ERR_STATE *const state = err_get_state();
666
0
  struct err_error_st *error;
667
668
0
  if (state == NULL || state->top == state->bottom) {
669
0
    free(data);
670
0
    return;
671
0
  }
672
673
0
  error = &state->errors[state->top];
674
675
0
  free(error->data);
676
0
  error->data = data;
677
0
}
678
679
void ERR_put_error(int library, int unused, int reason, const char *file,
680
5.18k
                   unsigned line) {
681
5.18k
  ERR_STATE *const state = err_get_state();
682
5.18k
  struct err_error_st *error;
683
684
5.18k
  if (state == NULL) {
685
0
    return;
686
0
  }
687
688
5.18k
  if (library == ERR_LIB_SYS && reason == 0) {
689
#if defined(OPENSSL_WINDOWS)
690
    reason = GetLastError();
691
#else
692
0
    reason = errno;
693
0
#endif
694
0
  }
695
696
5.18k
  state->top = (state->top + 1) % ERR_NUM_ERRORS;
697
5.18k
  if (state->top == state->bottom) {
698
4.83k
    state->bottom = (state->bottom + 1) % ERR_NUM_ERRORS;
699
4.83k
  }
700
701
5.18k
  error = &state->errors[state->top];
702
5.18k
  err_clear(error);
703
5.18k
  error->file = file;
704
5.18k
  error->line = line;
705
5.18k
  error->packed = ERR_PACK(library, reason);
706
5.18k
}
707
708
// ERR_add_error_data_vdata takes a variable number of const char* pointers,
709
// concatenates them and sets the result as the data on the most recent
710
// error.
711
0
static void err_add_error_vdata(unsigned num, va_list args) {
712
0
  size_t total_size = 0;
713
0
  const char *substr;
714
0
  char *buf;
715
716
0
  va_list args_copy;
717
0
  va_copy(args_copy, args);
718
0
  for (size_t i = 0; i < num; i++) {
719
0
    substr = va_arg(args_copy, const char *);
720
0
    if (substr == NULL) {
721
0
      continue;
722
0
    }
723
0
    size_t substr_len = strlen(substr);
724
0
    if (SIZE_MAX - total_size < substr_len) {
725
0
      return; // Would overflow.
726
0
    }
727
0
    total_size += substr_len;
728
0
  }
729
0
  va_end(args_copy);
730
0
  if (total_size == SIZE_MAX) {
731
0
      return; // Would overflow.
732
0
  }
733
0
  total_size += 1; // NUL terminator.
734
0
  if ((buf = malloc(total_size)) == NULL) {
735
0
    return;
736
0
  }
737
0
  buf[0] = '\0';
738
0
  for (size_t i = 0; i < num; i++) {
739
0
    substr = va_arg(args, const char *);
740
0
    if (substr == NULL) {
741
0
      continue;
742
0
    }
743
0
    if (OPENSSL_strlcat(buf, substr, total_size) >= total_size) {
744
0
      assert(0); // should not be possible.
745
0
    }
746
0
  }
747
0
  va_end(args);
748
0
  err_set_error_data(buf);
749
0
}
750
751
0
void ERR_add_error_data(unsigned count, ...) {
752
0
  va_list args;
753
0
  va_start(args, count);
754
0
  err_add_error_vdata(count, args);
755
0
  va_end(args);
756
0
}
757
758
0
void ERR_add_error_dataf(const char *format, ...) {
759
0
  char *buf = NULL;
760
0
  va_list ap;
761
762
0
  va_start(ap, format);
763
0
  if (OPENSSL_vasprintf_internal(&buf, format, ap, /*system_malloc=*/1) == -1) {
764
0
    return;
765
0
  }
766
0
  va_end(ap);
767
768
0
  err_set_error_data(buf);
769
0
}
770
771
0
void ERR_set_error_data(char *data, int flags) {
772
0
  if (!(flags & ERR_FLAG_STRING)) {
773
    // We do not support non-string error data.
774
0
    assert(0);
775
0
    return;
776
0
  }
777
  // We can not use OPENSSL_strdup because we don't want to call OPENSSL_malloc,
778
  // which can affect the error stack.
779
0
  char *copy = strdup_libc_malloc(data);
780
0
  if (copy != NULL) {
781
0
    err_set_error_data(copy);
782
0
  }
783
0
  if (flags & ERR_FLAG_MALLOCED) {
784
    // We can not take ownership of |data| directly because it is allocated with
785
    // |OPENSSL_malloc| and we will free it with system |free| later.
786
0
    OPENSSL_free(data);
787
0
  }
788
0
}
789
790
0
int ERR_set_mark(void) {
791
0
  ERR_STATE *const state = err_get_state();
792
793
0
  if (state == NULL || state->bottom == state->top) {
794
0
    return 0;
795
0
  }
796
0
  state->errors[state->top].mark = 1;
797
0
  return 1;
798
0
}
799
800
int ERR_pop_to_mark(void) {
801
  ERR_STATE *const state = err_get_state();
802
803
  if (state == NULL) {
804
    return 0;
805
  }
806
807
  while (state->bottom != state->top) {
808
    struct err_error_st *error = &state->errors[state->top];
809
810
    if (error->mark) {
811
      error->mark = 0;
812
      return 1;
813
    }
814
815
    err_clear(error);
816
    if (state->top == 0) {
817
      state->top = ERR_NUM_ERRORS - 1;
818
    } else {
819
      state->top--;
820
    }
821
  }
822
823
  return 0;
824
}
825
826
0
void ERR_load_crypto_strings(void) {}
827
828
0
void ERR_free_strings(void) {}
829
830
0
void ERR_load_BIO_strings(void) {}
831
832
0
void ERR_load_ERR_strings(void) {}
833
834
0
void ERR_load_RAND_strings(void) {}
835
836
struct err_save_state_st {
837
  struct err_error_st *errors;
838
  size_t num_errors;
839
};
840
841
0
void ERR_SAVE_STATE_free(ERR_SAVE_STATE *state) {
842
0
  if (state == NULL) {
843
0
    return;
844
0
  }
845
0
  for (size_t i = 0; i < state->num_errors; i++) {
846
0
    err_clear(&state->errors[i]);
847
0
  }
848
0
  free(state->errors);
849
0
  free(state);
850
0
}
851
852
0
ERR_SAVE_STATE *ERR_save_state(void) {
853
0
  ERR_STATE *const state = err_get_state();
854
0
  if (state == NULL || state->top == state->bottom) {
855
0
    return NULL;
856
0
  }
857
858
0
  ERR_SAVE_STATE *ret = malloc(sizeof(ERR_SAVE_STATE));
859
0
  if (ret == NULL) {
860
0
    return NULL;
861
0
  }
862
863
  // Errors are stored in the range (bottom, top].
864
0
  size_t num_errors = state->top >= state->bottom
865
0
                          ? state->top - state->bottom
866
0
                          : ERR_NUM_ERRORS + state->top - state->bottom;
867
0
  assert(num_errors < ERR_NUM_ERRORS);
868
0
  ret->errors = malloc(num_errors * sizeof(struct err_error_st));
869
0
  if (ret->errors == NULL) {
870
0
    free(ret);
871
0
    return NULL;
872
0
  }
873
0
  OPENSSL_memset(ret->errors, 0, num_errors * sizeof(struct err_error_st));
874
0
  ret->num_errors = num_errors;
875
876
0
  for (size_t i = 0; i < num_errors; i++) {
877
0
    size_t j = (state->bottom + i + 1) % ERR_NUM_ERRORS;
878
0
    err_copy(&ret->errors[i], &state->errors[j]);
879
0
  }
880
0
  return ret;
881
0
}
882
883
0
void ERR_restore_state(const ERR_SAVE_STATE *state) {
884
0
  if (state == NULL || state->num_errors == 0) {
885
0
    ERR_clear_error();
886
0
    return;
887
0
  }
888
889
0
  if (state->num_errors >= ERR_NUM_ERRORS) {
890
0
    abort();
891
0
  }
892
893
0
  ERR_STATE *const dst = err_get_state();
894
0
  if (dst == NULL) {
895
0
    return;
896
0
  }
897
898
0
  for (size_t i = 0; i < state->num_errors; i++) {
899
0
    err_copy(&dst->errors[i], &state->errors[i]);
900
0
  }
901
0
  dst->top = (unsigned)(state->num_errors - 1);
902
0
  dst->bottom = ERR_NUM_ERRORS - 1;
903
0
}