]> git.ipfire.org Git - thirdparty/squid.git/blob - src/MemBuf.cc
Merged from trunk
[thirdparty/squid.git] / src / MemBuf.cc
1 /*
2 * DEBUG: section 59 auto-growing Memory Buffer with printf
3 * AUTHOR: Alex Rousskov
4 *
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
7 *
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
16 *
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
21 *
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
30 *
31 */
32
33 /**
34 \todo use memory pools for .buf recycling @?@ @?@
35 */
36
37 /**
38 \verbatim
39 * Rationale:
40 * ----------
41 *
42 * Here is how one would Comm::Write an object without MemBuffer:
43 *
44 * {
45 * -- allocate:
46 * buf = malloc(big_enough);
47 *
48 * -- "pack":
49 * snprintf object(s) piece-by-piece constantly checking for overflows
50 * and maintaining (buf+offset);
51 * ...
52 *
53 * -- write
54 * Comm::Write(buf, free, ...);
55 * }
56 *
57 * The whole "packing" idea is quite messy: We are given a buffer of fixed
58 * size and we have to check all the time that we still fit. Sounds logical.
59 *
60 * However, what happens if we have more data? If we are lucky to stop before
61 * we overrun any buffers, we still may have garbage (e.g. half of ETag) in
62 * the buffer.
63 *
64 * MemBuffer:
65 * ----------
66 *
67 * MemBuffer is a memory-resident buffer with printf()-like interface. It
68 * hides all offest handling and overflow checking. Moreover, it has a
69 * build-in control that no partial data has been written.
70 *
71 * MemBuffer is designed to handle relatively small data. It starts with a
72 * small buffer of configurable size to avoid allocating huge buffers all the
73 * time. MemBuffer doubles the buffer when needed. It assert()s that it will
74 * not grow larger than a configurable limit. MemBuffer has virtually no
75 * overhead (and can even reduce memory consumption) compared to old
76 * "packing" approach.
77 *
78 * MemBuffer eliminates both "packing" mess and truncated data:
79 *
80 * {
81 * -- setup
82 * MemBuf buf;
83 *
84 * -- required init with optional size tuning (see #defines for defaults)
85 * buf.init(initial-size, absolute-maximum);
86 *
87 * -- "pack" (no need to handle offsets or check for overflows)
88 * buf.Printf(...);
89 * ...
90 *
91 * -- write
92 * Comm::Write(fd, buf, callback);
93 *
94 * -- *iff* you did not give the buffer away, free it yourself
95 * -- buf.clean();
96 * }
97 \endverbatim
98 */
99
100 #include "squid.h"
101 #include "Mem.h"
102 #include "MemBuf.h"
103 #include "profiler/Profiler.h"
104
105 #ifdef VA_COPY
106 #undef VA_COPY
107 #endif
108 #if defined HAVE_VA_COPY
109 #define VA_COPY va_copy
110 #elif defined HAVE___VA_COPY
111 #define VA_COPY __va_copy
112 #endif
113
114 /* local constants */
115
116 /* default values for buffer sizes, used by memBufDefInit */
117 #define MEM_BUF_INIT_SIZE (2*1024)
118 #define MEM_BUF_MAX_SIZE (2*1000*1024*1024)
119
120 CBDATA_CLASS_INIT(MemBuf);
121
122 /** init with defaults */
123 void
124 MemBuf::init()
125 {
126 init(MEM_BUF_INIT_SIZE, MEM_BUF_MAX_SIZE);
127 }
128
129 /** init with specific sizes */
130 void
131 MemBuf::init(mb_size_t szInit, mb_size_t szMax)
132 {
133 assert(szInit > 0 && szMax > 0);
134 buf = NULL;
135 size = 0;
136 max_capacity = szMax;
137 capacity = 0;
138 stolen = 0;
139 grow(szInit);
140 }
141
142 /**
143 * cleans the mb; last function to call if you do not give .buf away with
144 * memBufFreeFunc
145 */
146 void
147 MemBuf::clean()
148 {
149 if (isNull()) {
150 // nothing to do
151 } else {
152 assert(buf);
153 assert(!stolen); /* not frozen */
154
155 memFreeBuf(capacity, buf);
156 buf = NULL;
157 size = capacity = max_capacity = 0;
158 }
159 }
160
161 /**
162 * Cleans the buffer without changing its capacity
163 * if called with a Null buffer, calls memBufDefInit()
164 */
165 void
166 MemBuf::reset()
167 {
168 if (isNull()) {
169 init();
170 } else {
171 assert(!stolen); /* not frozen */
172 /* reset */
173 memset(buf, 0, capacity);
174 size = 0;
175 }
176 }
177
178 /**
179 * Unfortunate hack to test if the buffer has been Init()ialized
180 */
181 int
182 MemBuf::isNull()
183 {
184 if (!buf && !max_capacity && !capacity && !size)
185 return 1; /* is null (not initialized) */
186
187 assert(buf && max_capacity && capacity); /* paranoid */
188
189 return 0;
190 }
191
192 mb_size_t MemBuf::spaceSize() const
193 {
194 const mb_size_t terminatedSize = size + 1;
195 return (terminatedSize < capacity) ? capacity - terminatedSize : 0;
196 }
197
198 mb_size_t MemBuf::potentialSpaceSize() const
199 {
200 const mb_size_t terminatedSize = size + 1;
201 return (terminatedSize < max_capacity) ? max_capacity - terminatedSize : 0;
202 }
203
204 /// removes sz bytes and "packs" by moving content left
205 void MemBuf::consume(mb_size_t shiftSize)
206 {
207 const mb_size_t cSize = contentSize();
208 assert(0 <= shiftSize && shiftSize <= cSize);
209 assert(!stolen); /* not frozen */
210
211 PROF_start(MemBuf_consume);
212 if (shiftSize > 0) {
213 if (shiftSize < cSize)
214 memmove(buf, buf + shiftSize, cSize - shiftSize);
215
216 size -= shiftSize;
217
218 terminate();
219 }
220 PROF_stop(MemBuf_consume);
221 }
222
223 // removes last tailSize bytes
224 void MemBuf::truncate(mb_size_t tailSize)
225 {
226 const mb_size_t cSize = contentSize();
227 assert(0 <= tailSize && tailSize <= cSize);
228 assert(!stolen); /* not frozen */
229 size -= tailSize;
230 }
231
232 /**
233 * calls memcpy, appends exactly size bytes,
234 * extends buffer or creates buffer if needed.
235 */
236 void MemBuf::append(const char *newContent, mb_size_t sz)
237 {
238 assert(sz >= 0);
239 assert(buf || (0==capacity && 0==size));
240 assert(!stolen); /* not frozen */
241
242 PROF_start(MemBuf_append);
243 if (sz > 0) {
244 if (size + sz + 1 > capacity)
245 grow(size + sz + 1);
246
247 assert(size + sz <= capacity); /* paranoid */
248 memcpy(space(), newContent, sz);
249 appended(sz);
250 }
251 PROF_stop(MemBuf_append);
252 }
253
254 /// updates content size after external append
255 void MemBuf::appended(mb_size_t sz)
256 {
257 assert(size + sz <= capacity);
258 size += sz;
259 terminate();
260 }
261
262 /**
263 * Null-terminate in case we are used as a string.
264 * Extra octet is not counted in the content size (or space size)
265 *
266 \note XXX: but the extra octet is counted when growth decisions are made!
267 * This will cause the buffer to grow when spaceSize() == 1 on append,
268 * which will assert() if the buffer cannot grow any more.
269 */
270 void MemBuf::terminate()
271 {
272 assert(size < capacity);
273 *space() = '\0';
274 }
275
276 /* calls memBufVPrintf */
277 void
278 MemBuf::Printf(const char *fmt,...)
279 {
280 va_list args;
281 va_start(args, fmt);
282 vPrintf(fmt, args);
283 va_end(args);
284 }
285
286 /**
287 * vPrintf for other printf()'s to use; calls vsnprintf, extends buf if needed
288 */
289 void
290 MemBuf::vPrintf(const char *fmt, va_list vargs)
291 {
292 #ifdef VA_COPY
293 va_list ap;
294 #endif
295
296 int sz = 0;
297 assert(fmt);
298 assert(buf);
299 assert(!stolen); /* not frozen */
300 /* assert in Grow should quit first, but we do not want to have a scary infinite loop */
301
302 while (capacity <= max_capacity) {
303 mb_size_t free_space = capacity - size;
304 /* put as much as we can */
305
306 #ifdef VA_COPY
307 /* Fix of bug 753r. The value of vargs is undefined
308 * after vsnprintf() returns. Make a copy of vargs
309 * incase we loop around and call vsnprintf() again.
310 */
311 VA_COPY(ap,vargs);
312 sz = vsnprintf(buf + size, free_space, fmt, ap);
313 va_end(ap);
314 #else /* VA_COPY */
315
316 sz = vsnprintf(buf + size, free_space, fmt, vargs);
317 #endif /*VA_COPY*/
318 /* check for possible overflow */
319 /* snprintf on Linuz returns -1 on overflows */
320 /* snprintf on FreeBSD returns at least free_space on overflows */
321
322 if (sz < 0 || sz >= free_space)
323 grow(capacity + 1);
324 else
325 break;
326 }
327
328 size += sz;
329 /* on Linux and FreeBSD, '\0' is not counted in return value */
330 /* on XXX it might be counted */
331 /* check that '\0' is appended and not counted */
332
333 if (!size || buf[size - 1]) {
334 assert(!buf[size]);
335 } else {
336 --size;
337 }
338 }
339
340 /**
341 * Important:
342 * calling this function "freezes" mb,
343 * do not _update_ mb after that in any way
344 * (you still can read-access .buf and .size)
345 *
346 \retval free() function to be used.
347 */
348 FREE *
349 MemBuf::freeFunc()
350 {
351 FREE *ff;
352 assert(buf);
353 assert(!stolen); /* not frozen */
354
355 ff = memFreeBufFunc((size_t) capacity);
356 stolen = 1; /* freeze */
357 return ff;
358 }
359
360 /**
361 * Grows (doubles) internal buffer to satisfy required minimal capacity
362 */
363 void
364 MemBuf::grow(mb_size_t min_cap)
365 {
366 size_t new_cap;
367 size_t buf_cap;
368
369 assert(!stolen);
370 assert(capacity < min_cap);
371
372 PROF_start(MemBuf_grow);
373
374 /* determine next capacity */
375
376 if (min_cap > 64 * 1024) {
377 new_cap = 64 * 1024;
378
379 while (new_cap < (size_t) min_cap)
380 new_cap += 64 * 1024; /* increase in reasonable steps */
381 } else {
382 new_cap = (size_t) min_cap;
383 }
384
385 /* last chance to fit before we assert(!overflow) */
386 if (new_cap > (size_t) max_capacity)
387 new_cap = (size_t) max_capacity;
388
389 assert(new_cap <= (size_t) max_capacity); /* no overflow */
390
391 assert(new_cap > (size_t) capacity); /* progress */
392
393 buf_cap = (size_t) capacity;
394
395 buf = (char *)memReallocBuf(buf, new_cap, &buf_cap);
396
397 /* done */
398 capacity = (mb_size_t) buf_cap;
399 PROF_stop(MemBuf_grow);
400 }
401
402 /* Reports */
403
404 /**
405 * Puts report on MemBuf _module_ usage into mb
406 */
407 void
408 memBufReport(MemBuf * mb)
409 {
410 assert(mb);
411 mb->Printf("memBufReport is not yet implemented @?@\n");
412 }
413
414 #if !_USE_INLINE_
415 #include "MemBuf.cci"
416 #endif