7 /* ----------------------------------------------------------------------
8 * String handling routines.
14 char *p = smalloc(len + 1);
19 /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
20 char *dupcat(char *s1, ...)
29 sn = va_arg(ap, char *);
42 sn = va_arg(ap, char *);
53 /* ----------------------------------------------------------------------
54 * Base64 encoding routine. This is required in public-key writing
55 * but also in HTTP proxy handling, so it's centralised here.
58 void base64_encode_atom(unsigned char *data, int n, char *out)
60 static const char base64_chars[] =
61 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
70 out[0] = base64_chars[(word >> 18) & 0x3F];
71 out[1] = base64_chars[(word >> 12) & 0x3F];
73 out[2] = base64_chars[(word >> 6) & 0x3F];
77 out[3] = base64_chars[word & 0x3F];
82 /* ----------------------------------------------------------------------
83 * Generic routines to deal with send buffers: a linked list of
84 * smallish blocks, with the operations
86 * - add an arbitrary amount of data to the end of the list
87 * - remove the first N bytes from the list
88 * - return a (pointer,length) pair giving some initial data in
89 * the list, suitable for passing to a send or write system
91 * - return the current size of the buffer chain in bytes
94 #define BUFFER_GRANULE 512
96 struct bufchain_granule {
97 struct bufchain_granule *next;
99 char buf[BUFFER_GRANULE];
102 void bufchain_init(bufchain *ch)
104 ch->head = ch->tail = NULL;
108 void bufchain_clear(bufchain *ch)
110 struct bufchain_granule *b;
113 ch->head = ch->head->next;
120 int bufchain_size(bufchain *ch)
122 return ch->buffersize;
125 void bufchain_add(bufchain *ch, void *data, int len)
127 char *buf = (char *)data;
129 ch->buffersize += len;
131 if (ch->tail && ch->tail->buflen < BUFFER_GRANULE) {
132 int copylen = min(len, BUFFER_GRANULE - ch->tail->buflen);
133 memcpy(ch->tail->buf + ch->tail->buflen, buf, copylen);
136 ch->tail->buflen += copylen;
139 int grainlen = min(len, BUFFER_GRANULE);
140 struct bufchain_granule *newbuf;
141 newbuf = smalloc(sizeof(struct bufchain_granule));
143 newbuf->buflen = grainlen;
144 memcpy(newbuf->buf, buf, grainlen);
148 ch->tail->next = newbuf;
150 ch->head = ch->tail = newbuf;
156 void bufchain_consume(bufchain *ch, int len)
158 assert(ch->buffersize >= len);
159 assert(ch->head != NULL && ch->head->bufpos + len <= ch->head->buflen);
160 ch->head->bufpos += len;
161 ch->buffersize -= len;
162 if (ch->head->bufpos >= ch->head->buflen) {
163 struct bufchain_granule *tmp = ch->head;
164 ch->head = tmp->next;
171 void bufchain_prefix(bufchain *ch, void **data, int *len)
173 *len = ch->head->buflen - ch->head->bufpos;
174 *data = ch->head->buf + ch->head->bufpos;
177 /* ----------------------------------------------------------------------
178 * My own versions of malloc, realloc and free. Because I want
179 * malloc and realloc to bomb out and exit the program if they run
180 * out of memory, realloc to reliably call malloc if passed a NULL
181 * pointer, and free to reliably do nothing if passed a NULL
182 * pointer. We can also put trace printouts in, if we need to; and
183 * we can also replace the allocator with an ElectricFence-like
189 * Minefield - a Windows equivalent for Electric Fence
192 #define PAGESIZE 4096
197 * We start by reserving as much virtual address space as Windows
198 * will sensibly (or not sensibly) let us have. We flag it all as
201 * Any allocation attempt is satisfied by committing one or more
202 * pages, with an uncommitted page on either side. The returned
203 * memory region is jammed up against the _end_ of the pages.
205 * Freeing anything causes instantaneous decommitment of the pages
206 * involved, so stale pointers are caught as soon as possible.
209 static int minefield_initialised = 0;
210 static void *minefield_region = NULL;
211 static long minefield_size = 0;
212 static long minefield_npages = 0;
213 static long minefield_curpos = 0;
214 static unsigned short *minefield_admin = NULL;
215 static void *minefield_pages = NULL;
217 static void minefield_admin_hide(int hide)
219 int access = hide ? PAGE_NOACCESS : PAGE_READWRITE;
220 VirtualProtect(minefield_admin, minefield_npages * 2, access, NULL);
223 static void minefield_init(void)
229 for (size = 0x40000000; size > 0; size = ((size >> 3) * 7) & ~0xFFF) {
230 minefield_region = VirtualAlloc(NULL, size,
231 MEM_RESERVE, PAGE_NOACCESS);
232 if (minefield_region)
235 minefield_size = size;
238 * Firstly, allocate a section of that to be the admin block.
239 * We'll need a two-byte field for each page.
241 minefield_admin = minefield_region;
242 minefield_npages = minefield_size / PAGESIZE;
243 admin_size = (minefield_npages * 2 + PAGESIZE - 1) & ~(PAGESIZE - 1);
244 minefield_npages = (minefield_size - admin_size) / PAGESIZE;
245 minefield_pages = (char *) minefield_region + admin_size;
248 * Commit the admin region.
250 VirtualAlloc(minefield_admin, minefield_npages * 2,
251 MEM_COMMIT, PAGE_READWRITE);
254 * Mark all pages as unused (0xFFFF).
256 for (i = 0; i < minefield_npages; i++)
257 minefield_admin[i] = 0xFFFF;
260 * Hide the admin region.
262 minefield_admin_hide(1);
264 minefield_initialised = 1;
267 static void minefield_bomb(void)
269 div(1, *(int *) minefield_pages);
272 static void *minefield_alloc(int size)
275 int pos, lim, region_end, region_start;
279 npages = (size + PAGESIZE - 1) / PAGESIZE;
281 minefield_admin_hide(0);
284 * Search from current position until we find a contiguous
285 * bunch of npages+2 unused pages.
287 pos = minefield_curpos;
288 lim = minefield_npages;
290 /* Skip over used pages. */
291 while (pos < lim && minefield_admin[pos] != 0xFFFF)
293 /* Count unused pages. */
295 while (pos < lim && pos - start < npages + 2 &&
296 minefield_admin[pos] == 0xFFFF)
298 if (pos - start == npages + 2)
300 /* If we've reached the limit, reset the limit or stop. */
302 if (lim == minefield_npages) {
303 /* go round and start again at zero */
304 lim = minefield_curpos;
307 minefield_admin_hide(1);
313 minefield_curpos = pos - 1;
316 * We have npages+2 unused pages starting at start. We leave
317 * the first and last of these alone and use the rest.
319 region_end = (start + npages + 1) * PAGESIZE;
320 region_start = region_end - size;
321 /* FIXME: could align here if we wanted */
324 * Update the admin region.
326 for (i = start + 2; i < start + npages + 1; i++)
327 minefield_admin[i] = 0xFFFE; /* used but no region starts here */
328 minefield_admin[start + 1] = region_start % PAGESIZE;
330 minefield_admin_hide(1);
332 VirtualAlloc((char *) minefield_pages + region_start, size,
333 MEM_COMMIT, PAGE_READWRITE);
334 return (char *) minefield_pages + region_start;
337 static void minefield_free(void *ptr)
339 int region_start, i, j;
341 minefield_admin_hide(0);
343 region_start = (char *) ptr - (char *) minefield_pages;
344 i = region_start / PAGESIZE;
345 if (i < 0 || i >= minefield_npages ||
346 minefield_admin[i] != region_start % PAGESIZE)
348 for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++) {
349 minefield_admin[j] = 0xFFFF;
352 VirtualFree(ptr, j * PAGESIZE - region_start, MEM_DECOMMIT);
354 minefield_admin_hide(1);
357 static int minefield_get_size(void *ptr)
359 int region_start, i, j;
361 minefield_admin_hide(0);
363 region_start = (char *) ptr - (char *) minefield_pages;
364 i = region_start / PAGESIZE;
365 if (i < 0 || i >= minefield_npages ||
366 minefield_admin[i] != region_start % PAGESIZE)
368 for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++);
370 minefield_admin_hide(1);
372 return j * PAGESIZE - region_start;
375 static void *minefield_c_malloc(size_t size)
377 if (!minefield_initialised)
379 return minefield_alloc(size);
382 static void minefield_c_free(void *p)
384 if (!minefield_initialised)
390 * realloc _always_ moves the chunk, for rapid detection of code
391 * that assumes it won't.
393 static void *minefield_c_realloc(void *p, size_t size)
397 if (!minefield_initialised)
399 q = minefield_alloc(size);
400 oldsize = minefield_get_size(p);
401 memcpy(q, p, (oldsize < size ? oldsize : size));
406 #endif /* MINEFIELD */
409 static FILE *fp = NULL;
411 static char *mlog_file = NULL;
412 static int mlog_line = 0;
414 void mlog(char *file, int line)
419 fp = fopen("putty_mem.log", "w");
420 setvbuf(fp, NULL, _IONBF, BUFSIZ);
423 fprintf(fp, "%s:%d: ", file, line);
427 void *safemalloc(size_t size)
431 p = minefield_c_malloc(size);
438 sprintf(str, "Out of memory! (%s:%d, size=%d)",
439 mlog_file, mlog_line, size);
440 fprintf(fp, "*** %s\n", str);
443 strcpy(str, "Out of memory!");
445 MessageBox(NULL, str, "PuTTY Fatal Error",
446 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
451 fprintf(fp, "malloc(%d) returns %p\n", size, p);
456 void *saferealloc(void *ptr, size_t size)
461 p = minefield_c_malloc(size);
467 p = minefield_c_realloc(ptr, size);
469 p = realloc(ptr, size);
475 sprintf(str, "Out of memory! (%s:%d, size=%d)",
476 mlog_file, mlog_line, size);
477 fprintf(fp, "*** %s\n", str);
480 strcpy(str, "Out of memory!");
482 MessageBox(NULL, str, "PuTTY Fatal Error",
483 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
488 fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
493 void safefree(void *ptr)
498 fprintf(fp, "free(%p)\n", ptr);
501 minefield_c_free(ptr);
508 fprintf(fp, "freeing null pointer - no action taken\n");
512 /* ----------------------------------------------------------------------
513 * Debugging routines.
517 static FILE *debug_fp = NULL;
518 static int debug_got_console = 0;
520 static void dputs(char *buf)
524 if (!debug_got_console) {
526 debug_got_console = 1;
529 debug_fp = fopen("debug.log", "w");
532 WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, strlen(buf), &dw,
534 fputs(buf, debug_fp);
539 void dprintf(char *fmt, ...)
545 vsprintf(buf, fmt, ap);
551 void debug_memdump(void *buf, int len, int L)
554 unsigned char *p = buf;
558 dprintf("\t%d (0x%x) bytes:\n", len, len);
559 delta = 15 & (int) p;
563 for (; 0 < len; p += 16, len -= 16) {
567 strcpy(foo, "................"); /* sixteen dots */
568 for (i = 0; i < 16 && i < len; ++i) {
569 if (&p[i] < (unsigned char *) buf) {
570 dputs(" "); /* 3 spaces */
574 &p[i] != (unsigned char *) buf
575 && i % 4 ? '.' : ' ', p[i]
577 if (p[i] >= ' ' && p[i] <= '~')
578 foo[i] = (char) p[i];
582 dprintf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
586 #endif /* def DEBUG */