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