/src/boringssl/crypto/bio/printf.cc
Line | Count | Source (jump to first uncovered line) |
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/bio.h> |
16 | | |
17 | | #include <assert.h> |
18 | | #include <stdarg.h> |
19 | | #include <stdio.h> |
20 | | |
21 | | #include <openssl/err.h> |
22 | | #include <openssl/mem.h> |
23 | | |
24 | 421k | int BIO_printf(BIO *bio, const char *format, ...) { |
25 | 421k | va_list args; |
26 | 421k | char buf[256], *out, out_malloced = 0; |
27 | 421k | int out_len, ret; |
28 | | |
29 | 421k | va_start(args, format); |
30 | 421k | out_len = vsnprintf(buf, sizeof(buf), format, args); |
31 | 421k | va_end(args); |
32 | 421k | if (out_len < 0) { |
33 | 0 | return -1; |
34 | 0 | } |
35 | | |
36 | 421k | if ((size_t)out_len >= sizeof(buf)) { |
37 | 79 | const size_t requested_len = (size_t)out_len; |
38 | | // The output was truncated. Note that vsnprintf's return value does not |
39 | | // include a trailing NUL, but the buffer must be sized for it. |
40 | 79 | out = reinterpret_cast<char *>(OPENSSL_malloc(requested_len + 1)); |
41 | 79 | out_malloced = 1; |
42 | 79 | if (out == NULL) { |
43 | 0 | return -1; |
44 | 0 | } |
45 | 79 | va_start(args, format); |
46 | 79 | out_len = vsnprintf(out, requested_len + 1, format, args); |
47 | 79 | va_end(args); |
48 | 79 | assert(out_len == (int)requested_len); |
49 | 421k | } else { |
50 | 421k | out = buf; |
51 | 421k | } |
52 | | |
53 | 421k | ret = BIO_write(bio, out, out_len); |
54 | 421k | if (out_malloced) { |
55 | 79 | OPENSSL_free(out); |
56 | 79 | } |
57 | | |
58 | 421k | return ret; |
59 | 421k | } |