]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/trace/lib_trace.c
ncurses 6.4 - patch 20230603
[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.103 2023/05/28 14:39:10 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     do { \
100         _nc_lock_global(tst_tracef); \
101         statement; \
102         _nc_unlock_global(tst_tracef); \
103     } while (0)
104 #else
105 #define Locked(statement) statement
106 #endif
107
108 NCURSES_EXPORT(unsigned)
109 curses_trace(unsigned tracelevel)
110 {
111     unsigned result;
112
113 #if defined(TRACE)
114     int bit;
115
116 #define DATA(name) { name, #name }
117     static struct {
118         unsigned mask;
119         const char *name;
120     } trace_names[] = {
121         DATA(TRACE_TIMES),
122             DATA(TRACE_TPUTS),
123             DATA(TRACE_UPDATE),
124             DATA(TRACE_MOVE),
125             DATA(TRACE_CHARPUT),
126             DATA(TRACE_CALLS),
127             DATA(TRACE_VIRTPUT),
128             DATA(TRACE_IEVENT),
129             DATA(TRACE_BITS),
130             DATA(TRACE_ICALLS),
131             DATA(TRACE_CCALLS),
132             DATA(TRACE_DATABASE),
133             DATA(TRACE_ATTRS)
134     };
135 #undef DATA
136
137     Locked(result = _nc_tracing);
138
139     if ((MyFP == 0) && tracelevel) {
140         MyInit = TRUE;
141         if (MyFD >= 0) {
142             MyFP = fdopen(MyFD, BIN_W);
143         } else {
144             if (MyPath[0] == '\0') {
145                 size_t size = sizeof(MyPath) - 12;
146                 if (getcwd(MyPath, size) == 0) {
147                     perror("curses: Can't get working directory");
148                     exit(EXIT_FAILURE);
149                 }
150                 MyPath[size] = '\0';
151                 assert(strlen(MyPath) <= size);
152                 _nc_STRCAT(MyPath, "/trace", sizeof(MyPath));
153                 if (_nc_is_dir_path(MyPath)) {
154                     _nc_STRCAT(MyPath, ".log", sizeof(MyPath));
155                 }
156             }
157 #define SAFE_MODE (O_CREAT | O_EXCL | O_RDWR)
158             if (_nc_access(MyPath, W_OK) < 0
159                 || (MyFD = safe_open3(MyPath, SAFE_MODE, 0600)) < 0
160                 || (MyFP = fdopen(MyFD, BIN_W)) == 0) {
161                 ;               /* EMPTY */
162             }
163         }
164         Locked(_nc_tracing = tracelevel);
165         /* Try to set line-buffered mode, or (failing that) unbuffered,
166          * so that the trace-output gets flushed automatically at the
167          * end of each line.  This is useful in case the program dies.
168          */
169         if (MyFP != 0) {
170 #if HAVE_SETVBUF                /* ANSI */
171             (void) setvbuf(MyFP, (char *) 0, _IOLBF, (size_t) 0);
172 #elif HAVE_SETBUF /* POSIX */
173             (void) setbuffer(MyFP, (char *) 0);
174 #endif
175         }
176         _tracef("TRACING NCURSES version %s.%d (tracelevel=%#x)",
177                 NCURSES_VERSION,
178                 NCURSES_VERSION_PATCH,
179                 tracelevel);
180
181 #define SPECIAL_MASK(mask) \
182             if ((tracelevel & mask) == mask) \
183                 _tracef("- %s (%u)", #mask, mask)
184
185         for (bit = 0; bit < TRACE_SHIFT; ++bit) {
186             unsigned mask = (1U << bit) & tracelevel;
187             if ((mask & trace_names[bit].mask) != 0) {
188                 _tracef("- %s (%u)", trace_names[bit].name, mask);
189             }
190         }
191         SPECIAL_MASK(TRACE_MAXIMUM);
192         else
193         SPECIAL_MASK(TRACE_ORDINARY);
194
195         if (tracelevel > TRACE_MAXIMUM) {
196             _tracef("- DEBUG_LEVEL(%u)", tracelevel >> TRACE_SHIFT);
197         }
198     } else if (tracelevel == 0) {
199         if (MyFP != 0) {
200             MyFD = dup(MyFD);   /* allow reopen of same file */
201             fclose(MyFP);
202             MyFP = 0;
203         }
204         Locked(_nc_tracing = tracelevel);
205     } else if (_nc_tracing != tracelevel) {
206         Locked(_nc_tracing = tracelevel);
207         _tracef("tracelevel=%#x", tracelevel);
208     }
209 #else
210     (void) tracelevel;
211     result = 0;
212 #endif
213     return result;
214 }
215
216 #if defined(TRACE)
217 NCURSES_EXPORT(void)
218 trace(const unsigned int tracelevel)
219 {
220     curses_trace(tracelevel);
221 }
222
223 static void
224 _nc_va_tracef(const char *fmt, va_list ap)
225 {
226     static const char Called[] = T_CALLED("");
227     static const char Return[] = T_RETURN("");
228
229     bool before = FALSE;
230     bool after = FALSE;
231     unsigned doit = _nc_tracing;
232     int save_err = errno;
233     FILE *fp = MyFP;
234
235 #ifdef TRACE
236     /* verbose-trace in the command-line utilities relies on this */
237     if (fp == 0 && !MyInit && _nc_tracing >= DEBUG_LEVEL(1))
238         fp = stderr;
239 #endif
240
241     if (strlen(fmt) >= sizeof(Called) - 1) {
242         if (!strncmp(fmt, Called, sizeof(Called) - 1)) {
243             before = TRUE;
244             MyLevel++;
245         } else if (!strncmp(fmt, Return, sizeof(Return) - 1)) {
246             after = TRUE;
247         }
248         if (before || after) {
249             if ((MyLevel <= 1)
250                 || (doit & TRACE_ICALLS) != 0)
251                 doit &= (TRACE_CALLS | TRACE_CCALLS);
252             else
253                 doit = 0;
254         }
255     }
256
257     if (doit != 0 && fp != 0) {
258 #ifdef USE_PTHREADS
259         /*
260          * TRACE_ICALLS is "really" needed to show normal use with threaded
261          * applications, since anything can be running during a napms(),
262          * making it appear in the hierarchical trace as it other functions
263          * are being called.
264          *
265          * Rather than add the complication of a per-thread stack, just
266          * show the thread-id in each line of the trace.
267          */
268 # if USE_WEAK_SYMBOLS
269         if ((pthread_self))
270 # endif
271             fprintf(fp, "%#" PRIxPTR ":",
272 #ifdef _NC_WINDOWS
273                     CASTxPTR(pthread_self().p)
274 #else
275                     CASTxPTR(pthread_self())
276 #endif
277                 );
278 #endif
279         if (before || after) {
280             int n;
281             for (n = 1; n < MyLevel; n++)
282                 fputs("+ ", fp);
283         }
284         vfprintf(fp, fmt, ap);
285         fputc('\n', fp);
286         fflush(fp);
287     }
288
289     if (after && MyLevel)
290         MyLevel--;
291
292     errno = save_err;
293 }
294
295 NCURSES_EXPORT(void)
296 _tracef(const char *fmt, ...)
297 {
298     va_list ap;
299
300     va_start(ap, fmt);
301     _nc_va_tracef(fmt, ap);
302     va_end(ap);
303 }
304
305 /* Trace 'bool' return-values */
306 NCURSES_EXPORT(NCURSES_BOOL)
307 _nc_retrace_bool(int code)
308 {
309     T((T_RETURN("%s"), code ? "TRUE" : "FALSE"));
310     return code;
311 }
312
313 /* Trace 'char' return-values */
314 NCURSES_EXPORT(char)
315 _nc_retrace_char(int code)
316 {
317     T((T_RETURN("%c"), code));
318     return (char) code;
319 }
320
321 /* Trace 'int' return-values */
322 NCURSES_EXPORT(int)
323 _nc_retrace_int(int code)
324 {
325     T((T_RETURN("%d"), code));
326     return code;
327 }
328
329 /* Trace 'unsigned' return-values */
330 NCURSES_EXPORT(unsigned)
331 _nc_retrace_unsigned(unsigned code)
332 {
333     T((T_RETURN("%#x"), code));
334     return code;
335 }
336
337 /* Trace 'char*' return-values */
338 NCURSES_EXPORT(char *)
339 _nc_retrace_ptr(char *code)
340 {
341     T((T_RETURN("%s"), _nc_visbuf(code)));
342     return code;
343 }
344
345 /* Trace 'const char*' return-values */
346 NCURSES_EXPORT(const char *)
347 _nc_retrace_cptr(const char *code)
348 {
349     T((T_RETURN("%s"), _nc_visbuf(code)));
350     return code;
351 }
352
353 /* Trace 'NCURSES_CONST void*' return-values */
354 NCURSES_EXPORT(NCURSES_CONST void *)
355 _nc_retrace_cvoid_ptr(NCURSES_CONST void *code)
356 {
357     T((T_RETURN("%p"), code));
358     return code;
359 }
360
361 /* Trace 'void*' return-values */
362 NCURSES_EXPORT(void *)
363 _nc_retrace_void_ptr(void *code)
364 {
365     T((T_RETURN("%p"), code));
366     return code;
367 }
368
369 /* Trace 'SCREEN *' return-values */
370 NCURSES_EXPORT(SCREEN *)
371 _nc_retrace_sp(SCREEN *code)
372 {
373     T((T_RETURN("%p"), (void *) code));
374     return code;
375 }
376
377 /* Trace 'WINDOW *' return-values */
378 NCURSES_EXPORT(WINDOW *)
379 _nc_retrace_win(WINDOW *code)
380 {
381     T((T_RETURN("%p"), (void *) code));
382     return code;
383 }
384
385 NCURSES_EXPORT(char *)
386 _nc_fmt_funcptr(char *target, const char *source, size_t size)
387 {
388     size_t n;
389     char *dst = target;
390     bool leading = TRUE;
391
392     union {
393         int value;
394         char bytes[sizeof(int)];
395     } byteorder;
396
397     byteorder.value = 0x1234;
398
399     *dst++ = '0';
400     *dst++ = 'x';
401
402     for (n = 0; n < size; ++n) {
403         unsigned ch = ((byteorder.bytes[0] == 0x34)
404                        ? UChar(source[size - n - 1])
405                        : UChar(source[n]));
406         if (ch != 0 || (n + 1) >= size)
407             leading = FALSE;
408         if (!leading) {
409             _nc_SPRINTF(dst, _nc_SLIMIT(TR_FUNC_LEN - (size_t) (dst - target))
410                         "%02x", ch & 0xff);
411             dst += 2;
412         }
413     }
414     *dst = '\0';
415     return target;
416 }
417
418 #if USE_REENTRANT
419 /*
420  * Check if the given trace-mask is enabled.
421  *
422  * This function may be called from within one of the functions that fills
423  * in parameters for _tracef(), but in that case we do not want to lock the
424  * mutex, since it is already locked.
425  */
426 NCURSES_EXPORT(int)
427 _nc_use_tracef(unsigned mask)
428 {
429     bool result = FALSE;
430
431     _nc_lock_global(tst_tracef);
432     if (!MyNested++) {
433         if ((result = (_nc_tracing & (mask))) != 0
434             && _nc_try_global(tracef) == 0) {
435             /* we will call _nc_locked_tracef(), no nesting so far */
436         } else {
437             /* we will not call _nc_locked_tracef() */
438             MyNested = 0;
439         }
440     } else {
441         /* we may call _nc_locked_tracef(), but with nested_tracef > 0 */
442         result = (_nc_tracing & (mask));
443     }
444     _nc_unlock_global(tst_tracef);
445     return result;
446 }
447
448 /*
449  * We call this if _nc_use_tracef() returns true, which means we must unlock
450  * the tracef mutex.
451  */
452 NCURSES_EXPORT(void)
453 _nc_locked_tracef(const char *fmt, ...)
454 {
455     va_list ap;
456
457     va_start(ap, fmt);
458     _nc_va_tracef(fmt, ap);
459     va_end(ap);
460
461     if (--(MyNested) == 0) {
462         _nc_unlock_global(tracef);
463     }
464 }
465 #endif /* USE_REENTRANT */
466
467 #endif /* TRACE */