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