8 /* ----------------------------------------------------------------------
9 * String handling routines.
12 char *dupstr(const char *s)
15 char *p = smalloc(len + 1);
20 /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
21 char *dupcat(const char *s1, ...)
30 sn = va_arg(ap, char *);
43 sn = va_arg(ap, char *);
55 * Do an sprintf(), but into a custom-allocated buffer.
57 * Irritatingly, we don't seem to be able to do this portably using
58 * vsnprintf(), because there appear to be issues with re-using the
59 * same va_list for two calls, and the excellent C99 va_copy is not
60 * yet widespread. Bah. Instead I'm going to do a horrid, horrid
61 * hack, in which I trawl the format string myself, work out the
62 * maximum length of each format component, and resize the buffer
65 char *dupprintf(const char *fmt, ...)
70 ret = dupvprintf(fmt, ap);
74 char *dupvprintf(const char *fmt, va_list ap)
84 #define vsnprintf _vsnprintf
86 len = vsnprintf(buf, size, fmt, ap);
87 if (len >= 0 && len < size) {
88 /* This is the C99-specified criterion for snprintf to have
89 * been completely successful. */
92 /* This is the C99 error condition: the returned length is
93 * the required buffer size not counting the NUL. */
96 /* This is the pre-C99 glibc error condition: <0 means the
97 * buffer wasn't big enough, so we enlarge it a bit and hope. */
100 buf = srealloc(buf, size);
104 /* ----------------------------------------------------------------------
105 * Base64 encoding routine. This is required in public-key writing
106 * but also in HTTP proxy handling, so it's centralised here.
109 void base64_encode_atom(unsigned char *data, int n, char *out)
111 static const char base64_chars[] =
112 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
116 word = data[0] << 16;
118 word |= data[1] << 8;
121 out[0] = base64_chars[(word >> 18) & 0x3F];
122 out[1] = base64_chars[(word >> 12) & 0x3F];
124 out[2] = base64_chars[(word >> 6) & 0x3F];
128 out[3] = base64_chars[word & 0x3F];
133 /* ----------------------------------------------------------------------
134 * Generic routines to deal with send buffers: a linked list of
135 * smallish blocks, with the operations
137 * - add an arbitrary amount of data to the end of the list
138 * - remove the first N bytes from the list
139 * - return a (pointer,length) pair giving some initial data in
140 * the list, suitable for passing to a send or write system
142 * - retrieve a larger amount of initial data from the list
143 * - return the current size of the buffer chain in bytes
146 #define BUFFER_GRANULE 512
148 struct bufchain_granule {
149 struct bufchain_granule *next;
151 char buf[BUFFER_GRANULE];
154 void bufchain_init(bufchain *ch)
156 ch->head = ch->tail = NULL;
160 void bufchain_clear(bufchain *ch)
162 struct bufchain_granule *b;
165 ch->head = ch->head->next;
172 int bufchain_size(bufchain *ch)
174 return ch->buffersize;
177 void bufchain_add(bufchain *ch, void *data, int len)
179 char *buf = (char *)data;
181 ch->buffersize += len;
183 if (ch->tail && ch->tail->buflen < BUFFER_GRANULE) {
184 int copylen = min(len, BUFFER_GRANULE - ch->tail->buflen);
185 memcpy(ch->tail->buf + ch->tail->buflen, buf, copylen);
188 ch->tail->buflen += copylen;
191 int grainlen = min(len, BUFFER_GRANULE);
192 struct bufchain_granule *newbuf;
193 newbuf = smalloc(sizeof(struct bufchain_granule));
195 newbuf->buflen = grainlen;
196 memcpy(newbuf->buf, buf, grainlen);
200 ch->tail->next = newbuf;
202 ch->head = ch->tail = newbuf;
208 void bufchain_consume(bufchain *ch, int len)
210 struct bufchain_granule *tmp;
212 assert(ch->buffersize >= len);
215 assert(ch->head != NULL);
216 if (remlen >= ch->head->buflen - ch->head->bufpos) {
217 remlen = ch->head->buflen - ch->head->bufpos;
219 ch->head = tmp->next;
224 ch->head->bufpos += remlen;
225 ch->buffersize -= remlen;
230 void bufchain_prefix(bufchain *ch, void **data, int *len)
232 *len = ch->head->buflen - ch->head->bufpos;
233 *data = ch->head->buf + ch->head->bufpos;
236 void bufchain_fetch(bufchain *ch, void *data, int len)
238 struct bufchain_granule *tmp;
239 char *data_c = (char *)data;
243 assert(ch->buffersize >= len);
248 if (remlen >= tmp->buflen - tmp->bufpos)
249 remlen = tmp->buflen - tmp->bufpos;
250 memcpy(data_c, tmp->buf + tmp->bufpos, remlen);
258 /* ----------------------------------------------------------------------
259 * My own versions of malloc, realloc and free. Because I want
260 * malloc and realloc to bomb out and exit the program if they run
261 * out of memory, realloc to reliably call malloc if passed a NULL
262 * pointer, and free to reliably do nothing if passed a NULL
263 * pointer. We can also put trace printouts in, if we need to; and
264 * we can also replace the allocator with an ElectricFence-like
270 * Minefield - a Windows equivalent for Electric Fence
273 #define PAGESIZE 4096
278 * We start by reserving as much virtual address space as Windows
279 * will sensibly (or not sensibly) let us have. We flag it all as
282 * Any allocation attempt is satisfied by committing one or more
283 * pages, with an uncommitted page on either side. The returned
284 * memory region is jammed up against the _end_ of the pages.
286 * Freeing anything causes instantaneous decommitment of the pages
287 * involved, so stale pointers are caught as soon as possible.
290 static int minefield_initialised = 0;
291 static void *minefield_region = NULL;
292 static long minefield_size = 0;
293 static long minefield_npages = 0;
294 static long minefield_curpos = 0;
295 static unsigned short *minefield_admin = NULL;
296 static void *minefield_pages = NULL;
298 static void minefield_admin_hide(int hide)
300 int access = hide ? PAGE_NOACCESS : PAGE_READWRITE;
301 VirtualProtect(minefield_admin, minefield_npages * 2, access, NULL);
304 static void minefield_init(void)
310 for (size = 0x40000000; size > 0; size = ((size >> 3) * 7) & ~0xFFF) {
311 minefield_region = VirtualAlloc(NULL, size,
312 MEM_RESERVE, PAGE_NOACCESS);
313 if (minefield_region)
316 minefield_size = size;
319 * Firstly, allocate a section of that to be the admin block.
320 * We'll need a two-byte field for each page.
322 minefield_admin = minefield_region;
323 minefield_npages = minefield_size / PAGESIZE;
324 admin_size = (minefield_npages * 2 + PAGESIZE - 1) & ~(PAGESIZE - 1);
325 minefield_npages = (minefield_size - admin_size) / PAGESIZE;
326 minefield_pages = (char *) minefield_region + admin_size;
329 * Commit the admin region.
331 VirtualAlloc(minefield_admin, minefield_npages * 2,
332 MEM_COMMIT, PAGE_READWRITE);
335 * Mark all pages as unused (0xFFFF).
337 for (i = 0; i < minefield_npages; i++)
338 minefield_admin[i] = 0xFFFF;
341 * Hide the admin region.
343 minefield_admin_hide(1);
345 minefield_initialised = 1;
348 static void minefield_bomb(void)
350 div(1, *(int *) minefield_pages);
353 static void *minefield_alloc(int size)
356 int pos, lim, region_end, region_start;
360 npages = (size + PAGESIZE - 1) / PAGESIZE;
362 minefield_admin_hide(0);
365 * Search from current position until we find a contiguous
366 * bunch of npages+2 unused pages.
368 pos = minefield_curpos;
369 lim = minefield_npages;
371 /* Skip over used pages. */
372 while (pos < lim && minefield_admin[pos] != 0xFFFF)
374 /* Count unused pages. */
376 while (pos < lim && pos - start < npages + 2 &&
377 minefield_admin[pos] == 0xFFFF)
379 if (pos - start == npages + 2)
381 /* If we've reached the limit, reset the limit or stop. */
383 if (lim == minefield_npages) {
384 /* go round and start again at zero */
385 lim = minefield_curpos;
388 minefield_admin_hide(1);
394 minefield_curpos = pos - 1;
397 * We have npages+2 unused pages starting at start. We leave
398 * the first and last of these alone and use the rest.
400 region_end = (start + npages + 1) * PAGESIZE;
401 region_start = region_end - size;
402 /* FIXME: could align here if we wanted */
405 * Update the admin region.
407 for (i = start + 2; i < start + npages + 1; i++)
408 minefield_admin[i] = 0xFFFE; /* used but no region starts here */
409 minefield_admin[start + 1] = region_start % PAGESIZE;
411 minefield_admin_hide(1);
413 VirtualAlloc((char *) minefield_pages + region_start, size,
414 MEM_COMMIT, PAGE_READWRITE);
415 return (char *) minefield_pages + region_start;
418 static void minefield_free(void *ptr)
420 int region_start, i, j;
422 minefield_admin_hide(0);
424 region_start = (char *) ptr - (char *) minefield_pages;
425 i = region_start / PAGESIZE;
426 if (i < 0 || i >= minefield_npages ||
427 minefield_admin[i] != region_start % PAGESIZE)
429 for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++) {
430 minefield_admin[j] = 0xFFFF;
433 VirtualFree(ptr, j * PAGESIZE - region_start, MEM_DECOMMIT);
435 minefield_admin_hide(1);
438 static int minefield_get_size(void *ptr)
440 int region_start, i, j;
442 minefield_admin_hide(0);
444 region_start = (char *) ptr - (char *) minefield_pages;
445 i = region_start / PAGESIZE;
446 if (i < 0 || i >= minefield_npages ||
447 minefield_admin[i] != region_start % PAGESIZE)
449 for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++);
451 minefield_admin_hide(1);
453 return j * PAGESIZE - region_start;
456 static void *minefield_c_malloc(size_t size)
458 if (!minefield_initialised)
460 return minefield_alloc(size);
463 static void minefield_c_free(void *p)
465 if (!minefield_initialised)
471 * realloc _always_ moves the chunk, for rapid detection of code
472 * that assumes it won't.
474 static void *minefield_c_realloc(void *p, size_t size)
478 if (!minefield_initialised)
480 q = minefield_alloc(size);
481 oldsize = minefield_get_size(p);
482 memcpy(q, p, (oldsize < size ? oldsize : size));
487 #endif /* MINEFIELD */
490 static FILE *fp = NULL;
492 static char *mlog_file = NULL;
493 static int mlog_line = 0;
495 void mlog(char *file, int line)
500 fp = fopen("putty_mem.log", "w");
501 setvbuf(fp, NULL, _IONBF, BUFSIZ);
504 fprintf(fp, "%s:%d: ", file, line);
508 void *safemalloc(size_t size)
512 p = minefield_c_malloc(size);
519 sprintf(str, "Out of memory! (%s:%d, size=%d)",
520 mlog_file, mlog_line, size);
521 fprintf(fp, "*** %s\n", str);
524 strcpy(str, "Out of memory!");
530 fprintf(fp, "malloc(%d) returns %p\n", size, p);
535 void *saferealloc(void *ptr, size_t size)
540 p = minefield_c_malloc(size);
546 p = minefield_c_realloc(ptr, size);
548 p = realloc(ptr, size);
554 sprintf(str, "Out of memory! (%s:%d, size=%d)",
555 mlog_file, mlog_line, size);
556 fprintf(fp, "*** %s\n", str);
559 strcpy(str, "Out of memory!");
565 fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
570 void safefree(void *ptr)
575 fprintf(fp, "free(%p)\n", ptr);
578 minefield_c_free(ptr);
585 fprintf(fp, "freeing null pointer - no action taken\n");
589 /* ----------------------------------------------------------------------
590 * Debugging routines.
594 static FILE *debug_fp = NULL;
595 static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
596 static int debug_got_console = 0;
598 static void dputs(char *buf)
602 if (!debug_got_console) {
603 if (AllocConsole()) {
604 debug_got_console = 1;
605 debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
609 debug_fp = fopen("debug.log", "w");
612 if (debug_hdl != INVALID_HANDLE_VALUE) {
613 WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
615 fputs(buf, debug_fp);
620 void dprintf(char *fmt, ...)
626 buf = dupvprintf(fmt, ap);
633 void debug_memdump(void *buf, int len, int L)
636 unsigned char *p = buf;
640 dprintf("\t%d (0x%x) bytes:\n", len, len);
641 delta = 15 & (int) p;
645 for (; 0 < len; p += 16, len -= 16) {
649 strcpy(foo, "................"); /* sixteen dots */
650 for (i = 0; i < 16 && i < len; ++i) {
651 if (&p[i] < (unsigned char *) buf) {
652 dputs(" "); /* 3 spaces */
656 &p[i] != (unsigned char *) buf
657 && i % 4 ? '.' : ' ', p[i]
659 if (p[i] >= ' ' && p[i] <= '~')
660 foo[i] = (char) p[i];
664 dprintf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
668 #endif /* def DEBUG */