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