Oops. Dirsep in Makefile.cyg should be / not \.
[u/mdw/putty] / misc.c
CommitLineData
374330e2 1#include <windows.h>
2#include <stdio.h>
3#include <stdlib.h>
5471d09a 4#include <assert.h>
374330e2 5#include "putty.h"
6
03f64569 7/* ----------------------------------------------------------------------
8 * String handling routines.
9 */
10
11char *dupstr(char *s)
12{
13 int len = strlen(s);
14 char *p = smalloc(len + 1);
15 strcpy(p, s);
16 return p;
17}
18
19/* Allocate the concatenation of N strings. Terminate arg list with NULL. */
20char *dupcat(char *s1, ...)
21{
22 int len;
23 char *p, *q, *sn;
24 va_list ap;
25
26 len = strlen(s1);
27 va_start(ap, s1);
28 while (1) {
29 sn = va_arg(ap, char *);
30 if (!sn)
31 break;
32 len += strlen(sn);
33 }
34 va_end(ap);
35
36 p = smalloc(len + 1);
37 strcpy(p, s1);
38 q = p + strlen(p);
39
40 va_start(ap, s1);
41 while (1) {
42 sn = va_arg(ap, char *);
43 if (!sn)
44 break;
45 strcpy(q, sn);
46 q += strlen(q);
47 }
48 va_end(ap);
49
50 return p;
51}
52
53/* ----------------------------------------------------------------------
1549e076 54 * Base64 encoding routine. This is required in public-key writing
55 * but also in HTTP proxy handling, so it's centralised here.
56 */
57
58void base64_encode_atom(unsigned char *data, int n, char *out)
59{
60 static const char base64_chars[] =
61 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
62
63 unsigned word;
64
65 word = data[0] << 16;
66 if (n > 1)
67 word |= data[1] << 8;
68 if (n > 2)
69 word |= data[2];
70 out[0] = base64_chars[(word >> 18) & 0x3F];
71 out[1] = base64_chars[(word >> 12) & 0x3F];
72 if (n > 1)
73 out[2] = base64_chars[(word >> 6) & 0x3F];
74 else
75 out[2] = '=';
76 if (n > 2)
77 out[3] = base64_chars[word & 0x3F];
78 else
79 out[3] = '=';
80}
81
82/* ----------------------------------------------------------------------
5471d09a 83 * Generic routines to deal with send buffers: a linked list of
84 * smallish blocks, with the operations
85 *
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
90 * call
7983f47e 91 * - retrieve a larger amount of initial data from the list
5471d09a 92 * - return the current size of the buffer chain in bytes
93 */
94
95#define BUFFER_GRANULE 512
96
97struct bufchain_granule {
98 struct bufchain_granule *next;
99 int buflen, bufpos;
100 char buf[BUFFER_GRANULE];
101};
102
103void bufchain_init(bufchain *ch)
104{
105 ch->head = ch->tail = NULL;
106 ch->buffersize = 0;
107}
108
109void bufchain_clear(bufchain *ch)
110{
111 struct bufchain_granule *b;
112 while (ch->head) {
113 b = ch->head;
114 ch->head = ch->head->next;
115 sfree(b);
116 }
117 ch->tail = NULL;
118 ch->buffersize = 0;
119}
120
121int bufchain_size(bufchain *ch)
122{
123 return ch->buffersize;
124}
125
126void bufchain_add(bufchain *ch, void *data, int len)
127{
128 char *buf = (char *)data;
129
130 ch->buffersize += len;
131
132 if (ch->tail && ch->tail->buflen < BUFFER_GRANULE) {
133 int copylen = min(len, BUFFER_GRANULE - ch->tail->buflen);
134 memcpy(ch->tail->buf + ch->tail->buflen, buf, copylen);
135 buf += copylen;
136 len -= copylen;
137 ch->tail->buflen += copylen;
138 }
139 while (len > 0) {
140 int grainlen = min(len, BUFFER_GRANULE);
141 struct bufchain_granule *newbuf;
142 newbuf = smalloc(sizeof(struct bufchain_granule));
143 newbuf->bufpos = 0;
144 newbuf->buflen = grainlen;
145 memcpy(newbuf->buf, buf, grainlen);
146 buf += grainlen;
147 len -= grainlen;
148 if (ch->tail)
149 ch->tail->next = newbuf;
150 else
151 ch->head = ch->tail = newbuf;
152 newbuf->next = NULL;
153 ch->tail = newbuf;
154 }
155}
156
157void bufchain_consume(bufchain *ch, int len)
158{
7983f47e 159 struct bufchain_granule *tmp;
160
5471d09a 161 assert(ch->buffersize >= len);
7983f47e 162 while (len > 0) {
163 int remlen = len;
164 assert(ch->head != NULL);
165 if (remlen >= ch->head->buflen - ch->head->bufpos) {
166 remlen = ch->head->buflen - ch->head->bufpos;
167 tmp = ch->head;
168 ch->head = tmp->next;
169 sfree(tmp);
170 if (!ch->head)
171 ch->tail = NULL;
172 } else
173 ch->head->bufpos += remlen;
174 ch->buffersize -= remlen;
175 len -= remlen;
5471d09a 176 }
177}
178
179void bufchain_prefix(bufchain *ch, void **data, int *len)
180{
181 *len = ch->head->buflen - ch->head->bufpos;
182 *data = ch->head->buf + ch->head->bufpos;
183}
184
7983f47e 185void bufchain_fetch(bufchain *ch, void *data, int len)
186{
187 struct bufchain_granule *tmp;
188 char *data_c = (char *)data;
189
190 tmp = ch->head;
191
192 assert(ch->buffersize >= len);
193 while (len > 0) {
194 int remlen = len;
195
196 assert(tmp != NULL);
197 if (remlen >= tmp->buflen - tmp->bufpos)
198 remlen = tmp->buflen - tmp->bufpos;
199 memcpy(data_c, tmp->buf + tmp->bufpos, remlen);
200
201 tmp = tmp->next;
202 len -= remlen;
203 data_c += remlen;
204 }
205}
206
03f64569 207/* ----------------------------------------------------------------------
b191636d 208 * My own versions of malloc, realloc and free. Because I want
209 * malloc and realloc to bomb out and exit the program if they run
210 * out of memory, realloc to reliably call malloc if passed a NULL
211 * pointer, and free to reliably do nothing if passed a NULL
212 * pointer. We can also put trace printouts in, if we need to; and
213 * we can also replace the allocator with an ElectricFence-like
214 * one.
215 */
216
217#ifdef MINEFIELD
218/*
219 * Minefield - a Windows equivalent for Electric Fence
220 */
221
222#define PAGESIZE 4096
223
224/*
225 * Design:
226 *
227 * We start by reserving as much virtual address space as Windows
228 * will sensibly (or not sensibly) let us have. We flag it all as
229 * invalid memory.
230 *
231 * Any allocation attempt is satisfied by committing one or more
232 * pages, with an uncommitted page on either side. The returned
233 * memory region is jammed up against the _end_ of the pages.
234 *
235 * Freeing anything causes instantaneous decommitment of the pages
236 * involved, so stale pointers are caught as soon as possible.
237 */
238
239static int minefield_initialised = 0;
240static void *minefield_region = NULL;
241static long minefield_size = 0;
242static long minefield_npages = 0;
243static long minefield_curpos = 0;
244static unsigned short *minefield_admin = NULL;
245static void *minefield_pages = NULL;
246
32874aea 247static void minefield_admin_hide(int hide)
248{
b191636d 249 int access = hide ? PAGE_NOACCESS : PAGE_READWRITE;
32874aea 250 VirtualProtect(minefield_admin, minefield_npages * 2, access, NULL);
b191636d 251}
252
32874aea 253static void minefield_init(void)
254{
b191636d 255 int size;
256 int admin_size;
257 int i;
258
32874aea 259 for (size = 0x40000000; size > 0; size = ((size >> 3) * 7) & ~0xFFF) {
260 minefield_region = VirtualAlloc(NULL, size,
261 MEM_RESERVE, PAGE_NOACCESS);
262 if (minefield_region)
263 break;
b191636d 264 }
265 minefield_size = size;
b191636d 266
267 /*
268 * Firstly, allocate a section of that to be the admin block.
269 * We'll need a two-byte field for each page.
270 */
271 minefield_admin = minefield_region;
272 minefield_npages = minefield_size / PAGESIZE;
32874aea 273 admin_size = (minefield_npages * 2 + PAGESIZE - 1) & ~(PAGESIZE - 1);
b191636d 274 minefield_npages = (minefield_size - admin_size) / PAGESIZE;
32874aea 275 minefield_pages = (char *) minefield_region + admin_size;
b191636d 276
277 /*
278 * Commit the admin region.
279 */
280 VirtualAlloc(minefield_admin, minefield_npages * 2,
32874aea 281 MEM_COMMIT, PAGE_READWRITE);
b191636d 282
283 /*
284 * Mark all pages as unused (0xFFFF).
285 */
286 for (i = 0; i < minefield_npages; i++)
32874aea 287 minefield_admin[i] = 0xFFFF;
b191636d 288
289 /*
290 * Hide the admin region.
291 */
292 minefield_admin_hide(1);
293
294 minefield_initialised = 1;
295}
296
32874aea 297static void minefield_bomb(void)
298{
299 div(1, *(int *) minefield_pages);
b191636d 300}
301
32874aea 302static void *minefield_alloc(int size)
303{
b191636d 304 int npages;
305 int pos, lim, region_end, region_start;
306 int start;
307 int i;
308
32874aea 309 npages = (size + PAGESIZE - 1) / PAGESIZE;
b191636d 310
311 minefield_admin_hide(0);
312
313 /*
314 * Search from current position until we find a contiguous
315 * bunch of npages+2 unused pages.
316 */
317 pos = minefield_curpos;
318 lim = minefield_npages;
319 while (1) {
32874aea 320 /* Skip over used pages. */
321 while (pos < lim && minefield_admin[pos] != 0xFFFF)
322 pos++;
323 /* Count unused pages. */
324 start = pos;
325 while (pos < lim && pos - start < npages + 2 &&
326 minefield_admin[pos] == 0xFFFF)
327 pos++;
328 if (pos - start == npages + 2)
329 break;
330 /* If we've reached the limit, reset the limit or stop. */
331 if (pos >= lim) {
332 if (lim == minefield_npages) {
333 /* go round and start again at zero */
334 lim = minefield_curpos;
335 pos = 0;
336 } else {
337 minefield_admin_hide(1);
338 return NULL;
339 }
340 }
b191636d 341 }
342
32874aea 343 minefield_curpos = pos - 1;
b191636d 344
345 /*
346 * We have npages+2 unused pages starting at start. We leave
347 * the first and last of these alone and use the rest.
348 */
32874aea 349 region_end = (start + npages + 1) * PAGESIZE;
b191636d 350 region_start = region_end - size;
351 /* FIXME: could align here if we wanted */
352
353 /*
354 * Update the admin region.
355 */
0f7432cc 356 for (i = start + 2; i < start + npages + 1; i++)
32874aea 357 minefield_admin[i] = 0xFFFE; /* used but no region starts here */
358 minefield_admin[start + 1] = region_start % PAGESIZE;
b191636d 359
360 minefield_admin_hide(1);
361
32874aea 362 VirtualAlloc((char *) minefield_pages + region_start, size,
363 MEM_COMMIT, PAGE_READWRITE);
364 return (char *) minefield_pages + region_start;
b191636d 365}
366
32874aea 367static void minefield_free(void *ptr)
368{
b191636d 369 int region_start, i, j;
370
371 minefield_admin_hide(0);
372
32874aea 373 region_start = (char *) ptr - (char *) minefield_pages;
b191636d 374 i = region_start / PAGESIZE;
375 if (i < 0 || i >= minefield_npages ||
32874aea 376 minefield_admin[i] != region_start % PAGESIZE)
377 minefield_bomb();
b191636d 378 for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++) {
32874aea 379 minefield_admin[j] = 0xFFFF;
b191636d 380 }
381
32874aea 382 VirtualFree(ptr, j * PAGESIZE - region_start, MEM_DECOMMIT);
b191636d 383
384 minefield_admin_hide(1);
385}
386
32874aea 387static int minefield_get_size(void *ptr)
388{
b191636d 389 int region_start, i, j;
390
391 minefield_admin_hide(0);
392
32874aea 393 region_start = (char *) ptr - (char *) minefield_pages;
b191636d 394 i = region_start / PAGESIZE;
395 if (i < 0 || i >= minefield_npages ||
32874aea 396 minefield_admin[i] != region_start % PAGESIZE)
397 minefield_bomb();
b191636d 398 for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++);
399
400 minefield_admin_hide(1);
401
32874aea 402 return j * PAGESIZE - region_start;
b191636d 403}
404
32874aea 405static void *minefield_c_malloc(size_t size)
406{
407 if (!minefield_initialised)
408 minefield_init();
b191636d 409 return minefield_alloc(size);
410}
411
32874aea 412static void minefield_c_free(void *p)
413{
414 if (!minefield_initialised)
415 minefield_init();
b191636d 416 minefield_free(p);
417}
418
419/*
420 * realloc _always_ moves the chunk, for rapid detection of code
421 * that assumes it won't.
422 */
32874aea 423static void *minefield_c_realloc(void *p, size_t size)
424{
b191636d 425 size_t oldsize;
426 void *q;
32874aea 427 if (!minefield_initialised)
428 minefield_init();
b191636d 429 q = minefield_alloc(size);
430 oldsize = minefield_get_size(p);
431 memcpy(q, p, (oldsize < size ? oldsize : size));
432 minefield_free(p);
433 return q;
434}
435
32874aea 436#endif /* MINEFIELD */
374330e2 437
438#ifdef MALLOC_LOG
439static FILE *fp = NULL;
440
d7da76ca 441static char *mlog_file = NULL;
442static int mlog_line = 0;
443
32874aea 444void mlog(char *file, int line)
445{
d7da76ca 446 mlog_file = file;
447 mlog_line = line;
c662dbc0 448 if (!fp) {
374330e2 449 fp = fopen("putty_mem.log", "w");
c662dbc0 450 setvbuf(fp, NULL, _IONBF, BUFSIZ);
451 }
374330e2 452 if (fp)
32874aea 453 fprintf(fp, "%s:%d: ", file, line);
374330e2 454}
455#endif
456
32874aea 457void *safemalloc(size_t size)
458{
b191636d 459 void *p;
460#ifdef MINEFIELD
32874aea 461 p = minefield_c_malloc(size);
b191636d 462#else
32874aea 463 p = malloc(size);
b191636d 464#endif
374330e2 465 if (!p) {
d7da76ca 466 char str[200];
467#ifdef MALLOC_LOG
468 sprintf(str, "Out of memory! (%s:%d, size=%d)",
469 mlog_file, mlog_line, size);
1b2ef365 470 fprintf(fp, "*** %s\n", str);
471 fclose(fp);
d7da76ca 472#else
473 strcpy(str, "Out of memory!");
474#endif
475 MessageBox(NULL, str, "PuTTY Fatal Error",
374330e2 476 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
93b581bd 477 cleanup_exit(1);
374330e2 478 }
479#ifdef MALLOC_LOG
480 if (fp)
481 fprintf(fp, "malloc(%d) returns %p\n", size, p);
482#endif
483 return p;
484}
485
32874aea 486void *saferealloc(void *ptr, size_t size)
487{
374330e2 488 void *p;
b191636d 489 if (!ptr) {
490#ifdef MINEFIELD
32874aea 491 p = minefield_c_malloc(size);
b191636d 492#else
32874aea 493 p = malloc(size);
b191636d 494#endif
495 } else {
496#ifdef MINEFIELD
32874aea 497 p = minefield_c_realloc(ptr, size);
b191636d 498#else
32874aea 499 p = realloc(ptr, size);
b191636d 500#endif
501 }
374330e2 502 if (!p) {
d7da76ca 503 char str[200];
504#ifdef MALLOC_LOG
505 sprintf(str, "Out of memory! (%s:%d, size=%d)",
506 mlog_file, mlog_line, size);
1b2ef365 507 fprintf(fp, "*** %s\n", str);
508 fclose(fp);
d7da76ca 509#else
510 strcpy(str, "Out of memory!");
511#endif
512 MessageBox(NULL, str, "PuTTY Fatal Error",
374330e2 513 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
93b581bd 514 cleanup_exit(1);
374330e2 515 }
516#ifdef MALLOC_LOG
517 if (fp)
518 fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
519#endif
520 return p;
521}
522
32874aea 523void safefree(void *ptr)
524{
374330e2 525 if (ptr) {
526#ifdef MALLOC_LOG
527 if (fp)
528 fprintf(fp, "free(%p)\n", ptr);
529#endif
b191636d 530#ifdef MINEFIELD
32874aea 531 minefield_c_free(ptr);
b191636d 532#else
32874aea 533 free(ptr);
b191636d 534#endif
374330e2 535 }
536#ifdef MALLOC_LOG
537 else if (fp)
538 fprintf(fp, "freeing null pointer - no action taken\n");
539#endif
540}
c82bda52 541
03f64569 542/* ----------------------------------------------------------------------
543 * Debugging routines.
544 */
545
c82bda52 546#ifdef DEBUG
547static FILE *debug_fp = NULL;
548static int debug_got_console = 0;
549
32874aea 550static void dputs(char *buf)
551{
c82bda52 552 DWORD dw;
c82bda52 553
554 if (!debug_got_console) {
555 AllocConsole();
556 debug_got_console = 1;
557 }
558 if (!debug_fp) {
559 debug_fp = fopen("debug.log", "w");
560 }
561
32874aea 562 WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, strlen(buf), &dw,
563 NULL);
c82bda52 564 fputs(buf, debug_fp);
565 fflush(debug_fp);
db9c0f86 566}
567
568
32874aea 569void dprintf(char *fmt, ...)
570{
db9c0f86 571 char buf[2048];
572 va_list ap;
573
574 va_start(ap, fmt);
575 vsprintf(buf, fmt, ap);
32874aea 576 dputs(buf);
c82bda52 577 va_end(ap);
578}
db9c0f86 579
580
32874aea 581void debug_memdump(void *buf, int len, int L)
582{
db9c0f86 583 int i;
584 unsigned char *p = buf;
765c4200 585 char foo[17];
db9c0f86 586 if (L) {
587 int delta;
32874aea 588 dprintf("\t%d (0x%x) bytes:\n", len, len);
db9c0f86 589 delta = 15 & (int) p;
590 p -= delta;
591 len += delta;
592 }
593 for (; 0 < len; p += 16, len -= 16) {
32874aea 594 dputs(" ");
595 if (L)
596 dprintf("%p: ", p);
597 strcpy(foo, "................"); /* sixteen dots */
db9c0f86 598 for (i = 0; i < 16 && i < len; ++i) {
599 if (&p[i] < (unsigned char *) buf) {
32874aea 600 dputs(" "); /* 3 spaces */
765c4200 601 foo[i] = ' ';
db9c0f86 602 } else {
32874aea 603 dprintf("%c%02.2x",
604 &p[i] != (unsigned char *) buf
605 && i % 4 ? '.' : ' ', p[i]
606 );
765c4200 607 if (p[i] >= ' ' && p[i] <= '~')
32874aea 608 foo[i] = (char) p[i];
db9c0f86 609 }
610 }
765c4200 611 foo[i] = '\0';
32874aea 612 dprintf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
db9c0f86 613 }
614}
615
32874aea 616#endif /* def DEBUG */