]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/trace/lib_trace.c
ncurses 6.1 - patch 20191207
[ncurses.git] / ncurses / trace / lib_trace.c
1 /****************************************************************************
2  * Copyright (c) 1998-2018,2019 Free Software Foundation, Inc.              *
3  *                                                                          *
4  * Permission is hereby granted, free of charge, to any person obtaining a  *
5  * copy of this software and associated documentation files (the            *
6  * "Software"), to deal in the Software without restriction, including      *
7  * without limitation the rights to use, copy, modify, merge, publish,      *
8  * distribute, distribute with modifications, sublicense, and/or sell       *
9  * copies of the Software, and to permit persons to whom the Software is    *
10  * furnished to do so, subject to the following conditions:                 *
11  *                                                                          *
12  * The above copyright notice and this permission notice shall be included  *
13  * in all copies or substantial portions of the Software.                   *
14  *                                                                          *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
16  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
18  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
19  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
20  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
21  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
22  *                                                                          *
23  * Except as contained in this notice, the name(s) of the above copyright   *
24  * holders shall not be used in advertising or otherwise to promote the     *
25  * sale, use or other dealings in this Software without prior written       *
26  * authorization.                                                           *
27  ****************************************************************************/
28
29 /****************************************************************************
30  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
31  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
32  *     and: Thomas E. Dickey                        1996-on                 *
33  *     and: Juergen Pfeifer                                                 *
34  ****************************************************************************/
35
36 /*
37  *      lib_trace.c - Tracing/Debugging routines
38  *
39  * The _tracef() function is originally from pcurses (by Pavel Curtis) in 1982. 
40  * pcurses allowed one to enable/disable tracing using traceon() and traceoff()
41  * functions.  ncurses provides a trace() function which allows one to
42  * selectively enable or disable several tracing features.
43  */
44
45 #include <curses.priv.h>
46 #include <tic.h>
47
48 #include <ctype.h>
49
50 MODULE_ID("$Id: lib_trace.c,v 1.94 2019/12/07 22:32:36 tom Exp $")
51
52 NCURSES_EXPORT_VAR(unsigned) _nc_tracing = 0; /* always define this */
53
54 #ifdef TRACE
55
56 #if USE_REENTRANT
57 NCURSES_EXPORT(const char *)
58 NCURSES_PUBLIC_VAR(_nc_tputs_trace) (void)
59 {
60     return CURRENT_SCREEN ? CURRENT_SCREEN->_tputs_trace : _nc_prescreen._tputs_trace;
61 }
62 NCURSES_EXPORT(long)
63 NCURSES_PUBLIC_VAR(_nc_outchars) (void)
64 {
65     return CURRENT_SCREEN ? CURRENT_SCREEN->_outchars : _nc_prescreen._outchars;
66 }
67 NCURSES_EXPORT(void)
68 _nc_set_tputs_trace(const char *s)
69 {
70     if (CURRENT_SCREEN)
71         CURRENT_SCREEN->_tputs_trace = s;
72     else
73         _nc_prescreen._tputs_trace = s;
74 }
75 NCURSES_EXPORT(void)
76 _nc_count_outchars(long increment)
77 {
78     if (CURRENT_SCREEN)
79         CURRENT_SCREEN->_outchars += increment;
80     else
81         _nc_prescreen._outchars += increment;
82 }
83 #else
84 NCURSES_EXPORT_VAR(const char *) _nc_tputs_trace = "";
85 NCURSES_EXPORT_VAR(long) _nc_outchars = 0;
86 #endif
87
88 #define MyFP            _nc_globals.trace_fp
89 #define MyFD            _nc_globals.trace_fd
90 #define MyInit          _nc_globals.trace_opened
91 #define MyPath          _nc_globals.trace_fname
92 #define MyLevel         _nc_globals.trace_level
93 #define MyNested        _nc_globals.nested_tracef
94 #endif /* TRACE */
95
96 NCURSES_EXPORT(unsigned)
97 curses_trace(unsigned tracelevel)
98 {
99     unsigned result;
100 #if defined(TRACE)
101     result = _nc_tracing;
102     if ((MyFP == 0) && tracelevel) {
103         MyInit = TRUE;
104         if (MyFD >= 0) {
105             MyFP = fdopen(MyFD, BIN_W);
106         } else {
107             if (MyPath[0] == '\0') {
108                 size_t size = sizeof(MyPath) - 12;
109                 if (getcwd(MyPath, size) == 0) {
110                     perror("curses: Can't get working directory");
111                     exit(EXIT_FAILURE);
112                 }
113                 MyPath[size] = '\0';
114                 assert(strlen(MyPath) <= size);
115                 _nc_STRCAT(MyPath, "/trace", sizeof(MyPath));
116                 if (_nc_is_dir_path(MyPath)) {
117                     _nc_STRCAT(MyPath, ".log", sizeof(MyPath));
118                 }
119             }
120             if (_nc_access(MyPath, W_OK) < 0
121                 || (MyFD = open(MyPath, O_CREAT | O_EXCL | O_RDWR, 0600)) < 0
122                 || (MyFP = fdopen(MyFD, BIN_W)) == 0) {
123                 ;               /* EMPTY */
124             }
125         }
126         _nc_tracing = tracelevel;
127         /* Try to set line-buffered mode, or (failing that) unbuffered,
128          * so that the trace-output gets flushed automatically at the
129          * end of each line.  This is useful in case the program dies. 
130          */
131         if (MyFP != 0) {
132 #if HAVE_SETVBUF                /* ANSI */
133             (void) setvbuf(MyFP, (char *) 0, _IOLBF, (size_t) 0);
134 #elif HAVE_SETBUF /* POSIX */
135             (void) setbuffer(MyFP, (char *) 0);
136 #endif
137         }
138         _tracef("TRACING NCURSES version %s.%d (tracelevel=%#x)",
139                 NCURSES_VERSION,
140                 NCURSES_VERSION_PATCH,
141                 tracelevel);
142     } else if (tracelevel == 0) {
143         if (MyFP != 0) {
144             MyFD = dup(MyFD);   /* allow reopen of same file */
145             fclose(MyFP);
146             MyFP = 0;
147         }
148         _nc_tracing = tracelevel;
149     } else if (_nc_tracing != tracelevel) {
150         _nc_tracing = tracelevel;
151         _tracef("tracelevel=%#x", tracelevel);
152     }
153 #else
154     (void) tracelevel;
155     result = 0;
156 #endif
157     return result;
158 }
159
160 #if defined(TRACE)
161 NCURSES_EXPORT(void)
162 trace(const unsigned int tracelevel)
163 {
164     curses_trace(tracelevel);
165 }
166
167 static void
168 _nc_va_tracef(const char *fmt, va_list ap)
169 {
170     static const char Called[] = T_CALLED("");
171     static const char Return[] = T_RETURN("");
172
173     bool before = FALSE;
174     bool after = FALSE;
175     unsigned doit = _nc_tracing;
176     int save_err = errno;
177     FILE *fp = MyFP;
178
179 #ifdef TRACE
180     /* verbose-trace in the command-line utilities relies on this */
181     if (fp == 0 && !MyInit && _nc_tracing >= DEBUG_LEVEL(1))
182         fp = stderr;
183 #endif
184
185     if (strlen(fmt) >= sizeof(Called) - 1) {
186         if (!strncmp(fmt, Called, sizeof(Called) - 1)) {
187             before = TRUE;
188             MyLevel++;
189         } else if (!strncmp(fmt, Return, sizeof(Return) - 1)) {
190             after = TRUE;
191         }
192         if (before || after) {
193             if ((MyLevel <= 1)
194                 || (doit & TRACE_ICALLS) != 0)
195                 doit &= (TRACE_CALLS | TRACE_CCALLS);
196             else
197                 doit = 0;
198         }
199     }
200
201     if (doit != 0 && fp != 0) {
202 #ifdef USE_PTHREADS
203         /*
204          * TRACE_ICALLS is "really" needed to show normal use with threaded
205          * applications, since anything can be running during a napms(),
206          * making it appear in the hierarchical trace as it other functions
207          * are being called.
208          *
209          * Rather than add the complication of a per-thread stack, just
210          * show the thread-id in each line of the trace.
211          */
212 # if USE_WEAK_SYMBOLS
213         if ((pthread_self))
214 # endif
215 #ifdef _WIN32
216             fprintf(fp, "%#lx:", (long) (intptr_t) pthread_self().p);
217 #else
218             fprintf(fp, "%#lx:", (long) (intptr_t) pthread_self());
219 #endif
220 #endif
221         if (before || after) {
222             int n;
223             for (n = 1; n < MyLevel; n++)
224                 fputs("+ ", fp);
225         }
226         vfprintf(fp, fmt, ap);
227         fputc('\n', fp);
228         fflush(fp);
229     }
230
231     if (after && MyLevel)
232         MyLevel--;
233
234     errno = save_err;
235 }
236
237 NCURSES_EXPORT(void)
238 _tracef(const char *fmt, ...)
239 {
240     va_list ap;
241
242     va_start(ap, fmt);
243     _nc_va_tracef(fmt, ap);
244     va_end(ap);
245 }
246
247 /* Trace 'bool' return-values */
248 NCURSES_EXPORT(NCURSES_BOOL)
249 _nc_retrace_bool(int code)
250 {
251     T((T_RETURN("%s"), code ? "TRUE" : "FALSE"));
252     return code;
253 }
254
255 /* Trace 'char' return-values */
256 NCURSES_EXPORT(char)
257 _nc_retrace_char(int code)
258 {
259     T((T_RETURN("%c"), code));
260     return (char) code;
261 }
262
263 /* Trace 'int' return-values */
264 NCURSES_EXPORT(int)
265 _nc_retrace_int(int code)
266 {
267     T((T_RETURN("%d"), code));
268     return code;
269 }
270
271 /* Trace 'unsigned' return-values */
272 NCURSES_EXPORT(unsigned)
273 _nc_retrace_unsigned(unsigned code)
274 {
275     T((T_RETURN("%#x"), code));
276     return code;
277 }
278
279 /* Trace 'char*' return-values */
280 NCURSES_EXPORT(char *)
281 _nc_retrace_ptr(char *code)
282 {
283     T((T_RETURN("%s"), _nc_visbuf(code)));
284     return code;
285 }
286
287 /* Trace 'const char*' return-values */
288 NCURSES_EXPORT(const char *)
289 _nc_retrace_cptr(const char *code)
290 {
291     T((T_RETURN("%s"), _nc_visbuf(code)));
292     return code;
293 }
294
295 /* Trace 'NCURSES_CONST void*' return-values */
296 NCURSES_EXPORT(NCURSES_CONST void *)
297 _nc_retrace_cvoid_ptr(NCURSES_CONST void *code)
298 {
299     T((T_RETURN("%p"), code));
300     return code;
301 }
302
303 /* Trace 'void*' return-values */
304 NCURSES_EXPORT(void *)
305 _nc_retrace_void_ptr(void *code)
306 {
307     T((T_RETURN("%p"), code));
308     return code;
309 }
310
311 /* Trace 'SCREEN *' return-values */
312 NCURSES_EXPORT(SCREEN *)
313 _nc_retrace_sp(SCREEN *code)
314 {
315     T((T_RETURN("%p"), (void *) code));
316     return code;
317 }
318
319 /* Trace 'WINDOW *' return-values */
320 NCURSES_EXPORT(WINDOW *)
321 _nc_retrace_win(WINDOW *code)
322 {
323     T((T_RETURN("%p"), (void *) code));
324     return code;
325 }
326
327 NCURSES_EXPORT(char *)
328 _nc_fmt_funcptr(char *target, const char *source, size_t size)
329 {
330     size_t n;
331     char *dst = target;
332     bool leading = TRUE;
333
334     union {
335         int value;
336         char bytes[sizeof(int)];
337     } byteorder;
338
339     byteorder.value = 0x1234;
340
341     *dst++ = '0';
342     *dst++ = 'x';
343
344     for (n = 0; n < size; ++n) {
345         unsigned ch = ((byteorder.bytes[0] == 0x34)
346                        ? UChar(source[size - n - 1])
347                        : UChar(source[n]));
348         if (ch != 0 || (n + 1) >= size)
349             leading = FALSE;
350         if (!leading) {
351             _nc_SPRINTF(dst, _nc_SLIMIT(TR_FUNC_LEN - (dst - target))
352                         "%02x", ch & 0xff);
353             dst += 2;
354         }
355     }
356     *dst = '\0';
357     return target;
358 }
359
360 #if USE_REENTRANT
361 /*
362  * Check if the given trace-mask is enabled.
363  *
364  * This function may be called from within one of the functions that fills
365  * in parameters for _tracef(), but in that case we do not want to lock the
366  * mutex, since it is already locked.
367  */
368 NCURSES_EXPORT(int)
369 _nc_use_tracef(unsigned mask)
370 {
371     bool result = FALSE;
372
373     _nc_lock_global(tst_tracef);
374     if (!MyNested++) {
375         if ((result = (_nc_tracing & (mask))) != 0
376             && _nc_try_global(tracef) == 0) {
377             /* we will call _nc_locked_tracef(), no nesting so far */
378         } else {
379             /* we will not call _nc_locked_tracef() */
380             MyNested = 0;
381         }
382     } else {
383         /* we may call _nc_locked_tracef(), but with nested_tracef > 0 */
384         result = (_nc_tracing & (mask));
385     }
386     _nc_unlock_global(tst_tracef);
387     return result;
388 }
389
390 /*
391  * We call this if _nc_use_tracef() returns true, which means we must unlock
392  * the tracef mutex.
393  */
394 NCURSES_EXPORT(void)
395 _nc_locked_tracef(const char *fmt, ...)
396 {
397     va_list ap;
398
399     va_start(ap, fmt);
400     _nc_va_tracef(fmt, ap);
401     va_end(ap);
402
403     if (--(MyNested) == 0) {
404         _nc_unlock_global(tracef);
405     }
406 }
407 #endif /* USE_REENTRANT */
408
409 #endif /* TRACE */