Coverage Report

Created: 2026-08-14 07:01

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/boringssl/crypto/mem.cc
Line
Count
Source
1
// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
#include <openssl/mem.h>
16
17
#include <assert.h>
18
#include <errno.h>
19
#include <limits.h>
20
#include <stdarg.h>
21
#include <stdio.h>
22
#include <stdlib.h>
23
24
#include <openssl/err.h>
25
26
#if defined(OPENSSL_WINDOWS)
27
#include <windows.h>
28
#endif
29
30
#if defined(BORINGSSL_MALLOC_FAILURE_TESTING)
31
#include <errno.h>
32
#include <signal.h>
33
#include <unistd.h>
34
#endif
35
36
#include "internal.h"
37
38
39
using namespace bssl;
40
41
169M
#define OPENSSL_MALLOC_PREFIX 8
42
static_assert(OPENSSL_MALLOC_PREFIX >= sizeof(size_t), "size_t too large");
43
44
#if defined(OPENSSL_ASAN)
45
extern "C" {
46
void __asan_poison_memory_region(const volatile void *addr, size_t size);
47
void __asan_unpoison_memory_region(const volatile void *addr, size_t size);
48
}
49
#else
50
25.7M
static void __asan_poison_memory_region(const void *addr, size_t size) {}
51
25.7M
static void __asan_unpoison_memory_region(const void *addr, size_t size) {}
52
#endif
53
54
// Windows doesn't really support weak symbols as of May 2019, and Clang on
55
// Windows will emit strong symbols instead. See
56
// https://bugs.llvm.org/show_bug.cgi?id=37598
57
//
58
// EDK2 targets UEFI but builds as ELF and then translates the binary to
59
// COFF(!). Thus it builds with __ELF__ defined but cannot actually cope with
60
// weak symbols.
61
#if !defined(__EDK2_BORINGSSL__) && defined(__ELF__) && defined(__GNUC__)
62
#define WEAK_SYMBOL_FUNC(rettype, name, args) \
63
  extern "C" {                                \
64
  rettype name args __attribute__((weak));    \
65
  }
66
#else
67
#define WEAK_SYMBOL_FUNC(rettype, name, args) \
68
  static rettype(*const name) args = nullptr;
69
#endif
70
71
#if defined(BORINGSSL_DETECT_SDALLOCX)
72
// sdallocx is a sized `free` function. By passing the size (which we happen to
73
// always know in BoringSSL), the malloc implementation can save work. We cannot
74
// depend on `sdallocx` being available, however, so it's a weak symbol.
75
//
76
// This mechanism is kept opt-in because it assumes that, when `sdallocx` is
77
// defined, it is part of the same allocator as `malloc`. This is usually true
78
// but may break if `malloc` does not implement `sdallocx`, but some other
79
// allocator with `sdallocx` is imported which does.
80
WEAK_SYMBOL_FUNC(void, sdallocx, (void *ptr, size_t size, int flags))
81
#else
82
static void (*const sdallocx)(void *ptr, size_t size, int flags) = nullptr;
83
#endif
84
85
// The following three functions can be defined to override default heap
86
// allocation and freeing. If defined, it is the responsibility of
87
// `OPENSSL_memory_free` to zero out the memory before returning it to the
88
// system. `OPENSSL_memory_free` will not be passed NULL pointers.
89
//
90
// WARNING: These functions are called on every allocation and free in
91
// BoringSSL across the entire process. They may be called by any code in the
92
// process which calls BoringSSL, including in process initializers and thread
93
// destructors. When called, BoringSSL may hold pthreads locks. Any other code
94
// in the process which, directly or indirectly, calls BoringSSL may be on the
95
// call stack and may itself be using arbitrary synchronization primitives.
96
//
97
// As a result, these functions may not have the usual programming environment
98
// available to most C or C++ code. In particular, they may not call into
99
// BoringSSL, or any library which depends on BoringSSL. Any synchronization
100
// primitives used must tolerate every other synchronization primitive linked
101
// into the process, including pthreads locks. Failing to meet these constraints
102
// may result in deadlocks, crashes, or memory corruption.
103
WEAK_SYMBOL_FUNC(void *, OPENSSL_memory_alloc, (size_t size))
104
WEAK_SYMBOL_FUNC(void, OPENSSL_memory_free, (void *ptr))
105
WEAK_SYMBOL_FUNC(size_t, OPENSSL_memory_get_size, (void *ptr))
106
107
#if defined(BORINGSSL_MALLOC_FAILURE_TESTING)
108
static StaticMutex malloc_failure_lock;
109
static uint64_t current_malloc_count = 0;
110
static uint64_t malloc_number_to_fail = 0;
111
static int malloc_failure_enabled = 0, break_on_malloc_fail = 0,
112
           any_malloc_failed = 0, disable_malloc_failures = 0;
113
114
static void malloc_exit_handler() {
115
  MutexReadLock lock(&malloc_failure_lock);
116
  if (any_malloc_failed) {
117
    // Signal to the test driver that some allocation failed, so it knows to
118
    // increment the counter and continue.
119
    _exit(88);
120
  }
121
}
122
123
static void init_malloc_failure() {
124
  const char *env = getenv("MALLOC_NUMBER_TO_FAIL");
125
  if (env != nullptr && env[0] != 0) {
126
    char *endptr;
127
    malloc_number_to_fail = strtoull(env, &endptr, 10);
128
    if (*endptr == 0) {
129
      malloc_failure_enabled = 1;
130
      atexit(malloc_exit_handler);
131
    }
132
  }
133
  break_on_malloc_fail = getenv("MALLOC_BREAK_ON_FAIL") != nullptr;
134
}
135
136
// should_fail_allocation returns one if the current allocation should fail and
137
// zero otherwise.
138
static int should_fail_allocation() {
139
  static CRYPTO_once_t once = CRYPTO_ONCE_INIT;
140
  CRYPTO_once(&once, init_malloc_failure);
141
  if (!malloc_failure_enabled || disable_malloc_failures) {
142
    return 0;
143
  }
144
145
  // We lock just so multi-threaded tests are still correct, but we won't test
146
  // every malloc exhaustively.
147
  malloc_failure_lock.LockWrite();
148
  int should_fail = current_malloc_count == malloc_number_to_fail;
149
  current_malloc_count++;
150
  any_malloc_failed = any_malloc_failed || should_fail;
151
  malloc_failure_lock.UnlockWrite();
152
153
  if (should_fail && break_on_malloc_fail) {
154
    raise(SIGTRAP);
155
  }
156
  if (should_fail) {
157
    errno = ENOMEM;
158
  }
159
  return should_fail;
160
}
161
162
void bssl::OPENSSL_reset_malloc_counter_for_testing() {
163
  MutexWriteLock lock(&malloc_failure_lock);
164
  current_malloc_count = 0;
165
}
166
167
void bssl::OPENSSL_disable_malloc_failures_for_testing() {
168
  MutexWriteLock lock(&malloc_failure_lock);
169
  BSSL_CHECK(!disable_malloc_failures);
170
  disable_malloc_failures = 1;
171
}
172
173
void bssl::OPENSSL_enable_malloc_failures_for_testing() {
174
  MutexWriteLock lock(&malloc_failure_lock);
175
  BSSL_CHECK(disable_malloc_failures);
176
  disable_malloc_failures = 0;
177
}
178
179
#else
180
23.0M
static int should_fail_allocation() { return 0; }
181
#endif
182
183
23.0M
void *OPENSSL_malloc(size_t size) {
184
23.0M
  void *ptr = nullptr;
185
23.0M
  if (should_fail_allocation()) {
186
0
    goto err;
187
0
  }
188
189
23.0M
  if (OPENSSL_memory_alloc != nullptr) {
190
0
    assert(OPENSSL_memory_free != nullptr);
191
0
    assert(OPENSSL_memory_get_size != nullptr);
192
0
    void *ptr2 = OPENSSL_memory_alloc(size);
193
0
    if (ptr2 == nullptr && size != 0) {
194
0
      goto err;
195
0
    }
196
0
    return ptr2;
197
0
  }
198
199
23.0M
  if (size + OPENSSL_MALLOC_PREFIX < size) {
200
0
    goto err;
201
0
  }
202
203
23.0M
  ptr = malloc(size + OPENSSL_MALLOC_PREFIX);
204
23.0M
  if (ptr == nullptr) {
205
0
    goto err;
206
0
  }
207
208
23.0M
  *(size_t *)ptr = size;
209
210
23.0M
  __asan_poison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
211
23.0M
  return ((uint8_t *)ptr) + OPENSSL_MALLOC_PREFIX;
212
213
0
err:
214
  // This only works because ERR does not call OPENSSL_malloc.
215
0
  OPENSSL_PUT_ERROR(CRYPTO, ERR_R_MALLOC_FAILURE);
216
0
  return nullptr;
217
23.0M
}
218
219
2.35M
void *OPENSSL_zalloc(size_t size) {
220
2.35M
  void *ret = OPENSSL_malloc(size);
221
2.35M
  if (ret != nullptr) {
222
2.35M
    OPENSSL_memset(ret, 0, size);
223
2.35M
  }
224
2.35M
  return ret;
225
2.35M
}
226
227
1.74M
void *OPENSSL_calloc(size_t num, size_t size) {
228
1.74M
  if (size != 0 && num > SIZE_MAX / size) {
229
0
    OPENSSL_PUT_ERROR(CRYPTO, ERR_R_OVERFLOW);
230
0
    return nullptr;
231
0
  }
232
233
1.74M
  return OPENSSL_zalloc(num * size);
234
1.74M
}
235
236
40.7M
void OPENSSL_free(void *orig_ptr) {
237
40.7M
  if (orig_ptr == nullptr) {
238
17.7M
    return;
239
17.7M
  }
240
241
23.0M
  if (OPENSSL_memory_free != nullptr) {
242
0
    OPENSSL_memory_free(orig_ptr);
243
0
    return;
244
0
  }
245
246
23.0M
  void *ptr = ((uint8_t *)orig_ptr) - OPENSSL_MALLOC_PREFIX;
247
23.0M
  __asan_unpoison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
248
249
23.0M
  size_t size = *(size_t *)ptr;
250
23.0M
  OPENSSL_cleanse(ptr, size + OPENSSL_MALLOC_PREFIX);
251
252
// ASan knows to intercept malloc and free, but not sdallocx.
253
#if defined(OPENSSL_ASAN)
254
  (void)sdallocx;
255
  free(ptr);
256
#else
257
23.0M
  if (sdallocx) {
258
0
    sdallocx(ptr, size + OPENSSL_MALLOC_PREFIX, 0 /* flags */);
259
23.0M
  } else {
260
23.0M
    free(ptr);
261
23.0M
  }
262
23.0M
#endif
263
23.0M
}
264
265
3.11M
void *OPENSSL_realloc(void *orig_ptr, size_t new_size) {
266
3.11M
  if (orig_ptr == nullptr) {
267
363k
    return OPENSSL_malloc(new_size);
268
363k
  }
269
270
2.75M
  size_t old_size;
271
2.75M
  if (OPENSSL_memory_get_size != nullptr) {
272
0
    old_size = OPENSSL_memory_get_size(orig_ptr);
273
2.75M
  } else {
274
2.75M
    void *ptr = ((uint8_t *)orig_ptr) - OPENSSL_MALLOC_PREFIX;
275
2.75M
    __asan_unpoison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
276
2.75M
    old_size = *(size_t *)ptr;
277
2.75M
    __asan_poison_memory_region(ptr, OPENSSL_MALLOC_PREFIX);
278
2.75M
  }
279
280
2.75M
  void *ret = OPENSSL_malloc(new_size);
281
2.75M
  if (ret == nullptr) {
282
0
    return nullptr;
283
0
  }
284
285
2.75M
  size_t to_copy = new_size;
286
2.75M
  if (old_size < to_copy) {
287
2.75M
    to_copy = old_size;
288
2.75M
  }
289
290
2.75M
  memcpy(ret, orig_ptr, to_copy);
291
2.75M
  OPENSSL_free(orig_ptr);
292
293
2.75M
  return ret;
294
2.75M
}
295
296
26.2M
void OPENSSL_cleanse(void *ptr, size_t len) {
297
#if defined(OPENSSL_WINDOWS)
298
  SecureZeroMemory(ptr, len);
299
#else
300
26.2M
  OPENSSL_memset(ptr, 0, len);
301
  // As best as we can tell, this is sufficient to break any optimisations that
302
  // might try to eliminate "superfluous" memsets. If there's an easy way to
303
  // detect memset_s, it would be better to use that.
304
26.2M
  __asm__ __volatile__("" : : "r"(ptr) : "memory");
305
26.2M
#endif
306
26.2M
}
307
308
0
void OPENSSL_clear_free(void *ptr, size_t unused) { OPENSSL_free(ptr); }
309
310
0
int CRYPTO_secure_malloc_init(size_t size, size_t min_size) { return 0; }
311
312
0
int CRYPTO_secure_malloc_initialized() { return 0; }
313
314
0
size_t CRYPTO_secure_used() { return 0; }
315
316
0
void *OPENSSL_secure_malloc(size_t size) { return OPENSSL_malloc(size); }
317
318
0
void OPENSSL_secure_clear_free(void *ptr, size_t len) {
319
0
  OPENSSL_clear_free(ptr, len);
320
0
}
321
322
182k
int CRYPTO_memcmp(const void *in_a, const void *in_b, size_t len) {
323
182k
  const uint8_t *a = reinterpret_cast<const uint8_t *>(in_a);
324
182k
  const uint8_t *b = reinterpret_cast<const uint8_t *>(in_b);
325
182k
  uint8_t x = 0;
326
327
4.77M
  for (size_t i = 0; i < len; i++) {
328
4.58M
    x |= a[i] ^ b[i];
329
4.58M
  }
330
331
182k
  return x;
332
182k
}
333
334
0
uint32_t OPENSSL_hash32(const void *ptr, size_t len) {
335
  // These are the FNV-1a parameters for 32 bits.
336
0
  static const uint32_t kPrime = 16777619u;
337
0
  static const uint32_t kOffsetBasis = 2166136261u;
338
339
0
  const uint8_t *in = reinterpret_cast<const uint8_t *>(ptr);
340
0
  uint32_t h = kOffsetBasis;
341
342
0
  for (size_t i = 0; i < len; i++) {
343
0
    h ^= in[i];
344
0
    h *= kPrime;
345
0
  }
346
347
0
  return h;
348
0
}
349
350
0
uint32_t OPENSSL_strhash(const char *s) { return OPENSSL_hash32(s, strlen(s)); }
351
352
28.7k
size_t OPENSSL_strnlen(const char *s, size_t len) {
353
302k
  for (size_t i = 0; i < len; i++) {
354
273k
    if (s[i] == 0) {
355
0
      return i;
356
0
    }
357
273k
  }
358
359
28.7k
  return len;
360
28.7k
}
361
362
30.9k
char *OPENSSL_strdup(const char *s) {
363
30.9k
  if (s == nullptr) {
364
0
    return nullptr;
365
0
  }
366
  // Copy the NUL terminator.
367
30.9k
  return reinterpret_cast<char *>(OPENSSL_memdup(s, strlen(s) + 1));
368
30.9k
}
369
370
300k
int OPENSSL_isalpha(int c) {
371
300k
  return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
372
300k
}
373
374
4.42M
int OPENSSL_isdigit(int c) { return c >= '0' && c <= '9'; }
375
376
3.61k
int OPENSSL_isxdigit(int c) {
377
3.61k
  return OPENSSL_isdigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
378
3.61k
}
379
380
0
int OPENSSL_fromxdigit(uint8_t *out, int c) {
381
0
  if (OPENSSL_isdigit(c)) {
382
0
    *out = c - '0';
383
0
    return 1;
384
0
  }
385
0
  if ('a' <= c && c <= 'f') {
386
0
    *out = c - 'a' + 10;
387
0
    return 1;
388
0
  }
389
0
  if ('A' <= c && c <= 'F') {
390
0
    *out = c - 'A' + 10;
391
0
    return 1;
392
0
  }
393
0
  return 0;
394
0
}
395
396
300k
int OPENSSL_isalnum(int c) { return OPENSSL_isalpha(c) || OPENSSL_isdigit(c); }
397
398
7.30M
int OPENSSL_tolower(int c) {
399
7.30M
  if (c >= 'A' && c <= 'Z') {
400
1.31M
    return c + ('a' - 'A');
401
1.31M
  }
402
5.98M
  return c;
403
7.30M
}
404
405
25.2M
int OPENSSL_isspace(int c) {
406
25.2M
  return c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r' ||
407
25.1M
         c == ' ';
408
25.2M
}
409
410
0
int OPENSSL_strcasecmp(const char *a, const char *b) {
411
0
  for (size_t i = 0;; i++) {
412
0
    const int aa = OPENSSL_tolower(a[i]);
413
0
    const int bb = OPENSSL_tolower(b[i]);
414
415
0
    if (aa < bb) {
416
0
      return -1;
417
0
    } else if (aa > bb) {
418
0
      return 1;
419
0
    } else if (aa == 0) {
420
0
      return 0;
421
0
    }
422
0
  }
423
0
}
424
425
0
int OPENSSL_strncasecmp(const char *a, const char *b, size_t n) {
426
0
  for (size_t i = 0; i < n; i++) {
427
0
    const int aa = OPENSSL_tolower(a[i]);
428
0
    const int bb = OPENSSL_tolower(b[i]);
429
430
0
    if (aa < bb) {
431
0
      return -1;
432
0
    } else if (aa > bb) {
433
0
      return 1;
434
0
    } else if (aa == 0) {
435
0
      return 0;
436
0
    }
437
0
  }
438
439
0
  return 0;
440
0
}
441
442
0
int BIO_snprintf(char *buf, size_t n, const char *format, ...) {
443
0
  va_list args;
444
0
  va_start(args, format);
445
0
  int ret = BIO_vsnprintf(buf, n, format, args);
446
0
  va_end(args);
447
0
  return ret;
448
0
}
449
450
0
int BIO_vsnprintf(char *buf, size_t n, const char *format, va_list args) {
451
0
  return vsnprintf(buf, n, format, args);
452
0
}
453
454
int bssl::OPENSSL_vasprintf_internal(char **str, const char *format,
455
15.9k
                                     va_list args, int system_malloc) {
456
15.9k
  void *(*allocate)(size_t) = system_malloc ? malloc : OPENSSL_malloc;
457
15.9k
  void (*deallocate)(void *) = system_malloc ? free : OPENSSL_free;
458
15.9k
  void *(*reallocate)(void *, size_t) =
459
15.9k
      system_malloc ? realloc : OPENSSL_realloc;
460
15.9k
  char *candidate = nullptr;
461
15.9k
  size_t candidate_len = 64;  // TODO(bbe) what's the best initial size?
462
15.9k
  int ret;
463
464
15.9k
  if ((candidate = reinterpret_cast<char *>(allocate(candidate_len))) ==
465
15.9k
      nullptr) {
466
0
    goto err;
467
0
  }
468
15.9k
  va_list args_copy;
469
15.9k
  va_copy(args_copy, args);
470
15.9k
  ret = vsnprintf(candidate, candidate_len, format, args_copy);
471
15.9k
  va_end(args_copy);
472
15.9k
  if (ret < 0) {
473
0
    goto err;
474
0
  }
475
15.9k
  if ((size_t)ret >= candidate_len) {
476
    // Too big to fit in allocation.
477
51
    char *tmp;
478
479
51
    candidate_len = (size_t)ret + 1;
480
51
    if ((tmp = reinterpret_cast<char *>(
481
51
             reallocate(candidate, candidate_len))) == nullptr) {
482
0
      goto err;
483
0
    }
484
51
    candidate = tmp;
485
51
    ret = vsnprintf(candidate, candidate_len, format, args);
486
51
  }
487
  // At this point this should not happen unless vsnprintf is insane.
488
15.9k
  if (ret < 0 || (size_t)ret >= candidate_len) {
489
0
    goto err;
490
0
  }
491
15.9k
  *str = candidate;
492
15.9k
  return ret;
493
494
0
err:
495
0
  deallocate(candidate);
496
0
  *str = nullptr;
497
0
  errno = ENOMEM;
498
0
  return -1;
499
15.9k
}
500
501
937
int OPENSSL_vasprintf(char **str, const char *format, va_list args) {
502
937
  return OPENSSL_vasprintf_internal(str, format, args, /*system_malloc=*/0);
503
937
}
504
505
937
int OPENSSL_asprintf(char **str, const char *format, ...) {
506
937
  va_list args;
507
937
  va_start(args, format);
508
937
  int ret = OPENSSL_vasprintf(str, format, args);
509
937
  va_end(args);
510
937
  return ret;
511
937
}
512
513
28.7k
char *OPENSSL_strndup(const char *str, size_t size) {
514
28.7k
  size = OPENSSL_strnlen(str, size);
515
516
28.7k
  size_t alloc_size = size + 1;
517
28.7k
  if (alloc_size < size) {
518
    // overflow
519
0
    OPENSSL_PUT_ERROR(CRYPTO, ERR_R_MALLOC_FAILURE);
520
0
    return nullptr;
521
0
  }
522
28.7k
  char *ret = reinterpret_cast<char *>(OPENSSL_malloc(alloc_size));
523
28.7k
  if (ret == nullptr) {
524
0
    return nullptr;
525
0
  }
526
527
28.7k
  OPENSSL_memcpy(ret, str, size);
528
28.7k
  ret[size] = '\0';
529
28.7k
  return ret;
530
28.7k
}
531
532
111k
size_t OPENSSL_strlcpy(char *dst, const char *src, size_t dst_size) {
533
111k
  size_t l = 0;
534
535
1.53M
  for (; dst_size > 1 && *src; dst_size--) {
536
1.41M
    *dst++ = *src++;
537
1.41M
    l++;
538
1.41M
  }
539
540
111k
  if (dst_size) {
541
111k
    *dst = 0;
542
111k
  }
543
544
111k
  return l + strlen(src);
545
111k
}
546
547
68.0k
size_t OPENSSL_strlcat(char *dst, const char *src, size_t dst_size) {
548
68.0k
  size_t l = 0;
549
496k
  for (; dst_size > 0 && *dst; dst_size--, dst++) {
550
428k
    l++;
551
428k
  }
552
68.0k
  return l + OPENSSL_strlcpy(dst, src, dst_size);
553
68.0k
}
554
555
2.54M
void *OPENSSL_memdup(const void *data, size_t size) {
556
2.54M
  if (size == 0) {
557
10.3k
    return nullptr;
558
10.3k
  }
559
560
2.53M
  void *ret = OPENSSL_malloc(size);
561
2.53M
  if (ret == nullptr) {
562
0
    return nullptr;
563
0
  }
564
565
2.53M
  OPENSSL_memcpy(ret, data, size);
566
2.53M
  return ret;
567
2.53M
}
568
569
0
void *CRYPTO_malloc(size_t size, const char *file, int line) {
570
0
  return OPENSSL_malloc(size);
571
0
}
572
573
0
void *CRYPTO_realloc(void *ptr, size_t new_size, const char *file, int line) {
574
0
  return OPENSSL_realloc(ptr, new_size);
575
0
}
576
577
0
void CRYPTO_free(void *ptr, const char *file, int line) { OPENSSL_free(ptr); }