1 /*
2 * nghttp2 - HTTP/2 C Library
3 *
4 * Copyright (c) 2012 Tatsuhiro Tsujikawa
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining
7 * a copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sublicense, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 */
25 #include "malloc_wrapper.h"
26
27 int nghttp2_failmalloc = 0;
28 int nghttp2_failstart = 0;
29 int nghttp2_countmalloc = 1;
30 int nghttp2_nmalloc = 0;
31
32 #define CHECK_PREREQ \
33 do { \
34 if (nghttp2_failmalloc && nghttp2_nmalloc >= nghttp2_failstart) { \
35 return NULL; \
36 } \
37 if (nghttp2_countmalloc) { \
38 ++nghttp2_nmalloc; \
39 } \
40 } while (0)
41
my_malloc(size_t size,void * mud)42 static void *my_malloc(size_t size, void *mud) {
43 (void)mud;
44
45 CHECK_PREREQ;
46 return malloc(size);
47 }
48
my_free(void * ptr,void * mud)49 static void my_free(void *ptr, void *mud) {
50 (void)mud;
51
52 free(ptr);
53 }
54
my_calloc(size_t nmemb,size_t size,void * mud)55 static void *my_calloc(size_t nmemb, size_t size, void *mud) {
56 (void)mud;
57
58 CHECK_PREREQ;
59 return calloc(nmemb, size);
60 }
61
my_realloc(void * ptr,size_t size,void * mud)62 static void *my_realloc(void *ptr, size_t size, void *mud) {
63 (void)mud;
64
65 CHECK_PREREQ;
66 return realloc(ptr, size);
67 }
68
69 static nghttp2_mem mem = {NULL, my_malloc, my_free, my_calloc, my_realloc};
70
nghttp2_mem_fm(void)71 nghttp2_mem *nghttp2_mem_fm(void) { return &mem; }
72
73 static int failmalloc_bk, countmalloc_bk;
74
nghttp2_failmalloc_pause(void)75 void nghttp2_failmalloc_pause(void) {
76 failmalloc_bk = nghttp2_failmalloc;
77 countmalloc_bk = nghttp2_countmalloc;
78 nghttp2_failmalloc = 0;
79 nghttp2_countmalloc = 0;
80 }
81
nghttp2_failmalloc_unpause(void)82 void nghttp2_failmalloc_unpause(void) {
83 nghttp2_failmalloc = failmalloc_bk;
84 nghttp2_countmalloc = countmalloc_bk;
85 }
86