Move dprintf and the debug system out into misc.c, to centralise it.
[u/mdw/putty] / misc.c
1 #include <windows.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include "putty.h"
5
6 /* My own versions of malloc, realloc and free. Because I want malloc and
7 * realloc to bomb out and exit the program if they run out of memory,
8 * realloc to reliably call malloc if passed a NULL pointer, and free
9 * to reliably do nothing if passed a NULL pointer. Of course we can also
10 * put trace printouts in, if we need to. */
11
12 #ifdef MALLOC_LOG
13 static FILE *fp = NULL;
14
15 void mlog(char *file, int line) {
16 if (!fp) {
17 fp = fopen("putty_mem.log", "w");
18 setvbuf(fp, NULL, _IONBF, BUFSIZ);
19 }
20 if (fp)
21 fprintf (fp, "%s:%d: ", file, line);
22 }
23 #endif
24
25 void *safemalloc(size_t size) {
26 void *p = malloc (size);
27 if (!p) {
28 MessageBox(NULL, "Out of memory!", "PuTTY Fatal Error",
29 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
30 exit(1);
31 }
32 #ifdef MALLOC_LOG
33 if (fp)
34 fprintf(fp, "malloc(%d) returns %p\n", size, p);
35 #endif
36 return p;
37 }
38
39 void *saferealloc(void *ptr, size_t size) {
40 void *p;
41 if (!ptr)
42 p = malloc (size);
43 else
44 p = realloc (ptr, size);
45 if (!p) {
46 MessageBox(NULL, "Out of memory!", "PuTTY Fatal Error",
47 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
48 exit(1);
49 }
50 #ifdef MALLOC_LOG
51 if (fp)
52 fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
53 #endif
54 return p;
55 }
56
57 void safefree(void *ptr) {
58 if (ptr) {
59 #ifdef MALLOC_LOG
60 if (fp)
61 fprintf(fp, "free(%p)\n", ptr);
62 #endif
63 free (ptr);
64 }
65 #ifdef MALLOC_LOG
66 else if (fp)
67 fprintf(fp, "freeing null pointer - no action taken\n");
68 #endif
69 }
70
71 #ifdef DEBUG
72 static FILE *debug_fp = NULL;
73 static int debug_got_console = 0;
74
75 void dprintf(char *fmt, ...) {
76 char buf[2048];
77 DWORD dw;
78 va_list ap;
79
80 if (!debug_got_console) {
81 AllocConsole();
82 debug_got_console = 1;
83 }
84 if (!debug_fp) {
85 debug_fp = fopen("debug.log", "w");
86 }
87
88 va_start(ap, fmt);
89 vsprintf(buf, fmt, ap);
90 WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, strlen(buf), &dw, NULL);
91 fputs(buf, debug_fp);
92 fflush(debug_fp);
93 va_end(ap);
94 }
95 #endif