2 * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
11 #include "internal/cryptlib.h"
12 #include <openssl/buffer.h>
15 * LIMIT_BEFORE_EXPANSION is the maximum n such that (n+3)/3*4 < 2**31. That
16 * function is applied in several functions in this file and this limit
17 * ensures that the result fits in an int.
19 #define LIMIT_BEFORE_EXPANSION 0x5ffffffc
21 BUF_MEM *BUF_MEM_new_ex(unsigned long flags)
31 BUF_MEM *BUF_MEM_new(void)
35 ret = OPENSSL_zalloc(sizeof(*ret));
37 BUFerr(BUF_F_BUF_MEM_NEW, ERR_R_MALLOC_FAILURE);
43 void BUF_MEM_free(BUF_MEM *a)
47 if (a->data != NULL) {
48 if (a->flags & BUF_MEM_FLAG_SECURE)
49 OPENSSL_secure_clear_free(a->data, a->max);
51 OPENSSL_clear_free(a->data, a->max);
56 /* Allocate a block of secure memory; copy over old data if there
57 * was any, and then free it. */
58 static char *sec_alloc_realloc(BUF_MEM *str, size_t len)
62 ret = OPENSSL_secure_malloc(len);
63 if (str->data != NULL) {
65 memcpy(ret, str->data, str->length);
66 OPENSSL_secure_clear_free(str->data, str->length);
73 size_t BUF_MEM_grow(BUF_MEM *str, size_t len)
78 if (str->length >= len) {
82 if (str->max >= len) {
83 if (str->data != NULL)
84 memset(&str->data[str->length], 0, len - str->length);
88 /* This limit is sufficient to ensure (len+3)/3*4 < 2**31 */
89 if (len > LIMIT_BEFORE_EXPANSION) {
90 BUFerr(BUF_F_BUF_MEM_GROW, ERR_R_MALLOC_FAILURE);
93 n = (len + 3) / 3 * 4;
94 if ((str->flags & BUF_MEM_FLAG_SECURE))
95 ret = sec_alloc_realloc(str, n);
97 ret = OPENSSL_realloc(str->data, n);
99 BUFerr(BUF_F_BUF_MEM_GROW, ERR_R_MALLOC_FAILURE);
104 memset(&str->data[str->length], 0, len - str->length);
110 size_t BUF_MEM_grow_clean(BUF_MEM *str, size_t len)
115 if (str->length >= len) {
116 if (str->data != NULL)
117 memset(&str->data[len], 0, str->length - len);
121 if (str->max >= len) {
122 memset(&str->data[str->length], 0, len - str->length);
126 /* This limit is sufficient to ensure (len+3)/3*4 < 2**31 */
127 if (len > LIMIT_BEFORE_EXPANSION) {
128 BUFerr(BUF_F_BUF_MEM_GROW_CLEAN, ERR_R_MALLOC_FAILURE);
131 n = (len + 3) / 3 * 4;
132 if ((str->flags & BUF_MEM_FLAG_SECURE))
133 ret = sec_alloc_realloc(str, n);
135 ret = OPENSSL_clear_realloc(str->data, str->max, n);
137 BUFerr(BUF_F_BUF_MEM_GROW_CLEAN, ERR_R_MALLOC_FAILURE);
142 memset(&str->data[str->length], 0, len - str->length);
148 void BUF_reverse(unsigned char *out, const unsigned char *in, size_t size)
153 for (i = 0; i < size; i++)
159 for (i = 0; i < size / 2; i++) {