• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2000 Wim Taymans <wtay@chello.be>
4  *                    2003 Benjamin Otte <in7y118@public.uni-hamburg.de>
5  * Copyright (C) 2008-2009 Tim-Philipp Müller <tim centricular net>
6  *
7  * gstinfo.c: debugging functions
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24 
25 /**
26  * SECTION:gstinfo
27  * @title: GstInfo
28  * @short_description: Debugging and logging facilities
29  * @see_also: #gst-running for command line parameters
30  * and environment variables that affect the debugging output.
31  *
32  * GStreamer's debugging subsystem is an easy way to get information about what
33  * the application is doing.  It is not meant for programming errors. Use GLib
34  * methods (g_warning and friends) for that.
35  *
36  * The debugging subsystem works only after GStreamer has been initialized
37  * - for example by calling gst_init().
38  *
39  * The debugging subsystem is used to log informational messages while the
40  * application runs.  Each messages has some properties attached to it. Among
41  * these properties are the debugging category, the severity (called "level"
42  * here) and an optional #GObject it belongs to. Each of these messages is sent
43  * to all registered debugging handlers, which then handle the messages.
44  * GStreamer attaches a default handler on startup, which outputs requested
45  * messages to stderr.
46  *
47  * Messages are output by using shortcut macros like #GST_DEBUG,
48  * #GST_CAT_ERROR_OBJECT or similar. These all expand to calling gst_debug_log()
49  * with the right parameters.
50  * The only thing a developer will probably want to do is define his own
51  * categories. This is easily done with 3 lines. At the top of your code,
52  * declare
53  * the variables and set the default category.
54  * |[<!-- language="C" -->
55  *   GST_DEBUG_CATEGORY_STATIC (my_category);  // define category (statically)
56  *   #define GST_CAT_DEFAULT my_category       // set as default
57  * ]|
58  * After that you only need to initialize the category.
59  * |[<!-- language="C" -->
60  *   GST_DEBUG_CATEGORY_INIT (my_category, "my category",
61  *                            0, "This is my very own");
62  * ]|
63  * Initialization must be done before the category is used first.
64  * Plugins do this
65  * in their plugin_init function, libraries and applications should do that
66  * during their initialization.
67  *
68  * The whole debugging subsystem can be disabled at build time with passing the
69  * --disable-gst-debug switch to configure. If this is done, every function,
70  * macro and even structs described in this file evaluate to default values or
71  * nothing at all.
72  * So don't take addresses of these functions or use other tricks.
73  * If you must do that for some reason, there is still an option.
74  * If the debugging
75  * subsystem was compiled out, GST_DISABLE_GST_DEBUG is defined in
76  * <gst/gst.h>,
77  * so you can check that before doing your trick.
78  * Disabling the debugging subsystem will give you a slight (read: unnoticeable)
79  * speed increase and will reduce the size of your compiled code. The GStreamer
80  * library itself becomes around 10% smaller.
81  *
82  * Please note that there are naming conventions for the names of debugging
83  * categories. These are explained at GST_DEBUG_CATEGORY_INIT().
84  */
85 
86 #define GST_INFO_C
87 #include "gst_private.h"
88 #include "gstinfo.h"
89 
90 #undef gst_debug_remove_log_function
91 #undef gst_debug_add_log_function
92 
93 #ifndef GST_DISABLE_GST_DEBUG
94 #ifdef HAVE_DLFCN_H
95 #  include <dlfcn.h>
96 #endif
97 #include <stdio.h>              /* fprintf */
98 #include <glib/gstdio.h>
99 #include <errno.h>
100 #ifdef HAVE_UNISTD_H
101 #  include <unistd.h>           /* getpid on UNIX */
102 #endif
103 #ifdef HAVE_PROCESS_H
104 #  include <process.h>          /* getpid on win32 */
105 #endif
106 #include <string.h>             /* G_VA_COPY */
107 #ifdef G_OS_WIN32
108 #  define WIN32_LEAN_AND_MEAN   /* prevents from including too many things */
109 #  include <windows.h>          /* GetStdHandle, windows console */
110 #endif
111 
112 #include "gst_private.h"
113 #include "gstutils.h"
114 #include "gstquark.h"
115 #include "gstsegment.h"
116 #include "gstvalue.h"
117 #include "gstcapsfeatures.h"
118 
119 #ifdef HAVE_VALGRIND_VALGRIND_H
120 #  include <valgrind/valgrind.h>
121 #endif
122 #include <glib/gprintf.h>       /* g_sprintf */
123 
124 /* our own printf implementation with custom extensions to %p for caps etc. */
125 #include "printf/printf.h"
126 #include "printf/printf-extension.h"
127 
128 static char *gst_info_printf_pointer_extension_func (const char *format,
129     void *ptr);
130 #else /* GST_DISABLE_GST_DEBUG */
131 
132 #include <glib/gprintf.h>
133 #endif /* !GST_DISABLE_GST_DEBUG */
134 
135 #ifdef HAVE_UNWIND
136 /* No need for remote debugging so turn on the 'local only' optimizations in
137  * libunwind */
138 #define UNW_LOCAL_ONLY
139 
140 #include <libunwind.h>
141 #include <stdio.h>
142 #include <stdlib.h>
143 #include <string.h>
144 #include <stdarg.h>
145 #include <unistd.h>
146 #include <errno.h>
147 
148 #ifdef HAVE_DW
149 #include <elfutils/libdwfl.h>
150 static Dwfl *_global_dwfl = NULL;
151 static GMutex _dwfl_mutex;
152 
153 #define GST_DWFL_LOCK() g_mutex_lock(&_dwfl_mutex);
154 #define GST_DWFL_UNLOCK() g_mutex_unlock(&_dwfl_mutex);
155 
156 static Dwfl *
get_global_dwfl(void)157 get_global_dwfl (void)
158 {
159   if (g_once_init_enter (&_global_dwfl)) {
160     static Dwfl_Callbacks callbacks = {
161       .find_elf = dwfl_linux_proc_find_elf,
162       .find_debuginfo = dwfl_standard_find_debuginfo,
163     };
164     Dwfl *_dwfl = dwfl_begin (&callbacks);
165     g_mutex_init (&_dwfl_mutex);
166     g_once_init_leave (&_global_dwfl, _dwfl);
167   }
168 
169   return _global_dwfl;
170 }
171 
172 #endif /* HAVE_DW */
173 #endif /* HAVE_UNWIND */
174 
175 #ifdef HAVE_BACKTRACE
176 #include <execinfo.h>
177 #define BT_BUF_SIZE 100
178 #endif /* HAVE_BACKTRACE */
179 
180 #ifdef HAVE_DBGHELP
181 #include <windows.h>
182 #include <dbghelp.h>
183 #include <tlhelp32.h>
184 #include <gmodule.h>
185 #endif /* HAVE_DBGHELP */
186 
187 #ifdef G_OS_WIN32
188 /* We take a lock in order to
189  * 1) keep colors and content together for a single line
190  * 2) serialise gst_print*() and gst_printerr*() with each other and the debug
191  *    log to keep the debug log colouring from interfering with those and
192  *    to prevent broken output on the windows terminal.
193  * Maybe there is a better way but for now this will do the right
194  * thing. */
195 G_LOCK_DEFINE_STATIC (win_print_mutex);
196 #endif
197 
198 extern gboolean gst_is_initialized (void);
199 
200 /* we want these symbols exported even if debug is disabled, to maintain
201  * ABI compatibility. Unless GST_REMOVE_DISABLED is defined. */
202 #if !defined(GST_DISABLE_GST_DEBUG) || !defined(GST_REMOVE_DISABLED)
203 
204 /* disabled by default, as soon as some threshold is set > NONE,
205  * it becomes enabled. */
206 gboolean _gst_debug_enabled = FALSE;
207 GstDebugLevel _gst_debug_min = GST_LEVEL_NONE;
208 
209 GstDebugCategory *GST_CAT_DEFAULT = NULL;
210 
211 GstDebugCategory *GST_CAT_GST_INIT = NULL;
212 GstDebugCategory *GST_CAT_MEMORY = NULL;
213 GstDebugCategory *GST_CAT_PARENTAGE = NULL;
214 GstDebugCategory *GST_CAT_STATES = NULL;
215 GstDebugCategory *GST_CAT_SCHEDULING = NULL;
216 
217 GstDebugCategory *GST_CAT_BUFFER = NULL;
218 GstDebugCategory *GST_CAT_BUFFER_LIST = NULL;
219 GstDebugCategory *GST_CAT_BUS = NULL;
220 GstDebugCategory *GST_CAT_CAPS = NULL;
221 GstDebugCategory *GST_CAT_CLOCK = NULL;
222 GstDebugCategory *GST_CAT_ELEMENT_PADS = NULL;
223 GstDebugCategory *GST_CAT_PADS = NULL;
224 GstDebugCategory *GST_CAT_PERFORMANCE = NULL;
225 GstDebugCategory *GST_CAT_PIPELINE = NULL;
226 GstDebugCategory *GST_CAT_PLUGIN_LOADING = NULL;
227 GstDebugCategory *GST_CAT_PLUGIN_INFO = NULL;
228 GstDebugCategory *GST_CAT_PROPERTIES = NULL;
229 GstDebugCategory *GST_CAT_NEGOTIATION = NULL;
230 GstDebugCategory *GST_CAT_REFCOUNTING = NULL;
231 GstDebugCategory *GST_CAT_ERROR_SYSTEM = NULL;
232 GstDebugCategory *GST_CAT_EVENT = NULL;
233 GstDebugCategory *GST_CAT_MESSAGE = NULL;
234 GstDebugCategory *GST_CAT_PARAMS = NULL;
235 GstDebugCategory *GST_CAT_CALL_TRACE = NULL;
236 GstDebugCategory *GST_CAT_SIGNAL = NULL;
237 GstDebugCategory *GST_CAT_PROBE = NULL;
238 GstDebugCategory *GST_CAT_REGISTRY = NULL;
239 GstDebugCategory *GST_CAT_QOS = NULL;
240 GstDebugCategory *_priv_GST_CAT_POLL = NULL;
241 GstDebugCategory *GST_CAT_META = NULL;
242 GstDebugCategory *GST_CAT_LOCKING = NULL;
243 GstDebugCategory *GST_CAT_CONTEXT = NULL;
244 GstDebugCategory *_priv_GST_CAT_PROTECTION = NULL;
245 
246 
247 #endif /* !defined(GST_DISABLE_GST_DEBUG) || !defined(GST_REMOVE_DISABLED) */
248 
249 #ifndef GST_DISABLE_GST_DEBUG
250 
251 /* underscore is to prevent conflict with GST_CAT_DEBUG define */
252 GST_DEBUG_CATEGORY_STATIC (_GST_CAT_DEBUG);
253 
254 #if 0
255 #if defined __sgi__
256 #include <rld_interface.h>
257 typedef struct DL_INFO
258 {
259   const char *dli_fname;
260   void *dli_fbase;
261   const char *dli_sname;
262   void *dli_saddr;
263   int dli_version;
264   int dli_reserved1;
265   long dli_reserved[4];
266 }
267 Dl_info;
268 
269 #define _RLD_DLADDR             14
270 int dladdr (void *address, Dl_info * dl);
271 
272 int
273 dladdr (void *address, Dl_info * dl)
274 {
275   void *v;
276 
277   v = _rld_new_interface (_RLD_DLADDR, address, dl);
278   return (int) v;
279 }
280 #endif /* __sgi__ */
281 #endif
282 
283 static void gst_debug_reset_threshold (gpointer category, gpointer unused);
284 static void gst_debug_reset_all_thresholds (void);
285 
286 struct _GstDebugMessage
287 {
288   gchar *message;
289   const gchar *format;
290   va_list arguments;
291 };
292 
293 /* list of all name/level pairs from --gst-debug and GST_DEBUG */
294 static GMutex __level_name_mutex;
295 static GSList *__level_name = NULL;
296 typedef struct
297 {
298   GPatternSpec *pat;
299   GstDebugLevel level;
300 }
301 LevelNameEntry;
302 
303 /* list of all categories */
304 static GMutex __cat_mutex;
305 static GSList *__categories = NULL;
306 
307 static GstDebugCategory *_gst_debug_get_category_locked (const gchar * name);
308 
309 
310 /* all registered debug handlers */
311 typedef struct
312 {
313   GstLogFunction func;
314   gpointer user_data;
315   GDestroyNotify notify;
316 }
317 LogFuncEntry;
318 static GMutex __log_func_mutex;
319 static GSList *__log_functions = NULL;
320 
321 /* whether to add the default log function in gst_init() */
322 static gboolean add_default_log_func = TRUE;
323 
324 #define PRETTY_TAGS_DEFAULT  TRUE
325 static gboolean pretty_tags = PRETTY_TAGS_DEFAULT;
326 
327 static gint G_GNUC_MAY_ALIAS __default_level = GST_LEVEL_DEFAULT;
328 static gint G_GNUC_MAY_ALIAS __use_color = GST_DEBUG_COLOR_MODE_ON;
329 
330 static gchar *
_replace_pattern_in_gst_debug_file_name(gchar * name,const char * token,guint val)331 _replace_pattern_in_gst_debug_file_name (gchar * name, const char *token,
332     guint val)
333 {
334   gchar *token_start;
335   if ((token_start = strstr (name, token))) {
336     gsize token_len = strlen (token);
337     gchar *name_prefix = name;
338     gchar *name_suffix = token_start + token_len;
339     token_start[0] = '\0';
340     name = g_strdup_printf ("%s%u%s", name_prefix, val, name_suffix);
341     g_free (name_prefix);
342   }
343   return name;
344 }
345 
346 static gchar *
_priv_gst_debug_file_name(const gchar * env)347 _priv_gst_debug_file_name (const gchar * env)
348 {
349   gchar *name;
350 
351   name = g_strdup (env);
352   name = _replace_pattern_in_gst_debug_file_name (name, "%p", getpid ());
353   name = _replace_pattern_in_gst_debug_file_name (name, "%r", g_random_int ());
354 
355   return name;
356 }
357 
358 /* Initialize the debugging system */
359 void
_priv_gst_debug_init(void)360 _priv_gst_debug_init (void)
361 {
362   const gchar *env;
363   FILE *log_file;
364 
365   if (add_default_log_func) {
366     env = g_getenv ("GST_DEBUG_FILE");
367     if (env != NULL && *env != '\0') {
368       if (strcmp (env, "-") == 0) {
369         log_file = stdout;
370       } else {
371         gchar *name = _priv_gst_debug_file_name (env);
372         log_file = g_fopen (name, "w");
373         g_free (name);
374         if (log_file == NULL) {
375           g_printerr ("Could not open log file '%s' for writing: %s\n", env,
376               g_strerror (errno));
377           log_file = stderr;
378         }
379       }
380     } else {
381       log_file = stderr;
382     }
383 
384     gst_debug_add_log_function (gst_debug_log_default, log_file, NULL);
385   }
386 
387   __gst_printf_pointer_extension_set_func
388       (gst_info_printf_pointer_extension_func);
389 
390   /* do NOT use a single debug function before this line has been run */
391   GST_CAT_DEFAULT = _gst_debug_category_new ("default",
392       GST_DEBUG_UNDERLINE, NULL);
393   _GST_CAT_DEBUG = _gst_debug_category_new ("GST_DEBUG",
394       GST_DEBUG_BOLD | GST_DEBUG_FG_YELLOW, "debugging subsystem");
395 
396   /* FIXME: add descriptions here */
397   GST_CAT_GST_INIT = _gst_debug_category_new ("GST_INIT",
398       GST_DEBUG_BOLD | GST_DEBUG_FG_RED, NULL);
399   GST_CAT_MEMORY = _gst_debug_category_new ("GST_MEMORY",
400       GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, "memory");
401   GST_CAT_PARENTAGE = _gst_debug_category_new ("GST_PARENTAGE",
402       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
403   GST_CAT_STATES = _gst_debug_category_new ("GST_STATES",
404       GST_DEBUG_BOLD | GST_DEBUG_FG_RED, NULL);
405   GST_CAT_SCHEDULING = _gst_debug_category_new ("GST_SCHEDULING",
406       GST_DEBUG_BOLD | GST_DEBUG_FG_MAGENTA, NULL);
407   GST_CAT_BUFFER = _gst_debug_category_new ("GST_BUFFER",
408       GST_DEBUG_BOLD | GST_DEBUG_BG_GREEN, NULL);
409   GST_CAT_BUFFER_LIST = _gst_debug_category_new ("GST_BUFFER_LIST",
410       GST_DEBUG_BOLD | GST_DEBUG_BG_GREEN, NULL);
411   GST_CAT_BUS = _gst_debug_category_new ("GST_BUS", GST_DEBUG_BG_YELLOW, NULL);
412   GST_CAT_CAPS = _gst_debug_category_new ("GST_CAPS",
413       GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
414   GST_CAT_CLOCK = _gst_debug_category_new ("GST_CLOCK",
415       GST_DEBUG_BOLD | GST_DEBUG_FG_YELLOW, NULL);
416   GST_CAT_ELEMENT_PADS = _gst_debug_category_new ("GST_ELEMENT_PADS",
417       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
418   GST_CAT_PADS = _gst_debug_category_new ("GST_PADS",
419       GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_BLUE, NULL);
420   GST_CAT_PERFORMANCE = _gst_debug_category_new ("GST_PERFORMANCE",
421       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
422   GST_CAT_PIPELINE = _gst_debug_category_new ("GST_PIPELINE",
423       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
424   GST_CAT_PLUGIN_LOADING = _gst_debug_category_new ("GST_PLUGIN_LOADING",
425       GST_DEBUG_BOLD | GST_DEBUG_FG_CYAN, NULL);
426   GST_CAT_PLUGIN_INFO = _gst_debug_category_new ("GST_PLUGIN_INFO",
427       GST_DEBUG_BOLD | GST_DEBUG_FG_CYAN, NULL);
428   GST_CAT_PROPERTIES = _gst_debug_category_new ("GST_PROPERTIES",
429       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_BLUE, NULL);
430   GST_CAT_NEGOTIATION = _gst_debug_category_new ("GST_NEGOTIATION",
431       GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
432   GST_CAT_REFCOUNTING = _gst_debug_category_new ("GST_REFCOUNTING",
433       GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_BLUE, NULL);
434   GST_CAT_ERROR_SYSTEM = _gst_debug_category_new ("GST_ERROR_SYSTEM",
435       GST_DEBUG_BOLD | GST_DEBUG_FG_RED | GST_DEBUG_BG_WHITE, NULL);
436 
437   GST_CAT_EVENT = _gst_debug_category_new ("GST_EVENT",
438       GST_DEBUG_BOLD | GST_DEBUG_FG_BLUE, NULL);
439   GST_CAT_MESSAGE = _gst_debug_category_new ("GST_MESSAGE",
440       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
441   GST_CAT_PARAMS = _gst_debug_category_new ("GST_PARAMS",
442       GST_DEBUG_BOLD | GST_DEBUG_FG_BLACK | GST_DEBUG_BG_YELLOW, NULL);
443   GST_CAT_CALL_TRACE = _gst_debug_category_new ("GST_CALL_TRACE",
444       GST_DEBUG_BOLD, NULL);
445   GST_CAT_SIGNAL = _gst_debug_category_new ("GST_SIGNAL",
446       GST_DEBUG_BOLD | GST_DEBUG_FG_WHITE | GST_DEBUG_BG_RED, NULL);
447   GST_CAT_PROBE = _gst_debug_category_new ("GST_PROBE",
448       GST_DEBUG_BOLD | GST_DEBUG_FG_GREEN, "pad probes");
449   GST_CAT_REGISTRY = _gst_debug_category_new ("GST_REGISTRY", 0, "registry");
450   GST_CAT_QOS = _gst_debug_category_new ("GST_QOS", 0, "QoS");
451   _priv_GST_CAT_POLL = _gst_debug_category_new ("GST_POLL", 0, "poll");
452   GST_CAT_META = _gst_debug_category_new ("GST_META", 0, "meta");
453   GST_CAT_LOCKING = _gst_debug_category_new ("GST_LOCKING", 0, "locking");
454   GST_CAT_CONTEXT = _gst_debug_category_new ("GST_CONTEXT", 0, NULL);
455   _priv_GST_CAT_PROTECTION =
456       _gst_debug_category_new ("GST_PROTECTION", 0, "protection");
457 
458   env = g_getenv ("GST_DEBUG_OPTIONS");
459   if (env != NULL) {
460     if (strstr (env, "full_tags") || strstr (env, "full-tags"))
461       pretty_tags = FALSE;
462     else if (strstr (env, "pretty_tags") || strstr (env, "pretty-tags"))
463       pretty_tags = TRUE;
464   }
465 
466   if (g_getenv ("GST_DEBUG_NO_COLOR") != NULL)
467     gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_OFF);
468   env = g_getenv ("GST_DEBUG_COLOR_MODE");
469   if (env)
470     gst_debug_set_color_mode_from_string (env);
471 
472   env = g_getenv ("GST_DEBUG");
473   if (env)
474     gst_debug_set_threshold_from_string (env, FALSE);
475 }
476 
477 /* we can't do this further above, because we initialize the GST_CAT_DEFAULT struct */
478 #define GST_CAT_DEFAULT _GST_CAT_DEBUG
479 
480 /**
481  * gst_debug_log:
482  * @category: category to log
483  * @level: level of the message is in
484  * @file: the file that emitted the message, usually the __FILE__ identifier
485  * @function: the function that emitted the message
486  * @line: the line from that the message was emitted, usually __LINE__
487  * @object: (transfer none) (allow-none): the object this message relates to,
488  *     or %NULL if none
489  * @format: a printf style format string
490  * @...: optional arguments for the format
491  *
492  * Logs the given message using the currently registered debugging handlers.
493  */
494 void
gst_debug_log(GstDebugCategory * category,GstDebugLevel level,const gchar * file,const gchar * function,gint line,GObject * object,const gchar * format,...)495 gst_debug_log (GstDebugCategory * category, GstDebugLevel level,
496     const gchar * file, const gchar * function, gint line,
497     GObject * object, const gchar * format, ...)
498 {
499   va_list var_args;
500 
501   va_start (var_args, format);
502   gst_debug_log_valist (category, level, file, function, line, object, format,
503       var_args);
504   va_end (var_args);
505 }
506 
507 /* based on g_basename(), which we can't use because it was deprecated */
508 static inline const gchar *
gst_path_basename(const gchar * file_name)509 gst_path_basename (const gchar * file_name)
510 {
511   register const gchar *base;
512 
513   base = strrchr (file_name, G_DIR_SEPARATOR);
514 
515   {
516     const gchar *q = strrchr (file_name, '/');
517     if (base == NULL || (q != NULL && q > base))
518       base = q;
519   }
520 
521   if (base)
522     return base + 1;
523 
524   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
525     return file_name + 2;
526 
527   return file_name;
528 }
529 
530 /**
531  * gst_debug_log_valist:
532  * @category: category to log
533  * @level: level of the message is in
534  * @file: the file that emitted the message, usually the __FILE__ identifier
535  * @function: the function that emitted the message
536  * @line: the line from that the message was emitted, usually __LINE__
537  * @object: (transfer none) (allow-none): the object this message relates to,
538  *     or %NULL if none
539  * @format: a printf style format string
540  * @args: optional arguments for the format
541  *
542  * Logs the given message using the currently registered debugging handlers.
543  */
544 void
gst_debug_log_valist(GstDebugCategory * category,GstDebugLevel level,const gchar * file,const gchar * function,gint line,GObject * object,const gchar * format,va_list args)545 gst_debug_log_valist (GstDebugCategory * category, GstDebugLevel level,
546     const gchar * file, const gchar * function, gint line,
547     GObject * object, const gchar * format, va_list args)
548 {
549   GstDebugMessage message;
550   LogFuncEntry *entry;
551   GSList *handler;
552 
553   g_return_if_fail (category != NULL);
554 
555 #ifdef GST_ENABLE_EXTRA_CHECKS
556   g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
557 #endif
558 
559   if (level > gst_debug_category_get_threshold (category))
560     return;
561 
562   g_return_if_fail (file != NULL);
563   g_return_if_fail (function != NULL);
564   g_return_if_fail (format != NULL);
565 
566   message.message = NULL;
567   message.format = format;
568   G_VA_COPY (message.arguments, args);
569 
570   handler = __log_functions;
571   while (handler) {
572     entry = handler->data;
573     handler = g_slist_next (handler);
574     entry->func (category, level, file, function, line, object, &message,
575         entry->user_data);
576   }
577   g_free (message.message);
578   va_end (message.arguments);
579 }
580 
581 /**
582  * gst_debug_log_literal:
583  * @category: category to log
584  * @level: level of the message is in
585  * @file: the file that emitted the message, usually the __FILE__ identifier
586  * @function: the function that emitted the message
587  * @line: the line from that the message was emitted, usually __LINE__
588  * @object: (transfer none) (allow-none): the object this message relates to,
589  *     or %NULL if none
590  * @message_string: a message string
591  *
592  * Logs the given message using the currently registered debugging handlers.
593  *
594  * Since: 1.20
595  */
596 void
gst_debug_log_literal(GstDebugCategory * category,GstDebugLevel level,const gchar * file,const gchar * function,gint line,GObject * object,const gchar * message_string)597 gst_debug_log_literal (GstDebugCategory * category, GstDebugLevel level,
598     const gchar * file, const gchar * function, gint line,
599     GObject * object, const gchar * message_string)
600 {
601   GstDebugMessage message;
602   LogFuncEntry *entry;
603   GSList *handler;
604 
605   g_return_if_fail (category != NULL);
606 
607 #ifdef GST_ENABLE_EXTRA_CHECKS
608   g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
609 #endif
610 
611   if (level > gst_debug_category_get_threshold (category))
612     return;
613 
614   g_return_if_fail (file != NULL);
615   g_return_if_fail (function != NULL);
616   g_return_if_fail (message_string != NULL);
617 
618   message.message = (gchar *) message_string;
619 
620   handler = __log_functions;
621   while (handler) {
622     entry = handler->data;
623     handler = g_slist_next (handler);
624     entry->func (category, level, file, function, line, object, &message,
625         entry->user_data);
626   }
627 }
628 
629 /**
630  * gst_debug_message_get:
631  * @message: a debug message
632  *
633  * Gets the string representation of a #GstDebugMessage. This function is used
634  * in debug handlers to extract the message.
635  *
636  * Returns: (nullable): the string representation of a #GstDebugMessage.
637  */
638 const gchar *
gst_debug_message_get(GstDebugMessage * message)639 gst_debug_message_get (GstDebugMessage * message)
640 {
641   if (message->message == NULL) {
642     int len;
643 
644     len = __gst_vasprintf (&message->message, message->format,
645         message->arguments);
646 
647     if (len < 0)
648       message->message = NULL;
649   }
650   return message->message;
651 }
652 
653 #define MAX_BUFFER_DUMP_STRING_LEN  100
654 
655 /* structure_to_pretty_string:
656  * @str: a serialized #GstStructure
657  *
658  * If the serialized structure contains large buffers such as images the hex
659  * representation of those buffers will be shortened so that the string remains
660  * readable.
661  *
662  * Returns: the filtered string
663  */
664 static gchar *
prettify_structure_string(gchar * str)665 prettify_structure_string (gchar * str)
666 {
667   gchar *pos = str, *end;
668 
669   while ((pos = strstr (pos, "(buffer)"))) {
670     guint count = 0;
671 
672     pos += strlen ("(buffer)");
673     for (end = pos; *end != '\0' && *end != ';' && *end != ' '; ++end)
674       ++count;
675     if (count > MAX_BUFFER_DUMP_STRING_LEN) {
676       memcpy (pos + MAX_BUFFER_DUMP_STRING_LEN - 6, "..", 2);
677       memcpy (pos + MAX_BUFFER_DUMP_STRING_LEN - 4, pos + count - 4, 4);
678       memmove (pos + MAX_BUFFER_DUMP_STRING_LEN, pos + count,
679           strlen (pos + count) + 1);
680       pos += MAX_BUFFER_DUMP_STRING_LEN;
681     }
682   }
683 
684   return str;
685 }
686 
687 static inline gchar *
gst_info_structure_to_string(const GstStructure * s)688 gst_info_structure_to_string (const GstStructure * s)
689 {
690   if (G_LIKELY (s)) {
691     gchar *str = gst_structure_to_string (s);
692     if (G_UNLIKELY (pretty_tags && s->name == GST_QUARK (TAGLIST)))
693       return prettify_structure_string (str);
694     else
695       return str;
696   }
697   return NULL;
698 }
699 
700 static inline gchar *
gst_info_describe_buffer(GstBuffer * buffer)701 gst_info_describe_buffer (GstBuffer * buffer)
702 {
703   const gchar *offset_str = "none";
704   const gchar *offset_end_str = "none";
705   gchar offset_buf[32], offset_end_buf[32];
706 
707   if (GST_BUFFER_OFFSET_IS_VALID (buffer)) {
708     g_snprintf (offset_buf, sizeof (offset_buf), "%" G_GUINT64_FORMAT,
709         GST_BUFFER_OFFSET (buffer));
710     offset_str = offset_buf;
711   }
712   if (GST_BUFFER_OFFSET_END_IS_VALID (buffer)) {
713     g_snprintf (offset_end_buf, sizeof (offset_end_buf), "%" G_GUINT64_FORMAT,
714         GST_BUFFER_OFFSET_END (buffer));
715     offset_end_str = offset_end_buf;
716   }
717 
718   return g_strdup_printf ("buffer: %p, pts %" GST_TIME_FORMAT ", dts %"
719       GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT ", size %" G_GSIZE_FORMAT
720       ", offset %s, offset_end %s, flags 0x%x", buffer,
721       GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
722       GST_TIME_ARGS (GST_BUFFER_DTS (buffer)),
723       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)),
724       gst_buffer_get_size (buffer), offset_str, offset_end_str,
725       GST_BUFFER_FLAGS (buffer));
726 }
727 
728 static inline gchar *
gst_info_describe_buffer_list(GstBufferList * list)729 gst_info_describe_buffer_list (GstBufferList * list)
730 {
731   GstClockTime pts = GST_CLOCK_TIME_NONE;
732   GstClockTime dts = GST_CLOCK_TIME_NONE;
733   gsize total_size = 0;
734   guint n, i;
735 
736   n = gst_buffer_list_length (list);
737   for (i = 0; i < n; ++i) {
738     GstBuffer *buf = gst_buffer_list_get (list, i);
739 
740     if (i == 0) {
741       pts = GST_BUFFER_PTS (buf);
742       dts = GST_BUFFER_DTS (buf);
743     }
744 
745     total_size += gst_buffer_get_size (buf);
746   }
747 
748   return g_strdup_printf ("bufferlist: %p, %u buffers, pts %" GST_TIME_FORMAT
749       ", dts %" GST_TIME_FORMAT ", size %" G_GSIZE_FORMAT, list, n,
750       GST_TIME_ARGS (pts), GST_TIME_ARGS (dts), total_size);
751 }
752 
753 static inline gchar *
gst_info_describe_event(GstEvent * event)754 gst_info_describe_event (GstEvent * event)
755 {
756   gchar *s, *ret;
757 
758   s = gst_info_structure_to_string (gst_event_get_structure (event));
759   ret = g_strdup_printf ("%s event: %p, time %" GST_TIME_FORMAT
760       ", seq-num %d, %s", GST_EVENT_TYPE_NAME (event), event,
761       GST_TIME_ARGS (GST_EVENT_TIMESTAMP (event)), GST_EVENT_SEQNUM (event),
762       (s ? s : "(NULL)"));
763   g_free (s);
764   return ret;
765 }
766 
767 static inline gchar *
gst_info_describe_message(GstMessage * message)768 gst_info_describe_message (GstMessage * message)
769 {
770   gchar *s, *ret;
771 
772   s = gst_info_structure_to_string (gst_message_get_structure (message));
773   ret = g_strdup_printf ("%s message: %p, time %" GST_TIME_FORMAT
774       ", seq-num %d, element '%s', %s", GST_MESSAGE_TYPE_NAME (message),
775       message, GST_TIME_ARGS (GST_MESSAGE_TIMESTAMP (message)),
776       GST_MESSAGE_SEQNUM (message),
777       ((message->src) ? GST_ELEMENT_NAME (message->src) : "(NULL)"),
778       (s ? s : "(NULL)"));
779   g_free (s);
780   return ret;
781 }
782 
783 static inline gchar *
gst_info_describe_query(GstQuery * query)784 gst_info_describe_query (GstQuery * query)
785 {
786   gchar *s, *ret;
787 
788   s = gst_info_structure_to_string (gst_query_get_structure (query));
789   ret = g_strdup_printf ("%s query: %p, %s", GST_QUERY_TYPE_NAME (query),
790       query, (s ? s : "(NULL)"));
791   g_free (s);
792   return ret;
793 }
794 
795 static inline gchar *
gst_info_describe_stream(GstStream * stream)796 gst_info_describe_stream (GstStream * stream)
797 {
798   gchar *ret, *caps_str = NULL, *tags_str = NULL;
799   GstCaps *caps;
800   GstTagList *tags;
801 
802   caps = gst_stream_get_caps (stream);
803   if (caps) {
804     caps_str = gst_caps_to_string (caps);
805     gst_caps_unref (caps);
806   }
807 
808   tags = gst_stream_get_tags (stream);
809   if (tags) {
810     tags_str = gst_tag_list_to_string (tags);
811     gst_tag_list_unref (tags);
812   }
813 
814   ret =
815       g_strdup_printf ("stream %s %p, ID %s, flags 0x%x, caps [%s], tags [%s]",
816       gst_stream_type_get_name (gst_stream_get_stream_type (stream)), stream,
817       gst_stream_get_stream_id (stream), gst_stream_get_stream_flags (stream),
818       caps_str ? caps_str : "", tags_str ? tags_str : "");
819 
820   g_free (caps_str);
821   g_free (tags_str);
822 
823   return ret;
824 }
825 
826 static inline gchar *
gst_info_describe_stream_collection(GstStreamCollection * collection)827 gst_info_describe_stream_collection (GstStreamCollection * collection)
828 {
829   gchar *ret;
830   GString *streams_str;
831   guint i;
832 
833   streams_str = g_string_new ("<");
834   for (i = 0; i < gst_stream_collection_get_size (collection); i++) {
835     GstStream *stream = gst_stream_collection_get_stream (collection, i);
836     gchar *s;
837 
838     s = gst_info_describe_stream (stream);
839     g_string_append_printf (streams_str, " %s,", s);
840     g_free (s);
841   }
842   g_string_append (streams_str, " >");
843 
844   ret = g_strdup_printf ("collection %p (%d streams) %s", collection,
845       gst_stream_collection_get_size (collection), streams_str->str);
846 
847   g_string_free (streams_str, TRUE);
848   return ret;
849 }
850 
851 static gchar *
gst_debug_print_object(gpointer ptr)852 gst_debug_print_object (gpointer ptr)
853 {
854   GObject *object = (GObject *) ptr;
855 
856 #ifdef unused
857   /* This is a cute trick to detect unmapped memory, but is unportable,
858    * slow, screws around with madvise, and not actually that useful. */
859   {
860     int ret;
861 
862     ret = madvise ((void *) ((unsigned long) ptr & (~0xfff)), 4096, 0);
863     if (ret == -1 && errno == ENOMEM) {
864       buffer = g_strdup_printf ("%p (unmapped memory)", ptr);
865     }
866   }
867 #endif
868 
869   /* nicely printed object */
870   if (object == NULL) {
871     return g_strdup ("(NULL)");
872   }
873   if (GST_IS_CAPS (ptr)) {
874     return gst_caps_to_string ((const GstCaps *) ptr);
875   }
876   if (GST_IS_STRUCTURE (ptr)) {
877     return gst_info_structure_to_string ((const GstStructure *) ptr);
878   }
879   if (*(GType *) ptr == GST_TYPE_CAPS_FEATURES) {
880     return gst_caps_features_to_string ((const GstCapsFeatures *) ptr);
881   }
882   if (GST_IS_TAG_LIST (ptr)) {
883     gchar *str = gst_tag_list_to_string ((GstTagList *) ptr);
884     if (G_UNLIKELY (pretty_tags))
885       return prettify_structure_string (str);
886     else
887       return str;
888   }
889   if (*(GType *) ptr == GST_TYPE_DATE_TIME) {
890     return __gst_date_time_serialize ((GstDateTime *) ptr, TRUE);
891   }
892   if (GST_IS_BUFFER (ptr)) {
893     return gst_info_describe_buffer (GST_BUFFER_CAST (ptr));
894   }
895   if (GST_IS_BUFFER_LIST (ptr)) {
896     return gst_info_describe_buffer_list (GST_BUFFER_LIST_CAST (ptr));
897   }
898 #ifdef USE_POISONING
899   if (*(guint32 *) ptr == 0xffffffff) {
900     return g_strdup_printf ("<poisoned@%p>", ptr);
901   }
902 #endif
903   if (GST_IS_MESSAGE (object)) {
904     return gst_info_describe_message (GST_MESSAGE_CAST (object));
905   }
906   if (GST_IS_QUERY (object)) {
907     return gst_info_describe_query (GST_QUERY_CAST (object));
908   }
909   if (GST_IS_EVENT (object)) {
910     return gst_info_describe_event (GST_EVENT_CAST (object));
911   }
912   if (GST_IS_CONTEXT (object)) {
913     GstContext *context = GST_CONTEXT_CAST (object);
914     gchar *s, *ret;
915     const gchar *type;
916     const GstStructure *structure;
917 
918     type = gst_context_get_context_type (context);
919     structure = gst_context_get_structure (context);
920 
921     s = gst_info_structure_to_string (structure);
922 
923     ret = g_strdup_printf ("context '%s'='%s'", type, s);
924     g_free (s);
925     return ret;
926   }
927   if (GST_IS_STREAM (object)) {
928     return gst_info_describe_stream (GST_STREAM_CAST (object));
929   }
930   if (GST_IS_STREAM_COLLECTION (object)) {
931     return
932         gst_info_describe_stream_collection (GST_STREAM_COLLECTION_CAST
933         (object));
934   }
935   if (GST_IS_PAD (object) && GST_OBJECT_NAME (object)) {
936     return g_strdup_printf ("<%s:%s>", GST_DEBUG_PAD_NAME (object));
937   }
938   if (GST_IS_OBJECT (object) && GST_OBJECT_NAME (object)) {
939     return g_strdup_printf ("<%s>", GST_OBJECT_NAME (object));
940   }
941   if (G_IS_OBJECT (object)) {
942     return g_strdup_printf ("<%s@%p>", G_OBJECT_TYPE_NAME (object), object);
943   }
944 
945   return g_strdup_printf ("%p", ptr);
946 }
947 
948 static gchar *
gst_debug_print_segment(gpointer ptr)949 gst_debug_print_segment (gpointer ptr)
950 {
951   GstSegment *segment = (GstSegment *) ptr;
952 
953   /* nicely printed segment */
954   if (segment == NULL) {
955     return g_strdup ("(NULL)");
956   }
957 
958   switch (segment->format) {
959     case GST_FORMAT_UNDEFINED:{
960       return g_strdup_printf ("UNDEFINED segment");
961     }
962     case GST_FORMAT_TIME:{
963       return g_strdup_printf ("time segment start=%" GST_TIME_FORMAT
964           ", offset=%" GST_TIME_FORMAT ", stop=%" GST_TIME_FORMAT
965           ", rate=%f, applied_rate=%f" ", flags=0x%02x, time=%" GST_TIME_FORMAT
966           ", base=%" GST_TIME_FORMAT ", position %" GST_TIME_FORMAT
967           ", duration %" GST_TIME_FORMAT, GST_TIME_ARGS (segment->start),
968           GST_TIME_ARGS (segment->offset), GST_TIME_ARGS (segment->stop),
969           segment->rate, segment->applied_rate, (guint) segment->flags,
970           GST_TIME_ARGS (segment->time), GST_TIME_ARGS (segment->base),
971           GST_TIME_ARGS (segment->position), GST_TIME_ARGS (segment->duration));
972     }
973     default:{
974       const gchar *format_name;
975 
976       format_name = gst_format_get_name (segment->format);
977       if (G_UNLIKELY (format_name == NULL))
978         format_name = "(UNKNOWN FORMAT)";
979       return g_strdup_printf ("%s segment start=%" G_GINT64_FORMAT
980           ", offset=%" G_GINT64_FORMAT ", stop=%" G_GINT64_FORMAT
981           ", rate=%f, applied_rate=%f" ", flags=0x%02x, time=%" G_GINT64_FORMAT
982           ", base=%" G_GINT64_FORMAT ", position %" G_GINT64_FORMAT
983           ", duration %" G_GINT64_FORMAT, format_name, segment->start,
984           segment->offset, segment->stop, segment->rate, segment->applied_rate,
985           (guint) segment->flags, segment->time, segment->base,
986           segment->position, segment->duration);
987     }
988   }
989 }
990 
991 static char *
gst_info_printf_pointer_extension_func(const char * format,void * ptr)992 gst_info_printf_pointer_extension_func (const char *format, void *ptr)
993 {
994   char *s = NULL;
995 
996   if (format[0] == 'p' && format[1] == '\a') {
997     switch (format[2]) {
998       case 'A':                /* GST_PTR_FORMAT     */
999         s = gst_debug_print_object (ptr);
1000         break;
1001       case 'B':                /* GST_SEGMENT_FORMAT */
1002         s = gst_debug_print_segment (ptr);
1003         break;
1004       case 'T':                /* GST_TIMEP_FORMAT */
1005         if (ptr)
1006           s = g_strdup_printf ("%" GST_TIME_FORMAT,
1007               GST_TIME_ARGS (*(GstClockTime *) ptr));
1008         break;
1009       case 'S':                /* GST_STIMEP_FORMAT */
1010         if (ptr)
1011           s = g_strdup_printf ("%" GST_STIME_FORMAT,
1012               GST_STIME_ARGS (*(gint64 *) ptr));
1013         break;
1014       case 'a':                /* GST_WRAPPED_PTR_FORMAT */
1015         s = priv_gst_string_take_and_wrap (gst_debug_print_object (ptr));
1016         break;
1017       default:
1018         /* must have been compiled against a newer version with an extension
1019          * we don't known about yet - just ignore and fallback to %p below */
1020         break;
1021     }
1022   }
1023   if (s == NULL)
1024     s = g_strdup_printf ("%p", ptr);
1025 
1026   return s;
1027 }
1028 
1029 /**
1030  * gst_debug_construct_term_color:
1031  * @colorinfo: the color info
1032  *
1033  * Constructs a string that can be used for getting the desired color in color
1034  * terminals.
1035  * You need to free the string after use.
1036  *
1037  * Returns: (transfer full) (type gchar*): a string containing the color
1038  *     definition
1039  */
1040 gchar *
gst_debug_construct_term_color(guint colorinfo)1041 gst_debug_construct_term_color (guint colorinfo)
1042 {
1043   GString *color;
1044 
1045   color = g_string_new ("\033[00");
1046 
1047   if (colorinfo & GST_DEBUG_BOLD) {
1048     g_string_append_len (color, ";01", 3);
1049   }
1050   if (colorinfo & GST_DEBUG_UNDERLINE) {
1051     g_string_append_len (color, ";04", 3);
1052   }
1053   if (colorinfo & GST_DEBUG_FG_MASK) {
1054     g_string_append_printf (color, ";3%1d", colorinfo & GST_DEBUG_FG_MASK);
1055   }
1056   if (colorinfo & GST_DEBUG_BG_MASK) {
1057     g_string_append_printf (color, ";4%1d",
1058         (colorinfo & GST_DEBUG_BG_MASK) >> 4);
1059   }
1060   g_string_append_c (color, 'm');
1061 
1062   return g_string_free (color, FALSE);
1063 }
1064 
1065 /**
1066  * gst_debug_construct_win_color:
1067  * @colorinfo: the color info
1068  *
1069  * Constructs an integer that can be used for getting the desired color in
1070  * windows' terminals (cmd.exe). As there is no mean to underline, we simply
1071  * ignore this attribute.
1072  *
1073  * This function returns 0 on non-windows machines.
1074  *
1075  * Returns: an integer containing the color definition
1076  */
1077 gint
gst_debug_construct_win_color(guint colorinfo)1078 gst_debug_construct_win_color (guint colorinfo)
1079 {
1080   gint color = 0;
1081 #ifdef G_OS_WIN32
1082   static const guchar ansi_to_win_fg[8] = {
1083     0,                          /* black   */
1084     FOREGROUND_RED,             /* red     */
1085     FOREGROUND_GREEN,           /* green   */
1086     FOREGROUND_RED | FOREGROUND_GREEN,  /* yellow  */
1087     FOREGROUND_BLUE,            /* blue    */
1088     FOREGROUND_RED | FOREGROUND_BLUE,   /* magenta */
1089     FOREGROUND_GREEN | FOREGROUND_BLUE, /* cyan    */
1090     FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE /* white   */
1091   };
1092   static const guchar ansi_to_win_bg[8] = {
1093     0,
1094     BACKGROUND_RED,
1095     BACKGROUND_GREEN,
1096     BACKGROUND_RED | BACKGROUND_GREEN,
1097     BACKGROUND_BLUE,
1098     BACKGROUND_RED | BACKGROUND_BLUE,
1099     BACKGROUND_GREEN | FOREGROUND_BLUE,
1100     BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE
1101   };
1102 
1103   /* we draw black as white, as cmd.exe can only have black bg */
1104   if ((colorinfo & (GST_DEBUG_FG_MASK | GST_DEBUG_BG_MASK)) == 0) {
1105     color = ansi_to_win_fg[7];
1106   }
1107   if (colorinfo & GST_DEBUG_UNDERLINE) {
1108     color |= BACKGROUND_INTENSITY;
1109   }
1110   if (colorinfo & GST_DEBUG_BOLD) {
1111     color |= FOREGROUND_INTENSITY;
1112   }
1113   if (colorinfo & GST_DEBUG_FG_MASK) {
1114     color |= ansi_to_win_fg[colorinfo & GST_DEBUG_FG_MASK];
1115   }
1116   if (colorinfo & GST_DEBUG_BG_MASK) {
1117     color |= ansi_to_win_bg[(colorinfo & GST_DEBUG_BG_MASK) >> 4];
1118   }
1119 #endif
1120   return color;
1121 }
1122 
1123 /* width of %p varies depending on actual value of pointer, which can make
1124  * output unevenly aligned if multiple threads are involved, hence the %14p
1125  * (should really be %18p, but %14p seems a good compromise between too many
1126  * white spaces and likely unalignment on my system) */
1127 #if defined (GLIB_SIZEOF_VOID_P) && GLIB_SIZEOF_VOID_P == 8
1128 #define PTR_FMT "%14p"
1129 #else
1130 #define PTR_FMT "%10p"
1131 #endif
1132 #define PID_FMT "%5d"
1133 #define CAT_FMT "%20s %s:%d:%s:%s"
1134 #define NOCOLOR_PRINT_FMT " "PID_FMT" "PTR_FMT" %s "CAT_FMT" %s\n"
1135 
1136 #ifdef G_OS_WIN32
1137 static const guchar levelcolormap_w32[GST_LEVEL_COUNT] = {
1138   /* GST_LEVEL_NONE */
1139   FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1140   /* GST_LEVEL_ERROR */
1141   FOREGROUND_RED | FOREGROUND_INTENSITY,
1142   /* GST_LEVEL_WARNING */
1143   FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
1144   /* GST_LEVEL_INFO */
1145   FOREGROUND_GREEN | FOREGROUND_INTENSITY,
1146   /* GST_LEVEL_DEBUG */
1147   FOREGROUND_GREEN | FOREGROUND_BLUE,
1148   /* GST_LEVEL_LOG */
1149   FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1150   /* GST_LEVEL_FIXME */
1151   FOREGROUND_RED | FOREGROUND_GREEN,
1152   /* GST_LEVEL_TRACE */
1153   FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
1154   /* placeholder for log level 8 */
1155   0,
1156   /* GST_LEVEL_MEMDUMP */
1157   FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE
1158 };
1159 
1160 static const guchar available_colors[] = {
1161   FOREGROUND_RED, FOREGROUND_GREEN, FOREGROUND_RED | FOREGROUND_GREEN,
1162   FOREGROUND_BLUE, FOREGROUND_RED | FOREGROUND_BLUE,
1163   FOREGROUND_GREEN | FOREGROUND_BLUE,
1164 };
1165 #endif /* G_OS_WIN32 */
1166 static const gchar *levelcolormap[GST_LEVEL_COUNT] = {
1167   "\033[37m",                   /* GST_LEVEL_NONE */
1168   "\033[31;01m",                /* GST_LEVEL_ERROR */
1169   "\033[33;01m",                /* GST_LEVEL_WARNING */
1170   "\033[32;01m",                /* GST_LEVEL_INFO */
1171   "\033[36m",                   /* GST_LEVEL_DEBUG */
1172   "\033[37m",                   /* GST_LEVEL_LOG */
1173   "\033[33;01m",                /* GST_LEVEL_FIXME */
1174   "\033[37m",                   /* GST_LEVEL_TRACE */
1175   "\033[37m",                   /* placeholder for log level 8 */
1176   "\033[37m"                    /* GST_LEVEL_MEMDUMP */
1177 };
1178 
1179 static void
_gst_debug_log_preamble(GstDebugMessage * message,GObject * object,const gchar ** file,const gchar ** message_str,gchar ** obj_str,GstClockTime * elapsed)1180 _gst_debug_log_preamble (GstDebugMessage * message, GObject * object,
1181     const gchar ** file, const gchar ** message_str, gchar ** obj_str,
1182     GstClockTime * elapsed)
1183 {
1184   gchar c;
1185 
1186   /* Get message string first because printing it might call into our custom
1187    * printf format extension mechanism which in turn might log something, e.g.
1188    * from inside gst_structure_to_string() when something can't be serialised.
1189    * This means we either need to do this outside of any critical section or
1190    * use a recursive lock instead. As we always need the message string in all
1191    * code paths, we might just as well get it here first thing and outside of
1192    * the win_print_mutex critical section. */
1193   *message_str = gst_debug_message_get (message);
1194 
1195   /* __FILE__ might be a file name or an absolute path or a
1196    * relative path, irrespective of the exact compiler used,
1197    * in which case we want to shorten it to the filename for
1198    * readability. */
1199   c = (*file)[0];
1200   if (c == '.' || c == '/' || c == '\\' || (c != '\0' && (*file)[1] == ':')) {
1201     *file = gst_path_basename (*file);
1202   }
1203 
1204   if (object) {
1205     *obj_str = gst_debug_print_object (object);
1206   } else {
1207     *obj_str = (gchar *) "";
1208   }
1209 
1210   *elapsed = GST_CLOCK_DIFF (_priv_gst_start_time, gst_util_get_timestamp ());
1211 }
1212 
1213 /**
1214  * gst_debug_log_get_line:
1215  * @category: category to log
1216  * @level: level of the message
1217  * @file: the file that emitted the message, usually the __FILE__ identifier
1218  * @function: the function that emitted the message
1219  * @line: the line from that the message was emitted, usually __LINE__
1220  * @object: (transfer none) (allow-none): the object this message relates to,
1221  *     or %NULL if none
1222  * @message: the actual message
1223  *
1224  * Returns the string representation for the specified debug log message
1225  * formatted in the same way as gst_debug_log_default() (the default handler),
1226  * without color. The purpose is to make it easy for custom log output
1227  * handlers to get a log output that is identical to what the default handler
1228  * would write out.
1229  *
1230  * Since: 1.18
1231  */
1232 gchar *
gst_debug_log_get_line(GstDebugCategory * category,GstDebugLevel level,const gchar * file,const gchar * function,gint line,GObject * object,GstDebugMessage * message)1233 gst_debug_log_get_line (GstDebugCategory * category, GstDebugLevel level,
1234     const gchar * file, const gchar * function, gint line,
1235     GObject * object, GstDebugMessage * message)
1236 {
1237   GstClockTime elapsed;
1238   gchar *ret, *obj_str = NULL;
1239   const gchar *message_str;
1240 
1241 #ifdef GST_ENABLE_EXTRA_CHECKS
1242   g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
1243 #endif
1244 
1245   _gst_debug_log_preamble (message, object, &file, &message_str, &obj_str,
1246       &elapsed);
1247 
1248   ret = g_strdup_printf ("%" GST_TIME_FORMAT NOCOLOR_PRINT_FMT,
1249       GST_TIME_ARGS (elapsed), getpid (), g_thread_self (),
1250       gst_debug_level_get_name (level), gst_debug_category_get_name
1251       (category), file, line, function, obj_str, message_str);
1252 
1253   if (object != NULL)
1254     g_free (obj_str);
1255   return ret;
1256 }
1257 
1258 #ifdef G_OS_WIN32
1259 static void
_gst_debug_fprintf(FILE * file,const gchar * format,...)1260 _gst_debug_fprintf (FILE * file, const gchar * format, ...)
1261 {
1262   va_list args;
1263   gchar *str = NULL;
1264   gint length;
1265 
1266   va_start (args, format);
1267   length = gst_info_vasprintf (&str, format, args);
1268   va_end (args);
1269 
1270   if (length == 0 || !str)
1271     return;
1272 
1273   /* Even if it's valid UTF-8 string, console might print broken string
1274    * depending on codepage and the content of the given string.
1275    * Fortunately, g_print* family will take care of the Windows' codepage
1276    * specific behavior.
1277    */
1278   if (file == stderr) {
1279     g_printerr ("%s", str);
1280   } else if (file == stdout) {
1281     g_print ("%s", str);
1282   } else {
1283     /* We are writing to file. Text editors/viewers should be able to
1284      * decode valid UTF-8 string regardless of codepage setting */
1285     fwrite (str, 1, length, file);
1286 
1287     /* FIXME: fflush here might be redundant if setvbuf works as expected */
1288     fflush (file);
1289   }
1290 
1291   g_free (str);
1292 }
1293 #endif
1294 
1295 /**
1296  * gst_debug_log_default:
1297  * @category: category to log
1298  * @level: level of the message
1299  * @file: the file that emitted the message, usually the __FILE__ identifier
1300  * @function: the function that emitted the message
1301  * @line: the line from that the message was emitted, usually __LINE__
1302  * @message: the actual message
1303  * @object: (transfer none) (allow-none): the object this message relates to,
1304  *     or %NULL if none
1305  * @user_data: the FILE* to log to
1306  *
1307  * The default logging handler used by GStreamer. Logging functions get called
1308  * whenever a macro like GST_DEBUG or similar is used. By default this function
1309  * is setup to output the message and additional info to stderr (or the log file
1310  * specified via the GST_DEBUG_FILE environment variable) as received via
1311  * @user_data.
1312  *
1313  * You can add other handlers by using gst_debug_add_log_function().
1314  * And you can remove this handler by calling
1315  * gst_debug_remove_log_function(gst_debug_log_default);
1316  */
1317 void
gst_debug_log_default(GstDebugCategory * category,GstDebugLevel level,const gchar * file,const gchar * function,gint line,GObject * object,GstDebugMessage * message,gpointer user_data)1318 gst_debug_log_default (GstDebugCategory * category, GstDebugLevel level,
1319     const gchar * file, const gchar * function, gint line,
1320     GObject * object, GstDebugMessage * message, gpointer user_data)
1321 {
1322   gint pid;
1323   GstClockTime elapsed;
1324   gchar *obj = NULL;
1325   GstDebugColorMode color_mode;
1326   const gchar *message_str;
1327   FILE *log_file = user_data ? user_data : stderr;
1328 #ifdef G_OS_WIN32
1329 #define FPRINTF_DEBUG _gst_debug_fprintf
1330 /* _gst_debug_fprintf will do fflush if it's required */
1331 #define FFLUSH_DEBUG(f) ((void)(f))
1332 #else
1333 #define FPRINTF_DEBUG fprintf
1334 #define FFLUSH_DEBUG(f) G_STMT_START { \
1335     fflush (f); \
1336   } G_STMT_END
1337 #endif
1338 
1339 #ifdef GST_ENABLE_EXTRA_CHECKS
1340   g_warn_if_fail (object == NULL || G_IS_OBJECT (object));
1341 #endif
1342 
1343   _gst_debug_log_preamble (message, object, &file, &message_str, &obj,
1344       &elapsed);
1345 
1346   pid = getpid ();
1347   color_mode = gst_debug_get_color_mode ();
1348 
1349   if (color_mode != GST_DEBUG_COLOR_MODE_OFF) {
1350 #ifdef G_OS_WIN32
1351     G_LOCK (win_print_mutex);
1352     if (color_mode == GST_DEBUG_COLOR_MODE_UNIX) {
1353 #endif
1354       /* colors, non-windows */
1355       gchar *color = NULL;
1356       const gchar *clear;
1357       gchar pidcolor[10];
1358       const gchar *levelcolor;
1359 
1360       color = gst_debug_construct_term_color (gst_debug_category_get_color
1361           (category));
1362       clear = "\033[00m";
1363       g_sprintf (pidcolor, "\033[%02dm", pid % 6 + 31);
1364       levelcolor = levelcolormap[level];
1365 
1366 #define PRINT_FMT " %s"PID_FMT"%s "PTR_FMT" %s%s%s %s"CAT_FMT"%s %s\n"
1367       FPRINTF_DEBUG (log_file, "%" GST_TIME_FORMAT PRINT_FMT,
1368           GST_TIME_ARGS (elapsed), pidcolor, pid, clear, g_thread_self (),
1369           levelcolor, gst_debug_level_get_name (level), clear, color,
1370           gst_debug_category_get_name (category), file, line, function, obj,
1371           clear, message_str);
1372       FFLUSH_DEBUG (log_file);
1373 #undef PRINT_FMT
1374       g_free (color);
1375 #ifdef G_OS_WIN32
1376     } else {
1377       /* colors, windows. */
1378       const gint clear = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
1379 #define SET_COLOR(c) G_STMT_START { \
1380   if (log_file == stderr) \
1381     SetConsoleTextAttribute (GetStdHandle (STD_ERROR_HANDLE), (c)); \
1382   } G_STMT_END
1383       /* timestamp */
1384       FPRINTF_DEBUG (log_file, "%" GST_TIME_FORMAT " ",
1385           GST_TIME_ARGS (elapsed));
1386       /* pid */
1387       SET_COLOR (available_colors[pid % G_N_ELEMENTS (available_colors)]);
1388       FPRINTF_DEBUG (log_file, PID_FMT, pid);
1389       /* thread */
1390       SET_COLOR (clear);
1391       FPRINTF_DEBUG (log_file, " " PTR_FMT " ", g_thread_self ());
1392       /* level */
1393       SET_COLOR (levelcolormap_w32[level]);
1394       FPRINTF_DEBUG (log_file, "%s ", gst_debug_level_get_name (level));
1395       /* category */
1396       SET_COLOR (gst_debug_construct_win_color (gst_debug_category_get_color
1397               (category)));
1398       FPRINTF_DEBUG (log_file, CAT_FMT, gst_debug_category_get_name (category),
1399           file, line, function, obj);
1400       /* message */
1401       SET_COLOR (clear);
1402       FPRINTF_DEBUG (log_file, " %s\n", message_str);
1403     }
1404     G_UNLOCK (win_print_mutex);
1405 #endif
1406   } else {
1407     /* no color, all platforms */
1408     FPRINTF_DEBUG (log_file, "%" GST_TIME_FORMAT NOCOLOR_PRINT_FMT,
1409         GST_TIME_ARGS (elapsed), pid, g_thread_self (),
1410         gst_debug_level_get_name (level),
1411         gst_debug_category_get_name (category), file, line, function, obj,
1412         message_str);
1413     FFLUSH_DEBUG (log_file);
1414   }
1415 
1416   if (object != NULL)
1417     g_free (obj);
1418 }
1419 
1420 /**
1421  * gst_debug_level_get_name:
1422  * @level: the level to get the name for
1423  *
1424  * Get the string representation of a debugging level
1425  *
1426  * Returns: the name
1427  */
1428 const gchar *
gst_debug_level_get_name(GstDebugLevel level)1429 gst_debug_level_get_name (GstDebugLevel level)
1430 {
1431   switch (level) {
1432     case GST_LEVEL_NONE:
1433       return "";
1434     case GST_LEVEL_ERROR:
1435       return "ERROR  ";
1436     case GST_LEVEL_WARNING:
1437       return "WARN   ";
1438     case GST_LEVEL_INFO:
1439       return "INFO   ";
1440     case GST_LEVEL_DEBUG:
1441       return "DEBUG  ";
1442     case GST_LEVEL_LOG:
1443       return "LOG    ";
1444     case GST_LEVEL_FIXME:
1445       return "FIXME  ";
1446     case GST_LEVEL_TRACE:
1447       return "TRACE  ";
1448     case GST_LEVEL_MEMDUMP:
1449       return "MEMDUMP";
1450     default:
1451       g_warning ("invalid level specified for gst_debug_level_get_name");
1452       return "";
1453   }
1454 }
1455 
1456 /**
1457  * gst_debug_add_log_function:
1458  * @func: the function to use
1459  * @user_data: user data
1460  * @notify: called when @user_data is not used anymore
1461  *
1462  * Adds the logging function to the list of logging functions.
1463  * Be sure to use #G_GNUC_NO_INSTRUMENT on that function, it is needed.
1464  */
1465 void
gst_debug_add_log_function(GstLogFunction func,gpointer user_data,GDestroyNotify notify)1466 gst_debug_add_log_function (GstLogFunction func, gpointer user_data,
1467     GDestroyNotify notify)
1468 {
1469   LogFuncEntry *entry;
1470   GSList *list;
1471 
1472   if (func == NULL)
1473     func = gst_debug_log_default;
1474 
1475   entry = g_slice_new (LogFuncEntry);
1476   entry->func = func;
1477   entry->user_data = user_data;
1478   entry->notify = notify;
1479   /* FIXME: we leak the old list here - other threads might access it right now
1480    * in gst_debug_logv. Another solution is to lock the mutex in gst_debug_logv,
1481    * but that is waaay costly.
1482    * It'd probably be clever to use some kind of RCU here, but I don't know
1483    * anything about that.
1484    */
1485   g_mutex_lock (&__log_func_mutex);
1486   list = g_slist_copy (__log_functions);
1487   __log_functions = g_slist_prepend (list, entry);
1488   g_mutex_unlock (&__log_func_mutex);
1489 
1490   if (gst_is_initialized ())
1491     GST_DEBUG ("prepended log function %p (user data %p) to log functions",
1492         func, user_data);
1493 }
1494 
1495 static gint
gst_debug_compare_log_function_by_func(gconstpointer entry,gconstpointer func)1496 gst_debug_compare_log_function_by_func (gconstpointer entry, gconstpointer func)
1497 {
1498   gpointer entryfunc = (gpointer) (((LogFuncEntry *) entry)->func);
1499 
1500   return (entryfunc < func) ? -1 : (entryfunc > func) ? 1 : 0;
1501 }
1502 
1503 static gint
gst_debug_compare_log_function_by_data(gconstpointer entry,gconstpointer data)1504 gst_debug_compare_log_function_by_data (gconstpointer entry, gconstpointer data)
1505 {
1506   gpointer entrydata = ((LogFuncEntry *) entry)->user_data;
1507 
1508   return (entrydata < data) ? -1 : (entrydata > data) ? 1 : 0;
1509 }
1510 
1511 static guint
gst_debug_remove_with_compare_func(GCompareFunc func,gpointer data)1512 gst_debug_remove_with_compare_func (GCompareFunc func, gpointer data)
1513 {
1514   GSList *found;
1515   GSList *new, *cleanup = NULL;
1516   guint removals = 0;
1517 
1518   g_mutex_lock (&__log_func_mutex);
1519   new = __log_functions;
1520   cleanup = NULL;
1521   while ((found = g_slist_find_custom (new, data, func))) {
1522     if (new == __log_functions) {
1523       /* make a copy when we have the first hit, so that we modify the copy and
1524        * make that the new list later */
1525       new = g_slist_copy (new);
1526       continue;
1527     }
1528     cleanup = g_slist_prepend (cleanup, found->data);
1529     new = g_slist_delete_link (new, found);
1530     removals++;
1531   }
1532   /* FIXME: We leak the old list here. See _add_log_function for why. */
1533   __log_functions = new;
1534   g_mutex_unlock (&__log_func_mutex);
1535 
1536   while (cleanup) {
1537     LogFuncEntry *entry = cleanup->data;
1538 
1539     if (entry->notify)
1540       entry->notify (entry->user_data);
1541 
1542     g_slice_free (LogFuncEntry, entry);
1543     cleanup = g_slist_delete_link (cleanup, cleanup);
1544   }
1545   return removals;
1546 }
1547 
1548 /**
1549  * gst_debug_remove_log_function:
1550  * @func: (scope call) (allow-none): the log function to remove, or %NULL to
1551  *     remove the default log function
1552  *
1553  * Removes all registered instances of the given logging functions.
1554  *
1555  * Returns: How many instances of the function were removed
1556  */
1557 guint
gst_debug_remove_log_function(GstLogFunction func)1558 gst_debug_remove_log_function (GstLogFunction func)
1559 {
1560   guint removals;
1561 
1562   if (func == NULL)
1563     func = gst_debug_log_default;
1564 
1565   removals =
1566       gst_debug_remove_with_compare_func
1567       (gst_debug_compare_log_function_by_func, (gpointer) func);
1568 
1569   if (gst_is_initialized ()) {
1570     GST_DEBUG ("removed log function %p %d times from log function list", func,
1571         removals);
1572   } else {
1573     /* If the default log function is removed before gst_init() was called,
1574      * set a flag so we don't add it in gst_init() later */
1575     if (func == gst_debug_log_default) {
1576       add_default_log_func = FALSE;
1577       ++removals;
1578     }
1579   }
1580 
1581   return removals;
1582 }
1583 
1584 /**
1585  * gst_debug_remove_log_function_by_data:
1586  * @data: user data of the log function to remove
1587  *
1588  * Removes all registered instances of log functions with the given user data.
1589  *
1590  * Returns: How many instances of the function were removed
1591  */
1592 guint
gst_debug_remove_log_function_by_data(gpointer data)1593 gst_debug_remove_log_function_by_data (gpointer data)
1594 {
1595   guint removals;
1596 
1597   removals =
1598       gst_debug_remove_with_compare_func
1599       (gst_debug_compare_log_function_by_data, data);
1600 
1601   if (gst_is_initialized ())
1602     GST_DEBUG
1603         ("removed %d log functions with user data %p from log function list",
1604         removals, data);
1605 
1606   return removals;
1607 }
1608 
1609 /**
1610  * gst_debug_set_colored:
1611  * @colored: Whether to use colored output or not
1612  *
1613  * Sets or unsets the use of coloured debugging output.
1614  * Same as gst_debug_set_color_mode () with the argument being
1615  * being GST_DEBUG_COLOR_MODE_ON or GST_DEBUG_COLOR_MODE_OFF.
1616  *
1617  * This function may be called before gst_init().
1618  */
1619 void
gst_debug_set_colored(gboolean colored)1620 gst_debug_set_colored (gboolean colored)
1621 {
1622   GstDebugColorMode new_mode;
1623   new_mode = colored ? GST_DEBUG_COLOR_MODE_ON : GST_DEBUG_COLOR_MODE_OFF;
1624   g_atomic_int_set (&__use_color, (gint) new_mode);
1625 }
1626 
1627 /**
1628  * gst_debug_set_color_mode:
1629  * @mode: The coloring mode for debug output. See @GstDebugColorMode.
1630  *
1631  * Changes the coloring mode for debug output.
1632  *
1633  * This function may be called before gst_init().
1634  *
1635  * Since: 1.2
1636  */
1637 void
gst_debug_set_color_mode(GstDebugColorMode mode)1638 gst_debug_set_color_mode (GstDebugColorMode mode)
1639 {
1640   g_atomic_int_set (&__use_color, mode);
1641 }
1642 
1643 /**
1644  * gst_debug_set_color_mode_from_string:
1645  * @mode: The coloring mode for debug output. One of the following:
1646  * "on", "auto", "off", "disable", "unix".
1647  *
1648  * Changes the coloring mode for debug output.
1649  *
1650  * This function may be called before gst_init().
1651  *
1652  * Since: 1.2
1653  */
1654 void
gst_debug_set_color_mode_from_string(const gchar * mode)1655 gst_debug_set_color_mode_from_string (const gchar * mode)
1656 {
1657   if ((strcmp (mode, "on") == 0) || (strcmp (mode, "auto") == 0))
1658     gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_ON);
1659   else if ((strcmp (mode, "off") == 0) || (strcmp (mode, "disable") == 0))
1660     gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_OFF);
1661   else if (strcmp (mode, "unix") == 0)
1662     gst_debug_set_color_mode (GST_DEBUG_COLOR_MODE_UNIX);
1663 }
1664 
1665 /**
1666  * gst_debug_is_colored:
1667  *
1668  * Checks if the debugging output should be colored.
1669  *
1670  * Returns: %TRUE, if the debug output should be colored.
1671  */
1672 gboolean
gst_debug_is_colored(void)1673 gst_debug_is_colored (void)
1674 {
1675   GstDebugColorMode mode = g_atomic_int_get (&__use_color);
1676   return (mode == GST_DEBUG_COLOR_MODE_UNIX || mode == GST_DEBUG_COLOR_MODE_ON);
1677 }
1678 
1679 /**
1680  * gst_debug_get_color_mode:
1681  *
1682  * Changes the coloring mode for debug output.
1683  *
1684  * Returns: see @GstDebugColorMode for possible values.
1685  *
1686  * Since: 1.2
1687  */
1688 GstDebugColorMode
gst_debug_get_color_mode(void)1689 gst_debug_get_color_mode (void)
1690 {
1691   return g_atomic_int_get (&__use_color);
1692 }
1693 
1694 /**
1695  * gst_debug_set_active:
1696  * @active: Whether to use debugging output or not
1697  *
1698  * If activated, debugging messages are sent to the debugging
1699  * handlers.
1700  * It makes sense to deactivate it for speed issues.
1701  * > This function is not threadsafe. It makes sense to only call it
1702  * during initialization.
1703  */
1704 void
gst_debug_set_active(gboolean active)1705 gst_debug_set_active (gboolean active)
1706 {
1707   _gst_debug_enabled = active;
1708   if (active)
1709     _gst_debug_min = GST_LEVEL_COUNT;
1710   else
1711     _gst_debug_min = GST_LEVEL_NONE;
1712 }
1713 
1714 /**
1715  * gst_debug_is_active:
1716  *
1717  * Checks if debugging output is activated.
1718  *
1719  * Returns: %TRUE, if debugging is activated
1720  */
1721 gboolean
gst_debug_is_active(void)1722 gst_debug_is_active (void)
1723 {
1724   return _gst_debug_enabled;
1725 }
1726 
1727 /**
1728  * gst_debug_set_default_threshold:
1729  * @level: level to set
1730  *
1731  * Sets the default threshold to the given level and updates all categories to
1732  * use this threshold.
1733  *
1734  * This function may be called before gst_init().
1735  */
1736 void
gst_debug_set_default_threshold(GstDebugLevel level)1737 gst_debug_set_default_threshold (GstDebugLevel level)
1738 {
1739   g_atomic_int_set (&__default_level, level);
1740   gst_debug_reset_all_thresholds ();
1741 }
1742 
1743 /**
1744  * gst_debug_get_default_threshold:
1745  *
1746  * Returns the default threshold that is used for new categories.
1747  *
1748  * Returns: the default threshold level
1749  */
1750 GstDebugLevel
gst_debug_get_default_threshold(void)1751 gst_debug_get_default_threshold (void)
1752 {
1753   return (GstDebugLevel) g_atomic_int_get (&__default_level);
1754 }
1755 
1756 #if !GLIB_CHECK_VERSION(2,70,0)
1757 #define g_pattern_spec_match_string g_pattern_match_string
1758 #endif
1759 
1760 static gboolean
gst_debug_apply_entry(GstDebugCategory * cat,LevelNameEntry * entry)1761 gst_debug_apply_entry (GstDebugCategory * cat, LevelNameEntry * entry)
1762 {
1763   if (!g_pattern_spec_match_string (entry->pat, cat->name))
1764     return FALSE;
1765 
1766   if (gst_is_initialized ())
1767     GST_LOG ("category %s matches pattern %p - gets set to level %d",
1768         cat->name, entry->pat, entry->level);
1769 
1770   gst_debug_category_set_threshold (cat, entry->level);
1771   return TRUE;
1772 }
1773 
1774 static void
gst_debug_reset_threshold(gpointer category,gpointer unused)1775 gst_debug_reset_threshold (gpointer category, gpointer unused)
1776 {
1777   GstDebugCategory *cat = (GstDebugCategory *) category;
1778   GSList *walk;
1779 
1780   g_mutex_lock (&__level_name_mutex);
1781 
1782   for (walk = __level_name; walk != NULL; walk = walk->next) {
1783     if (gst_debug_apply_entry (cat, walk->data))
1784       break;
1785   }
1786 
1787   g_mutex_unlock (&__level_name_mutex);
1788 
1789   if (walk == NULL)
1790     gst_debug_category_set_threshold (cat, gst_debug_get_default_threshold ());
1791 }
1792 
1793 static void
gst_debug_reset_all_thresholds(void)1794 gst_debug_reset_all_thresholds (void)
1795 {
1796   g_mutex_lock (&__cat_mutex);
1797   g_slist_foreach (__categories, gst_debug_reset_threshold, NULL);
1798   g_mutex_unlock (&__cat_mutex);
1799 }
1800 
1801 static void
for_each_threshold_by_entry(gpointer data,gpointer user_data)1802 for_each_threshold_by_entry (gpointer data, gpointer user_data)
1803 {
1804   GstDebugCategory *cat = (GstDebugCategory *) data;
1805   LevelNameEntry *entry = (LevelNameEntry *) user_data;
1806 
1807   gst_debug_apply_entry (cat, entry);
1808 }
1809 
1810 /**
1811  * gst_debug_set_threshold_for_name:
1812  * @name: name of the categories to set
1813  * @level: level to set them to
1814  *
1815  * Sets all categories which match the given glob style pattern to the given
1816  * level.
1817  */
1818 void
gst_debug_set_threshold_for_name(const gchar * name,GstDebugLevel level)1819 gst_debug_set_threshold_for_name (const gchar * name, GstDebugLevel level)
1820 {
1821   GPatternSpec *pat;
1822   LevelNameEntry *entry;
1823 
1824   g_return_if_fail (name != NULL);
1825 
1826   pat = g_pattern_spec_new (name);
1827   entry = g_slice_new (LevelNameEntry);
1828   entry->pat = pat;
1829   entry->level = level;
1830   g_mutex_lock (&__level_name_mutex);
1831   __level_name = g_slist_prepend (__level_name, entry);
1832   g_mutex_unlock (&__level_name_mutex);
1833   g_mutex_lock (&__cat_mutex);
1834   g_slist_foreach (__categories, for_each_threshold_by_entry, entry);
1835   g_mutex_unlock (&__cat_mutex);
1836 }
1837 
1838 /**
1839  * gst_debug_unset_threshold_for_name:
1840  * @name: name of the categories to set
1841  *
1842  * Resets all categories with the given name back to the default level.
1843  */
1844 void
gst_debug_unset_threshold_for_name(const gchar * name)1845 gst_debug_unset_threshold_for_name (const gchar * name)
1846 {
1847   GSList *walk;
1848   GPatternSpec *pat;
1849 
1850   g_return_if_fail (name != NULL);
1851 
1852   pat = g_pattern_spec_new (name);
1853   g_mutex_lock (&__level_name_mutex);
1854   walk = __level_name;
1855   /* improve this if you want, it's mighty slow */
1856   while (walk) {
1857     LevelNameEntry *entry = walk->data;
1858 
1859     if (g_pattern_spec_equal (entry->pat, pat)) {
1860       __level_name = g_slist_remove_link (__level_name, walk);
1861       g_pattern_spec_free (entry->pat);
1862       g_slice_free (LevelNameEntry, entry);
1863       g_slist_free_1 (walk);
1864       walk = __level_name;
1865     } else {
1866       walk = g_slist_next (walk);
1867     }
1868   }
1869   g_mutex_unlock (&__level_name_mutex);
1870   g_pattern_spec_free (pat);
1871   gst_debug_reset_all_thresholds ();
1872 }
1873 
1874 GstDebugCategory *
_gst_debug_category_new(const gchar * name,guint color,const gchar * description)1875 _gst_debug_category_new (const gchar * name, guint color,
1876     const gchar * description)
1877 {
1878   GstDebugCategory *cat, *catfound;
1879 
1880   g_return_val_if_fail (name != NULL, NULL);
1881 
1882   cat = g_slice_new (GstDebugCategory);
1883   cat->name = g_strdup (name);
1884   cat->color = color;
1885   if (description != NULL) {
1886     cat->description = g_strdup (description);
1887   } else {
1888     cat->description = g_strdup ("no description");
1889   }
1890   g_atomic_int_set (&cat->threshold, 0);
1891   gst_debug_reset_threshold (cat, NULL);
1892 
1893   /* add to category list */
1894   g_mutex_lock (&__cat_mutex);
1895   catfound = _gst_debug_get_category_locked (name);
1896   if (catfound) {
1897     g_free ((gpointer) cat->name);
1898     g_free ((gpointer) cat->description);
1899     g_slice_free (GstDebugCategory, cat);
1900     cat = catfound;
1901   } else {
1902     __categories = g_slist_prepend (__categories, cat);
1903   }
1904   g_mutex_unlock (&__cat_mutex);
1905 
1906   return cat;
1907 }
1908 
1909 #ifndef GST_REMOVE_DEPRECATED
1910 /**
1911  * gst_debug_category_free:
1912  * @category: #GstDebugCategory to free.
1913  *
1914  * Removes and frees the category and all associated resources.
1915  *
1916  * Deprecated: This function can easily cause memory corruption, don't use it.
1917  */
1918 void
gst_debug_category_free(GstDebugCategory * category)1919 gst_debug_category_free (GstDebugCategory * category)
1920 {
1921 }
1922 #endif
1923 
1924 /**
1925  * gst_debug_category_set_threshold:
1926  * @category: a #GstDebugCategory to set threshold of.
1927  * @level: the #GstDebugLevel threshold to set.
1928  *
1929  * Sets the threshold of the category to the given level. Debug information will
1930  * only be output if the threshold is lower or equal to the level of the
1931  * debugging message.
1932  * > Do not use this function in production code, because other functions may
1933  * > change the threshold of categories as side effect. It is however a nice
1934  * > function to use when debugging (even from gdb).
1935  */
1936 void
gst_debug_category_set_threshold(GstDebugCategory * category,GstDebugLevel level)1937 gst_debug_category_set_threshold (GstDebugCategory * category,
1938     GstDebugLevel level)
1939 {
1940   g_return_if_fail (category != NULL);
1941 
1942   if (level > _gst_debug_min) {
1943     _gst_debug_enabled = TRUE;
1944     _gst_debug_min = level;
1945   }
1946 
1947   g_atomic_int_set (&category->threshold, level);
1948 }
1949 
1950 /**
1951  * gst_debug_category_reset_threshold:
1952  * @category: a #GstDebugCategory to reset threshold of.
1953  *
1954  * Resets the threshold of the category to the default level. Debug information
1955  * will only be output if the threshold is lower or equal to the level of the
1956  * debugging message.
1957  * Use this function to set the threshold back to where it was after using
1958  * gst_debug_category_set_threshold().
1959  */
1960 void
gst_debug_category_reset_threshold(GstDebugCategory * category)1961 gst_debug_category_reset_threshold (GstDebugCategory * category)
1962 {
1963   gst_debug_reset_threshold (category, NULL);
1964 }
1965 
1966 /**
1967  * gst_debug_category_get_threshold:
1968  * @category: a #GstDebugCategory to get threshold of.
1969  *
1970  * Returns the threshold of a #GstDebugCategory.
1971  *
1972  * Returns: the #GstDebugLevel that is used as threshold.
1973  */
1974 GstDebugLevel
gst_debug_category_get_threshold(GstDebugCategory * category)1975 gst_debug_category_get_threshold (GstDebugCategory * category)
1976 {
1977   return (GstDebugLevel) g_atomic_int_get (&category->threshold);
1978 }
1979 
1980 /**
1981  * gst_debug_category_get_name:
1982  * @category: a #GstDebugCategory to get name of.
1983  *
1984  * Returns the name of a debug category.
1985  *
1986  * Returns: the name of the category.
1987  */
1988 const gchar *
gst_debug_category_get_name(GstDebugCategory * category)1989 gst_debug_category_get_name (GstDebugCategory * category)
1990 {
1991   return category->name;
1992 }
1993 
1994 /**
1995  * gst_debug_category_get_color:
1996  * @category: a #GstDebugCategory to get the color of.
1997  *
1998  * Returns the color of a debug category used when printing output in this
1999  * category.
2000  *
2001  * Returns: the color of the category.
2002  */
2003 guint
gst_debug_category_get_color(GstDebugCategory * category)2004 gst_debug_category_get_color (GstDebugCategory * category)
2005 {
2006   return category->color;
2007 }
2008 
2009 /**
2010  * gst_debug_category_get_description:
2011  * @category: a #GstDebugCategory to get the description of.
2012  *
2013  * Returns the description of a debug category.
2014  *
2015  * Returns: the description of the category.
2016  */
2017 const gchar *
gst_debug_category_get_description(GstDebugCategory * category)2018 gst_debug_category_get_description (GstDebugCategory * category)
2019 {
2020   return category->description;
2021 }
2022 
2023 /**
2024  * gst_debug_get_all_categories:
2025  *
2026  * Returns a snapshot of a all categories that are currently in use . This list
2027  * may change anytime.
2028  * The caller has to free the list after use.
2029  *
2030  * Returns: (transfer container) (element-type Gst.DebugCategory): the list of
2031  *     debug categories
2032  */
2033 GSList *
gst_debug_get_all_categories(void)2034 gst_debug_get_all_categories (void)
2035 {
2036   GSList *ret;
2037 
2038   g_mutex_lock (&__cat_mutex);
2039   ret = g_slist_copy (__categories);
2040   g_mutex_unlock (&__cat_mutex);
2041 
2042   return ret;
2043 }
2044 
2045 static GstDebugCategory *
_gst_debug_get_category_locked(const gchar * name)2046 _gst_debug_get_category_locked (const gchar * name)
2047 {
2048   GstDebugCategory *ret = NULL;
2049   GSList *node;
2050 
2051   for (node = __categories; node; node = g_slist_next (node)) {
2052     ret = (GstDebugCategory *) node->data;
2053     if (!strcmp (name, ret->name)) {
2054       return ret;
2055     }
2056   }
2057   return NULL;
2058 }
2059 
2060 GstDebugCategory *
_gst_debug_get_category(const gchar * name)2061 _gst_debug_get_category (const gchar * name)
2062 {
2063   GstDebugCategory *ret;
2064 
2065   g_mutex_lock (&__cat_mutex);
2066   ret = _gst_debug_get_category_locked (name);
2067   g_mutex_unlock (&__cat_mutex);
2068 
2069   return ret;
2070 }
2071 
2072 static gboolean
parse_debug_category(gchar * str,const gchar ** category)2073 parse_debug_category (gchar * str, const gchar ** category)
2074 {
2075   if (!str)
2076     return FALSE;
2077 
2078   /* works in place */
2079   g_strstrip (str);
2080 
2081   if (str[0] != '\0') {
2082     *category = str;
2083     return TRUE;
2084   }
2085 
2086   return FALSE;
2087 }
2088 
2089 static gboolean
parse_debug_level(gchar * str,GstDebugLevel * level)2090 parse_debug_level (gchar * str, GstDebugLevel * level)
2091 {
2092   if (!str)
2093     return FALSE;
2094 
2095   /* works in place */
2096   g_strstrip (str);
2097 
2098   if (g_ascii_isdigit (str[0])) {
2099     unsigned long l;
2100     char *endptr;
2101     l = strtoul (str, &endptr, 10);
2102     if (endptr > str && endptr[0] == 0) {
2103       *level = (GstDebugLevel) l;
2104     } else {
2105       return FALSE;
2106     }
2107   } else if (strcmp (str, "ERROR") == 0) {
2108     *level = GST_LEVEL_ERROR;
2109   } else if (strncmp (str, "WARN", 4) == 0) {
2110     *level = GST_LEVEL_WARNING;
2111   } else if (strcmp (str, "FIXME") == 0) {
2112     *level = GST_LEVEL_FIXME;
2113   } else if (strcmp (str, "INFO") == 0) {
2114     *level = GST_LEVEL_INFO;
2115   } else if (strcmp (str, "DEBUG") == 0) {
2116     *level = GST_LEVEL_DEBUG;
2117   } else if (strcmp (str, "LOG") == 0) {
2118     *level = GST_LEVEL_LOG;
2119   } else if (strcmp (str, "TRACE") == 0) {
2120     *level = GST_LEVEL_TRACE;
2121   } else if (strcmp (str, "MEMDUMP") == 0) {
2122     *level = GST_LEVEL_MEMDUMP;
2123   } else
2124     return FALSE;
2125 
2126   return TRUE;
2127 }
2128 
2129 /**
2130  * gst_debug_set_threshold_from_string:
2131  * @list: comma-separated list of "category:level" pairs to be used
2132  *     as debug logging levels
2133  * @reset: %TRUE to clear all previously-set debug levels before setting
2134  *     new thresholds
2135  * %FALSE if adding the threshold described by @list to the one already set.
2136  *
2137  * Sets the debug logging wanted in the same form as with the GST_DEBUG
2138  * environment variable. You can use wildcards such as '*', but note that
2139  * the order matters when you use wild cards, e.g. "foosrc:6,*src:3,*:2" sets
2140  * everything to log level 2.
2141  *
2142  * Since: 1.2
2143  */
2144 void
gst_debug_set_threshold_from_string(const gchar * list,gboolean reset)2145 gst_debug_set_threshold_from_string (const gchar * list, gboolean reset)
2146 {
2147   gchar **split;
2148   gchar **walk;
2149 
2150   g_assert (list);
2151 
2152   if (reset)
2153     gst_debug_set_default_threshold (GST_LEVEL_DEFAULT);
2154 
2155   split = g_strsplit (list, ",", 0);
2156 
2157   for (walk = split; *walk; walk++) {
2158     if (strchr (*walk, ':')) {
2159       gchar **values = g_strsplit (*walk, ":", 2);
2160 
2161       if (values[0] && values[1]) {
2162         GstDebugLevel level;
2163         const gchar *category;
2164 
2165         if (parse_debug_category (values[0], &category)
2166             && parse_debug_level (values[1], &level)) {
2167           gst_debug_set_threshold_for_name (category, level);
2168 
2169           /* bump min-level anyway to allow the category to be registered in the
2170            * future still */
2171           if (level > _gst_debug_min) {
2172             _gst_debug_min = level;
2173           }
2174         }
2175       }
2176 
2177       g_strfreev (values);
2178     } else {
2179       GstDebugLevel level;
2180 
2181       if (parse_debug_level (*walk, &level))
2182         gst_debug_set_default_threshold (level);
2183     }
2184   }
2185 
2186   g_strfreev (split);
2187 }
2188 
2189 /*** FUNCTION POINTERS ********************************************************/
2190 
2191 static GHashTable *__gst_function_pointers;     /* NULL */
2192 static GMutex __dbg_functions_mutex;
2193 
2194 /* This function MUST NOT return NULL */
2195 const gchar *
_gst_debug_nameof_funcptr(GstDebugFuncPtr func)2196 _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
2197 {
2198   gchar *ptrname;
2199 
2200 #ifdef HAVE_DLADDR
2201   Dl_info dl_info;
2202 #endif
2203 
2204   if (G_UNLIKELY (func == NULL))
2205     return "(NULL)";
2206 
2207   g_mutex_lock (&__dbg_functions_mutex);
2208   if (G_LIKELY (__gst_function_pointers)) {
2209     ptrname = g_hash_table_lookup (__gst_function_pointers, (gpointer) func);
2210     g_mutex_unlock (&__dbg_functions_mutex);
2211     if (G_LIKELY (ptrname))
2212       return ptrname;
2213   } else {
2214     g_mutex_unlock (&__dbg_functions_mutex);
2215   }
2216   /* we need to create an entry in the hash table for this one so we don't leak
2217    * the name */
2218 #ifdef HAVE_DLADDR
2219   if (dladdr ((gpointer) func, &dl_info) && dl_info.dli_sname) {
2220     const gchar *name = g_intern_string (dl_info.dli_sname);
2221 
2222     _gst_debug_register_funcptr (func, name);
2223     return name;
2224   } else
2225 #endif
2226   {
2227     gchar *name = g_strdup_printf ("%p", (gpointer) func);
2228     const gchar *iname = g_intern_string (name);
2229 
2230     g_free (name);
2231 
2232     _gst_debug_register_funcptr (func, iname);
2233     return iname;
2234   }
2235 }
2236 
2237 void
_gst_debug_register_funcptr(GstDebugFuncPtr func,const gchar * ptrname)2238 _gst_debug_register_funcptr (GstDebugFuncPtr func, const gchar * ptrname)
2239 {
2240   gpointer ptr = (gpointer) func;
2241 
2242   g_mutex_lock (&__dbg_functions_mutex);
2243 
2244   if (!__gst_function_pointers)
2245     __gst_function_pointers = g_hash_table_new (g_direct_hash, g_direct_equal);
2246   if (!g_hash_table_lookup (__gst_function_pointers, ptr)) {
2247     g_hash_table_insert (__gst_function_pointers, ptr, (gpointer) ptrname);
2248   }
2249 
2250   g_mutex_unlock (&__dbg_functions_mutex);
2251 }
2252 
2253 void
_priv_gst_debug_cleanup(void)2254 _priv_gst_debug_cleanup (void)
2255 {
2256   g_mutex_lock (&__dbg_functions_mutex);
2257 
2258   if (__gst_function_pointers) {
2259     g_hash_table_unref (__gst_function_pointers);
2260     __gst_function_pointers = NULL;
2261   }
2262 
2263   g_mutex_unlock (&__dbg_functions_mutex);
2264 
2265   g_mutex_lock (&__cat_mutex);
2266   while (__categories) {
2267     GstDebugCategory *cat = __categories->data;
2268     g_free ((gpointer) cat->name);
2269     g_free ((gpointer) cat->description);
2270     g_slice_free (GstDebugCategory, cat);
2271     __categories = g_slist_delete_link (__categories, __categories);
2272   }
2273   g_mutex_unlock (&__cat_mutex);
2274 
2275   g_mutex_lock (&__level_name_mutex);
2276   while (__level_name) {
2277     LevelNameEntry *level_name_entry = __level_name->data;
2278     g_pattern_spec_free (level_name_entry->pat);
2279     g_slice_free (LevelNameEntry, level_name_entry);
2280     __level_name = g_slist_delete_link (__level_name, __level_name);
2281   }
2282   g_mutex_unlock (&__level_name_mutex);
2283 
2284   g_mutex_lock (&__log_func_mutex);
2285   while (__log_functions) {
2286     LogFuncEntry *log_func_entry = __log_functions->data;
2287     if (log_func_entry->notify)
2288       log_func_entry->notify (log_func_entry->user_data);
2289     g_slice_free (LogFuncEntry, log_func_entry);
2290     __log_functions = g_slist_delete_link (__log_functions, __log_functions);
2291   }
2292   g_mutex_unlock (&__log_func_mutex);
2293 }
2294 
2295 static void
gst_info_dump_mem_line(gchar * linebuf,gsize linebuf_size,const guint8 * mem,gsize mem_offset,gsize mem_size)2296 gst_info_dump_mem_line (gchar * linebuf, gsize linebuf_size,
2297     const guint8 * mem, gsize mem_offset, gsize mem_size)
2298 {
2299   gchar hexstr[50], ascstr[18], digitstr[4];
2300 
2301   if (mem_size > 16)
2302     mem_size = 16;
2303 
2304   hexstr[0] = '\0';
2305   ascstr[0] = '\0';
2306 
2307   if (mem != NULL) {
2308     guint i = 0;
2309 
2310     mem += mem_offset;
2311     while (i < mem_size) {
2312       ascstr[i] = (g_ascii_isprint (mem[i])) ? mem[i] : '.';
2313       g_snprintf (digitstr, sizeof (digitstr), "%02x ", mem[i]);
2314       g_strlcat (hexstr, digitstr, sizeof (hexstr));
2315       ++i;
2316     }
2317     ascstr[i] = '\0';
2318   }
2319 
2320   g_snprintf (linebuf, linebuf_size, "%08x: %-48.48s %-16.16s",
2321       (guint) mem_offset, hexstr, ascstr);
2322 }
2323 
2324 void
_gst_debug_dump_mem(GstDebugCategory * cat,const gchar * file,const gchar * func,gint line,GObject * obj,const gchar * msg,const guint8 * data,guint length)2325 _gst_debug_dump_mem (GstDebugCategory * cat, const gchar * file,
2326     const gchar * func, gint line, GObject * obj, const gchar * msg,
2327     const guint8 * data, guint length)
2328 {
2329   guint off = 0;
2330 
2331   gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "--------"
2332       "-------------------------------------------------------------------");
2333 
2334   if (msg != NULL && *msg != '\0') {
2335     gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "%s", msg);
2336   }
2337 
2338   while (off < length) {
2339     gchar buf[128];
2340 
2341     /* gst_info_dump_mem_line will process 16 bytes at most */
2342     gst_info_dump_mem_line (buf, sizeof (buf), data, off, length - off);
2343     gst_debug_log (cat, GST_LEVEL_MEMDUMP, file, func, line, obj, "%s", buf);
2344     off += 16;
2345   }
2346 
2347   gst_debug_log ((cat), GST_LEVEL_MEMDUMP, file, func, line, obj, "--------"
2348       "-------------------------------------------------------------------");
2349 }
2350 
2351 #else /* !GST_DISABLE_GST_DEBUG */
2352 #ifndef GST_REMOVE_DISABLED
2353 
2354 GstDebugCategory *
_gst_debug_category_new(const gchar * name,guint color,const gchar * description)2355 _gst_debug_category_new (const gchar * name, guint color,
2356     const gchar * description)
2357 {
2358   return NULL;
2359 }
2360 
2361 void
_gst_debug_register_funcptr(GstDebugFuncPtr func,const gchar * ptrname)2362 _gst_debug_register_funcptr (GstDebugFuncPtr func, const gchar * ptrname)
2363 {
2364 }
2365 
2366 /* This function MUST NOT return NULL */
2367 const gchar *
_gst_debug_nameof_funcptr(GstDebugFuncPtr func)2368 _gst_debug_nameof_funcptr (GstDebugFuncPtr func)
2369 {
2370   return "(NULL)";
2371 }
2372 
2373 void
_priv_gst_debug_cleanup(void)2374 _priv_gst_debug_cleanup (void)
2375 {
2376 }
2377 
2378 void
gst_debug_log(GstDebugCategory * category,GstDebugLevel level,const gchar * file,const gchar * function,gint line,GObject * object,const gchar * format,...)2379 gst_debug_log (GstDebugCategory * category, GstDebugLevel level,
2380     const gchar * file, const gchar * function, gint line,
2381     GObject * object, const gchar * format, ...)
2382 {
2383 }
2384 
2385 void
gst_debug_log_valist(GstDebugCategory * category,GstDebugLevel level,const gchar * file,const gchar * function,gint line,GObject * object,const gchar * format,va_list args)2386 gst_debug_log_valist (GstDebugCategory * category, GstDebugLevel level,
2387     const gchar * file, const gchar * function, gint line,
2388     GObject * object, const gchar * format, va_list args)
2389 {
2390 }
2391 
2392 void
gst_debug_log_literal(GstDebugCategory * category,GstDebugLevel level,const gchar * file,const gchar * function,gint line,GObject * object,const gchar * message_string)2393 gst_debug_log_literal (GstDebugCategory * category, GstDebugLevel level,
2394     const gchar * file, const gchar * function, gint line,
2395     GObject * object, const gchar * message_string)
2396 {
2397 }
2398 
2399 const gchar *
gst_debug_message_get(GstDebugMessage * message)2400 gst_debug_message_get (GstDebugMessage * message)
2401 {
2402   return "";
2403 }
2404 
2405 void
gst_debug_log_default(GstDebugCategory * category,GstDebugLevel level,const gchar * file,const gchar * function,gint line,GObject * object,GstDebugMessage * message,gpointer unused)2406 gst_debug_log_default (GstDebugCategory * category, GstDebugLevel level,
2407     const gchar * file, const gchar * function, gint line,
2408     GObject * object, GstDebugMessage * message, gpointer unused)
2409 {
2410 }
2411 
2412 const gchar *
gst_debug_level_get_name(GstDebugLevel level)2413 gst_debug_level_get_name (GstDebugLevel level)
2414 {
2415   return "NONE";
2416 }
2417 
2418 void
gst_debug_add_log_function(GstLogFunction func,gpointer user_data,GDestroyNotify notify)2419 gst_debug_add_log_function (GstLogFunction func, gpointer user_data,
2420     GDestroyNotify notify)
2421 {
2422   if (notify)
2423     notify (user_data);
2424 }
2425 
2426 guint
gst_debug_remove_log_function(GstLogFunction func)2427 gst_debug_remove_log_function (GstLogFunction func)
2428 {
2429   return 0;
2430 }
2431 
2432 guint
gst_debug_remove_log_function_by_data(gpointer data)2433 gst_debug_remove_log_function_by_data (gpointer data)
2434 {
2435   return 0;
2436 }
2437 
2438 void
gst_debug_set_active(gboolean active)2439 gst_debug_set_active (gboolean active)
2440 {
2441 }
2442 
2443 gboolean
gst_debug_is_active(void)2444 gst_debug_is_active (void)
2445 {
2446   return FALSE;
2447 }
2448 
2449 void
gst_debug_set_colored(gboolean colored)2450 gst_debug_set_colored (gboolean colored)
2451 {
2452 }
2453 
2454 void
gst_debug_set_color_mode(GstDebugColorMode mode)2455 gst_debug_set_color_mode (GstDebugColorMode mode)
2456 {
2457 }
2458 
2459 void
gst_debug_set_color_mode_from_string(const gchar * str)2460 gst_debug_set_color_mode_from_string (const gchar * str)
2461 {
2462 }
2463 
2464 gboolean
gst_debug_is_colored(void)2465 gst_debug_is_colored (void)
2466 {
2467   return FALSE;
2468 }
2469 
2470 GstDebugColorMode
gst_debug_get_color_mode(void)2471 gst_debug_get_color_mode (void)
2472 {
2473   return GST_DEBUG_COLOR_MODE_OFF;
2474 }
2475 
2476 void
gst_debug_set_threshold_from_string(const gchar * list,gboolean reset)2477 gst_debug_set_threshold_from_string (const gchar * list, gboolean reset)
2478 {
2479 }
2480 
2481 void
gst_debug_set_default_threshold(GstDebugLevel level)2482 gst_debug_set_default_threshold (GstDebugLevel level)
2483 {
2484 }
2485 
2486 GstDebugLevel
gst_debug_get_default_threshold(void)2487 gst_debug_get_default_threshold (void)
2488 {
2489   return GST_LEVEL_NONE;
2490 }
2491 
2492 void
gst_debug_set_threshold_for_name(const gchar * name,GstDebugLevel level)2493 gst_debug_set_threshold_for_name (const gchar * name, GstDebugLevel level)
2494 {
2495 }
2496 
2497 void
gst_debug_unset_threshold_for_name(const gchar * name)2498 gst_debug_unset_threshold_for_name (const gchar * name)
2499 {
2500 }
2501 
2502 #ifndef GST_REMOVE_DEPRECATED
2503 void
gst_debug_category_free(GstDebugCategory * category)2504 gst_debug_category_free (GstDebugCategory * category)
2505 {
2506 }
2507 #endif
2508 
2509 void
gst_debug_category_set_threshold(GstDebugCategory * category,GstDebugLevel level)2510 gst_debug_category_set_threshold (GstDebugCategory * category,
2511     GstDebugLevel level)
2512 {
2513 }
2514 
2515 void
gst_debug_category_reset_threshold(GstDebugCategory * category)2516 gst_debug_category_reset_threshold (GstDebugCategory * category)
2517 {
2518 }
2519 
2520 GstDebugLevel
gst_debug_category_get_threshold(GstDebugCategory * category)2521 gst_debug_category_get_threshold (GstDebugCategory * category)
2522 {
2523   return GST_LEVEL_NONE;
2524 }
2525 
2526 const gchar *
gst_debug_category_get_name(GstDebugCategory * category)2527 gst_debug_category_get_name (GstDebugCategory * category)
2528 {
2529   return "";
2530 }
2531 
2532 guint
gst_debug_category_get_color(GstDebugCategory * category)2533 gst_debug_category_get_color (GstDebugCategory * category)
2534 {
2535   return 0;
2536 }
2537 
2538 const gchar *
gst_debug_category_get_description(GstDebugCategory * category)2539 gst_debug_category_get_description (GstDebugCategory * category)
2540 {
2541   return "";
2542 }
2543 
2544 GSList *
gst_debug_get_all_categories(void)2545 gst_debug_get_all_categories (void)
2546 {
2547   return NULL;
2548 }
2549 
2550 GstDebugCategory *
_gst_debug_get_category(const gchar * name)2551 _gst_debug_get_category (const gchar * name)
2552 {
2553   return NULL;
2554 }
2555 
2556 gchar *
gst_debug_construct_term_color(guint colorinfo)2557 gst_debug_construct_term_color (guint colorinfo)
2558 {
2559   return g_strdup ("00");
2560 }
2561 
2562 gint
gst_debug_construct_win_color(guint colorinfo)2563 gst_debug_construct_win_color (guint colorinfo)
2564 {
2565   return 0;
2566 }
2567 
2568 void
_gst_debug_dump_mem(GstDebugCategory * cat,const gchar * file,const gchar * func,gint line,GObject * obj,const gchar * msg,const guint8 * data,guint length)2569 _gst_debug_dump_mem (GstDebugCategory * cat, const gchar * file,
2570     const gchar * func, gint line, GObject * obj, const gchar * msg,
2571     const guint8 * data, guint length)
2572 {
2573 }
2574 #endif /* GST_REMOVE_DISABLED */
2575 #endif /* GST_DISABLE_GST_DEBUG */
2576 
2577 /* Need this for _gst_element_error_printf even if GST_REMOVE_DISABLED is set:
2578  * fallback function that cleans up the format string and replaces all pointer
2579  * extension formats with plain %p. */
2580 #ifdef GST_DISABLE_GST_DEBUG
2581 int
__gst_info_fallback_vasprintf(char ** result,char const * format,va_list args)2582 __gst_info_fallback_vasprintf (char **result, char const *format, va_list args)
2583 {
2584   gchar *clean_format, *c;
2585   gsize len;
2586 
2587   if (format == NULL)
2588     return -1;
2589 
2590   clean_format = g_strdup (format);
2591   c = clean_format;
2592   while ((c = strstr (c, "%p\a"))) {
2593     if (c[3] < 'A' || c[3] > 'Z') {
2594       c += 3;
2595       continue;
2596     }
2597     len = strlen (c + 4);
2598     memmove (c + 2, c + 4, len + 1);
2599     c += 2;
2600   }
2601   while ((c = strstr (clean_format, "%P")))     /* old GST_PTR_FORMAT */
2602     c[1] = 'p';
2603   while ((c = strstr (clean_format, "%Q")))     /* old GST_SEGMENT_FORMAT */
2604     c[1] = 'p';
2605 
2606   len = g_vasprintf (result, clean_format, args);
2607 
2608   g_free (clean_format);
2609 
2610   if (*result == NULL)
2611     return -1;
2612 
2613   return len;
2614 }
2615 #endif
2616 
2617 /**
2618  * gst_info_vasprintf:
2619  * @result: (out): the resulting string
2620  * @format: a printf style format string
2621  * @args: the va_list of printf arguments for @format
2622  *
2623  * Allocates and fills a string large enough (including the terminating null
2624  * byte) to hold the specified printf style @format and @args.
2625  *
2626  * This function deals with the GStreamer specific printf specifiers
2627  * #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.  If you do not have these specifiers
2628  * in your @format string, you do not need to use this function and can use
2629  * alternatives such as g_vasprintf().
2630  *
2631  * Free @result with g_free().
2632  *
2633  * Returns: the length of the string allocated into @result or -1 on any error
2634  *
2635  * Since: 1.8
2636  */
2637 gint
gst_info_vasprintf(gchar ** result,const gchar * format,va_list args)2638 gst_info_vasprintf (gchar ** result, const gchar * format, va_list args)
2639 {
2640   /* This will fallback to __gst_info_fallback_vasprintf() via a #define in
2641    * gst_private.h if the debug system is disabled which will remove the gst
2642    * specific printf format specifiers */
2643   return __gst_vasprintf (result, format, args);
2644 }
2645 
2646 /**
2647  * gst_info_strdup_vprintf:
2648  * @format: a printf style format string
2649  * @args: the va_list of printf arguments for @format
2650  *
2651  * Allocates, fills and returns a null terminated string from the printf style
2652  * @format string and @args.
2653  *
2654  * See gst_info_vasprintf() for when this function is required.
2655  *
2656  * Free with g_free().
2657  *
2658  * Returns: (nullable): a newly allocated null terminated string or %NULL on any error
2659  *
2660  * Since: 1.8
2661  */
2662 gchar *
gst_info_strdup_vprintf(const gchar * format,va_list args)2663 gst_info_strdup_vprintf (const gchar * format, va_list args)
2664 {
2665   gchar *ret;
2666 
2667   if (gst_info_vasprintf (&ret, format, args) < 0)
2668     ret = NULL;
2669 
2670   return ret;
2671 }
2672 
2673 /**
2674  * gst_info_strdup_printf:
2675  * @format: a printf style format string
2676  * @...: the printf arguments for @format
2677  *
2678  * Allocates, fills and returns a 0-terminated string from the printf style
2679  * @format string and corresponding arguments.
2680  *
2681  * See gst_info_vasprintf() for when this function is required.
2682  *
2683  * Free with g_free().
2684  *
2685  * Returns: (nullable): a newly allocated null terminated string or %NULL on any error
2686  *
2687  * Since: 1.8
2688  */
2689 gchar *
gst_info_strdup_printf(const gchar * format,...)2690 gst_info_strdup_printf (const gchar * format, ...)
2691 {
2692   gchar *ret;
2693   va_list args;
2694 
2695   va_start (args, format);
2696   ret = gst_info_strdup_vprintf (format, args);
2697   va_end (args);
2698 
2699   return ret;
2700 }
2701 
2702 /**
2703  * gst_print:
2704  * @format: a printf style format string
2705  * @...: the printf arguments for @format
2706  *
2707  * Outputs a formatted message via the GLib print handler. The default print
2708  * handler simply outputs the message to stdout.
2709  *
2710  * This function will not append a new-line character at the end, unlike
2711  * gst_println() which will.
2712  *
2713  * All strings must be in ASCII or UTF-8 encoding.
2714  *
2715  * This function differs from g_print() in that it supports all the additional
2716  * printf specifiers that are supported by GStreamer's debug logging system,
2717  * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2718  *
2719  * This function is primarily for printing debug output.
2720  *
2721  * Since: 1.12
2722  */
2723 void
gst_print(const gchar * format,...)2724 gst_print (const gchar * format, ...)
2725 {
2726   va_list args;
2727   gchar *str;
2728 
2729   va_start (args, format);
2730   str = gst_info_strdup_vprintf (format, args);
2731   va_end (args);
2732 
2733 #ifdef G_OS_WIN32
2734   G_LOCK (win_print_mutex);
2735 #endif
2736 
2737   g_print ("%s", str);
2738 
2739 #ifdef G_OS_WIN32
2740   G_UNLOCK (win_print_mutex);
2741 #endif
2742   g_free (str);
2743 }
2744 
2745 /**
2746  * gst_println:
2747  * @format: a printf style format string
2748  * @...: the printf arguments for @format
2749  *
2750  * Outputs a formatted message via the GLib print handler. The default print
2751  * handler simply outputs the message to stdout.
2752  *
2753  * This function will append a new-line character at the end, unlike
2754  * gst_print() which will not.
2755  *
2756  * All strings must be in ASCII or UTF-8 encoding.
2757  *
2758  * This function differs from g_print() in that it supports all the additional
2759  * printf specifiers that are supported by GStreamer's debug logging system,
2760  * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2761  *
2762  * This function is primarily for printing debug output.
2763  *
2764  * Since: 1.12
2765  */
2766 void
gst_println(const gchar * format,...)2767 gst_println (const gchar * format, ...)
2768 {
2769   va_list args;
2770   gchar *str;
2771 
2772   va_start (args, format);
2773   str = gst_info_strdup_vprintf (format, args);
2774   va_end (args);
2775 
2776 #ifdef G_OS_WIN32
2777   G_LOCK (win_print_mutex);
2778 #endif
2779 
2780   g_print ("%s\n", str);
2781 
2782 #ifdef G_OS_WIN32
2783   G_UNLOCK (win_print_mutex);
2784 #endif
2785   g_free (str);
2786 }
2787 
2788 /**
2789  * gst_printerr:
2790  * @format: a printf style format string
2791  * @...: the printf arguments for @format
2792  *
2793  * Outputs a formatted message via the GLib error message handler. The default
2794  * handler simply outputs the message to stderr.
2795  *
2796  * This function will not append a new-line character at the end, unlike
2797  * gst_printerrln() which will.
2798  *
2799  * All strings must be in ASCII or UTF-8 encoding.
2800  *
2801  * This function differs from g_printerr() in that it supports the additional
2802  * printf specifiers that are supported by GStreamer's debug logging system,
2803  * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2804  *
2805  * This function is primarily for printing debug output.
2806  *
2807  * Since: 1.12
2808  */
2809 void
gst_printerr(const gchar * format,...)2810 gst_printerr (const gchar * format, ...)
2811 {
2812   va_list args;
2813   gchar *str;
2814 
2815   va_start (args, format);
2816   str = gst_info_strdup_vprintf (format, args);
2817   va_end (args);
2818 
2819 #ifdef G_OS_WIN32
2820   G_LOCK (win_print_mutex);
2821 #endif
2822 
2823   g_printerr ("%s", str);
2824 
2825 #ifdef G_OS_WIN32
2826   G_UNLOCK (win_print_mutex);
2827 #endif
2828   g_free (str);
2829 }
2830 
2831 /**
2832  * gst_printerrln:
2833  * @format: a printf style format string
2834  * @...: the printf arguments for @format
2835  *
2836  * Outputs a formatted message via the GLib error message handler. The default
2837  * handler simply outputs the message to stderr.
2838  *
2839  * This function will append a new-line character at the end, unlike
2840  * gst_printerr() which will not.
2841  *
2842  * All strings must be in ASCII or UTF-8 encoding.
2843  *
2844  * This function differs from g_printerr() in that it supports the additional
2845  * printf specifiers that are supported by GStreamer's debug logging system,
2846  * such as #GST_PTR_FORMAT and #GST_SEGMENT_FORMAT.
2847  *
2848  * This function is primarily for printing debug output.
2849  *
2850  * Since: 1.12
2851  */
2852 void
gst_printerrln(const gchar * format,...)2853 gst_printerrln (const gchar * format, ...)
2854 {
2855   va_list args;
2856   gchar *str;
2857 
2858   va_start (args, format);
2859   str = gst_info_strdup_vprintf (format, args);
2860   va_end (args);
2861 
2862 #ifdef G_OS_WIN32
2863   G_LOCK (win_print_mutex);
2864 #endif
2865 
2866   g_printerr ("%s\n", str);
2867 
2868 #ifdef G_OS_WIN32
2869   G_UNLOCK (win_print_mutex);
2870 #endif
2871   g_free (str);
2872 }
2873 
2874 #ifdef HAVE_UNWIND
2875 #ifdef HAVE_DW
2876 static gboolean
append_debug_info(GString * trace,Dwfl * dwfl,const void * ip)2877 append_debug_info (GString * trace, Dwfl * dwfl, const void *ip)
2878 {
2879   Dwfl_Line *line;
2880   Dwarf_Addr addr;
2881   Dwfl_Module *module;
2882   const gchar *function_name;
2883 
2884   addr = (uintptr_t) ip;
2885   module = dwfl_addrmodule (dwfl, addr);
2886   function_name = dwfl_module_addrname (module, addr);
2887 
2888   g_string_append_printf (trace, "%s (", function_name ? function_name : "??");
2889 
2890   line = dwfl_getsrc (dwfl, addr);
2891   if (line != NULL) {
2892     gint nline;
2893     Dwarf_Addr addr;
2894     const gchar *filename = dwfl_lineinfo (line, &addr,
2895         &nline, NULL, NULL, NULL);
2896 
2897     g_string_append_printf (trace, "%s:%d", strrchr (filename,
2898             G_DIR_SEPARATOR) + 1, nline);
2899   } else {
2900     const gchar *eflfile = NULL;
2901 
2902     dwfl_module_info (module, NULL, NULL, NULL, NULL, NULL, &eflfile, NULL);
2903     g_string_append_printf (trace, "%s:%p", eflfile ? eflfile : "??", ip);
2904   }
2905 
2906   return TRUE;
2907 }
2908 #endif /* HAVE_DW */
2909 
2910 static gchar *
generate_unwind_trace(GstStackTraceFlags flags)2911 generate_unwind_trace (GstStackTraceFlags flags)
2912 {
2913   gint unret;
2914   unw_context_t uc;
2915   unw_cursor_t cursor;
2916   gboolean use_libunwind = TRUE;
2917   GString *trace = g_string_new (NULL);
2918 
2919 #ifdef HAVE_DW
2920   Dwfl *dwfl = NULL;
2921 
2922   if ((flags & GST_STACK_TRACE_SHOW_FULL)) {
2923     dwfl = get_global_dwfl ();
2924     if (G_UNLIKELY (dwfl == NULL)) {
2925       GST_WARNING ("Failed to initialize dwlf");
2926       goto done;
2927     }
2928     GST_DWFL_LOCK ();
2929   }
2930 #endif /* HAVE_DW */
2931 
2932   unret = unw_getcontext (&uc);
2933   if (unret) {
2934     GST_DEBUG ("Could not get libunwind context (%d)", unret);
2935 
2936     goto done;
2937   }
2938   unret = unw_init_local (&cursor, &uc);
2939   if (unret) {
2940     GST_DEBUG ("Could not init libunwind context (%d)", unret);
2941 
2942     goto done;
2943   }
2944 #ifdef HAVE_DW
2945   /* Due to plugins being loaded, mapping of process might have changed,
2946    * so always scan it. */
2947   if (dwfl_linux_proc_report (dwfl, getpid ()) != 0)
2948     goto done;
2949 #endif
2950 
2951   while (unw_step (&cursor) > 0) {
2952 #ifdef HAVE_DW
2953     if (dwfl) {
2954       unw_word_t ip;
2955 
2956       unret = unw_get_reg (&cursor, UNW_REG_IP, &ip);
2957       if (unret) {
2958         GST_DEBUG ("libunwind could not read frame info (%d)", unret);
2959 
2960         goto done;
2961       }
2962 
2963       if (append_debug_info (trace, dwfl, (void *) (ip - 4))) {
2964         use_libunwind = FALSE;
2965         g_string_append (trace, ")\n");
2966       }
2967     }
2968 #endif /* HAVE_DW */
2969 
2970     if (use_libunwind) {
2971       char name[32];
2972 
2973       unw_word_t offset = 0;
2974       unw_get_proc_name (&cursor, name, sizeof (name), &offset);
2975       g_string_append_printf (trace, "%s (0x%" G_GSIZE_FORMAT ")\n", name,
2976           (gsize) offset);
2977     }
2978   }
2979 
2980 done:
2981 #ifdef HAVE_DW
2982   if (dwfl)
2983     GST_DWFL_UNLOCK ();
2984 #endif
2985 
2986   return g_string_free (trace, FALSE);
2987 }
2988 
2989 #endif /* HAVE_UNWIND */
2990 
2991 #ifdef HAVE_BACKTRACE
2992 static gchar *
generate_backtrace_trace(void)2993 generate_backtrace_trace (void)
2994 {
2995   int j, nptrs;
2996   void *buffer[BT_BUF_SIZE];
2997   char **strings;
2998   GString *trace;
2999 
3000   nptrs = backtrace (buffer, BT_BUF_SIZE);
3001 
3002   strings = backtrace_symbols (buffer, nptrs);
3003 
3004   if (!strings)
3005     return NULL;
3006 
3007   trace = g_string_new (NULL);
3008 
3009   for (j = 0; j < nptrs; j++)
3010     g_string_append_printf (trace, "%s\n", strings[j]);
3011 
3012   free (strings);
3013 
3014   return g_string_free (trace, FALSE);
3015 }
3016 #else
3017 #define generate_backtrace_trace() NULL
3018 #endif /* HAVE_BACKTRACE */
3019 
3020 #ifdef HAVE_DBGHELP
3021 /* *INDENT-OFF* */
3022 static struct
3023 {
3024   DWORD (WINAPI * pSymSetOptions) (DWORD SymOptions);
3025   BOOL  (WINAPI * pSymInitialize) (HANDLE hProcess,
3026                                    PCSTR UserSearchPath,
3027                                    BOOL fInvadeProcess);
3028   BOOL  (WINAPI * pStackWalk64)   (DWORD MachineType,
3029                                    HANDLE hProcess,
3030                                    HANDLE hThread,
3031                                    LPSTACKFRAME64 StackFrame,
3032                                    PVOID ContextRecord,
3033                                    PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
3034                                    PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
3035                                    PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
3036                                    PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress);
3037   PVOID (WINAPI * pSymFunctionTableAccess64) (HANDLE hProcess,
3038                                               DWORD64 AddrBase);
3039   DWORD64 (WINAPI * pSymGetModuleBase64) (HANDLE hProcess,
3040                                           DWORD64 qwAddr);
3041   BOOL (WINAPI * pSymFromAddr) (HANDLE hProcess,
3042                                 DWORD64 Address,
3043                                 PDWORD64 Displacement,
3044                                 PSYMBOL_INFO Symbol);
3045   BOOL (WINAPI * pSymGetModuleInfo64) (HANDLE hProcess,
3046                                        DWORD64 qwAddr,
3047                                        PIMAGEHLP_MODULE64 ModuleInfo);
3048   BOOL (WINAPI * pSymGetLineFromAddr64) (HANDLE hProcess,
3049                                          DWORD64 qwAddr,
3050                                          PDWORD pdwDisplacement,
3051                                          PIMAGEHLP_LINE64 Line64);
3052 } dbg_help_vtable = { NULL,};
3053 /* *INDENT-ON* */
3054 
3055 static GModule *dbg_help_module = NULL;
3056 
3057 static gboolean
dbghelp_load_symbol(const gchar * symbol_name,gpointer * symbol)3058 dbghelp_load_symbol (const gchar * symbol_name, gpointer * symbol)
3059 {
3060   if (dbg_help_module &&
3061       !g_module_symbol (dbg_help_module, symbol_name, symbol)) {
3062     GST_WARNING ("Cannot load %s symbol", symbol_name);
3063     g_module_close (dbg_help_module);
3064     dbg_help_module = NULL;
3065   }
3066 
3067   return ! !dbg_help_module;
3068 }
3069 
3070 static gboolean
dbghelp_initialize_symbols(HANDLE process)3071 dbghelp_initialize_symbols (HANDLE process)
3072 {
3073   static gsize initialization_value = 0;
3074 
3075   if (g_once_init_enter (&initialization_value)) {
3076     GST_INFO ("Initializing Windows symbol handler");
3077 
3078     dbg_help_module = g_module_open ("dbghelp.dll", G_MODULE_BIND_LAZY);
3079     dbghelp_load_symbol ("SymSetOptions",
3080         (gpointer *) & dbg_help_vtable.pSymSetOptions);
3081     dbghelp_load_symbol ("SymInitialize",
3082         (gpointer *) & dbg_help_vtable.pSymInitialize);
3083     dbghelp_load_symbol ("StackWalk64",
3084         (gpointer *) & dbg_help_vtable.pStackWalk64);
3085     dbghelp_load_symbol ("SymFunctionTableAccess64",
3086         (gpointer *) & dbg_help_vtable.pSymFunctionTableAccess64);
3087     dbghelp_load_symbol ("SymGetModuleBase64",
3088         (gpointer *) & dbg_help_vtable.pSymGetModuleBase64);
3089     dbghelp_load_symbol ("SymFromAddr",
3090         (gpointer *) & dbg_help_vtable.pSymFromAddr);
3091     dbghelp_load_symbol ("SymGetModuleInfo64",
3092         (gpointer *) & dbg_help_vtable.pSymGetModuleInfo64);
3093     dbghelp_load_symbol ("SymGetLineFromAddr64",
3094         (gpointer *) & dbg_help_vtable.pSymGetLineFromAddr64);
3095 
3096     if (dbg_help_module) {
3097       dbg_help_vtable.pSymSetOptions (SYMOPT_LOAD_LINES);
3098       dbg_help_vtable.pSymInitialize (process, NULL, TRUE);
3099       GST_INFO ("Initialized Windows symbol handler");
3100     }
3101 
3102     g_once_init_leave (&initialization_value, 1);
3103   }
3104 
3105   return ! !dbg_help_module;
3106 }
3107 
3108 static gchar *
generate_dbghelp_trace(void)3109 generate_dbghelp_trace (void)
3110 {
3111   HANDLE process = GetCurrentProcess ();
3112   HANDLE thread = GetCurrentThread ();
3113   IMAGEHLP_MODULE64 module_info;
3114   DWORD machine;
3115   CONTEXT context;
3116   STACKFRAME64 frame = { 0 };
3117   PVOID save_context;
3118   GString *trace = NULL;
3119 
3120   if (!dbghelp_initialize_symbols (process))
3121     return NULL;
3122 
3123   memset (&context, 0, sizeof (CONTEXT));
3124   context.ContextFlags = CONTEXT_FULL;
3125 
3126   RtlCaptureContext (&context);
3127 
3128   frame.AddrPC.Mode = AddrModeFlat;
3129   frame.AddrStack.Mode = AddrModeFlat;
3130   frame.AddrFrame.Mode = AddrModeFlat;
3131 
3132 #if (defined _M_IX86)
3133   machine = IMAGE_FILE_MACHINE_I386;
3134   frame.AddrFrame.Offset = context.Ebp;
3135   frame.AddrPC.Offset = context.Eip;
3136   frame.AddrStack.Offset = context.Esp;
3137 #elif (defined _M_X64)
3138   machine = IMAGE_FILE_MACHINE_AMD64;
3139   frame.AddrFrame.Offset = context.Rbp;
3140   frame.AddrPC.Offset = context.Rip;
3141   frame.AddrStack.Offset = context.Rsp;
3142 #else
3143   return NULL;
3144 #endif
3145 
3146   trace = g_string_new (NULL);
3147 
3148   module_info.SizeOfStruct = sizeof (module_info);
3149   save_context = (machine == IMAGE_FILE_MACHINE_I386) ? NULL : &context;
3150 
3151   while (TRUE) {
3152     char buffer[sizeof (SYMBOL_INFO) + MAX_SYM_NAME * sizeof (TCHAR)];
3153     PSYMBOL_INFO symbol = (PSYMBOL_INFO) buffer;
3154     IMAGEHLP_LINE64 line;
3155     DWORD displacement = 0;
3156 
3157     symbol->SizeOfStruct = sizeof (SYMBOL_INFO);
3158     symbol->MaxNameLen = MAX_SYM_NAME;
3159 
3160     line.SizeOfStruct = sizeof (line);
3161 
3162     if (!dbg_help_vtable.pStackWalk64 (machine, process, thread, &frame,
3163             save_context, 0, dbg_help_vtable.pSymFunctionTableAccess64,
3164             dbg_help_vtable.pSymGetModuleBase64, 0)) {
3165       break;
3166     }
3167 
3168     if (dbg_help_vtable.pSymFromAddr (process, frame.AddrPC.Offset, 0, symbol))
3169       g_string_append_printf (trace, "%s ", symbol->Name);
3170     else
3171       g_string_append (trace, "?? ");
3172 
3173     if (dbg_help_vtable.pSymGetLineFromAddr64 (process, frame.AddrPC.Offset,
3174             &displacement, &line))
3175       g_string_append_printf (trace, "(%s:%lu)", line.FileName,
3176           line.LineNumber);
3177     else if (dbg_help_vtable.pSymGetModuleInfo64 (process, frame.AddrPC.Offset,
3178             &module_info))
3179       g_string_append_printf (trace, "(%s)", module_info.ImageName);
3180     else
3181       g_string_append_printf (trace, "(%s)", "??");
3182 
3183     g_string_append (trace, "\n");
3184   }
3185 
3186   return g_string_free (trace, FALSE);
3187 }
3188 #endif /* HAVE_DBGHELP */
3189 
3190 /**
3191  * gst_debug_get_stack_trace:
3192  * @flags: A set of #GstStackTraceFlags to determine how the stack trace should
3193  * look like. Pass #GST_STACK_TRACE_SHOW_NONE to retrieve a minimal backtrace.
3194  *
3195  * Returns: (nullable): a stack trace, if libunwind or glibc backtrace are
3196  * present, else %NULL.
3197  *
3198  * Since: 1.12
3199  */
3200 gchar *
gst_debug_get_stack_trace(GstStackTraceFlags flags)3201 gst_debug_get_stack_trace (GstStackTraceFlags flags)
3202 {
3203   gchar *trace = NULL;
3204 #ifdef HAVE_BACKTRACE
3205   gboolean have_backtrace = TRUE;
3206 #else
3207   gboolean have_backtrace = FALSE;
3208 #endif
3209 
3210 #ifdef HAVE_UNWIND
3211   if ((flags & GST_STACK_TRACE_SHOW_FULL) || !have_backtrace)
3212     trace = generate_unwind_trace (flags);
3213 #elif defined(HAVE_DBGHELP)
3214   trace = generate_dbghelp_trace ();
3215 #endif
3216 
3217   if (trace)
3218     return trace;
3219   else if (have_backtrace)
3220     return generate_backtrace_trace ();
3221 
3222   return NULL;
3223 }
3224 
3225 /**
3226  * gst_debug_print_stack_trace:
3227  *
3228  * If libunwind, glibc backtrace or DbgHelp are present
3229  * a stack trace is printed.
3230  */
3231 void
gst_debug_print_stack_trace(void)3232 gst_debug_print_stack_trace (void)
3233 {
3234   gchar *trace = gst_debug_get_stack_trace (GST_STACK_TRACE_SHOW_FULL);
3235 
3236   if (trace) {
3237 #ifdef G_OS_WIN32
3238     G_LOCK (win_print_mutex);
3239 #endif
3240 
3241     g_print ("%s\n", trace);
3242 
3243 #ifdef G_OS_WIN32
3244     G_UNLOCK (win_print_mutex);
3245 #endif
3246   }
3247 
3248   g_free (trace);
3249 }
3250 
3251 #ifndef GST_DISABLE_GST_DEBUG
3252 typedef struct
3253 {
3254   guint max_size_per_thread;
3255   guint thread_timeout;
3256   GQueue threads;
3257   GHashTable *thread_index;
3258 } GstRingBufferLogger;
3259 
3260 typedef struct
3261 {
3262   GList *link;
3263   gint64 last_use;
3264   GThread *thread;
3265 
3266   GQueue log;
3267   gsize log_size;
3268 } GstRingBufferLog;
3269 
3270 G_LOCK_DEFINE_STATIC (ring_buffer_logger);
3271 static GstRingBufferLogger *ring_buffer_logger = NULL;
3272 
3273 static void
gst_ring_buffer_logger_log(GstDebugCategory * category,GstDebugLevel level,const gchar * file,const gchar * function,gint line,GObject * object,GstDebugMessage * message,gpointer user_data)3274 gst_ring_buffer_logger_log (GstDebugCategory * category,
3275     GstDebugLevel level,
3276     const gchar * file,
3277     const gchar * function,
3278     gint line, GObject * object, GstDebugMessage * message, gpointer user_data)
3279 {
3280   GstRingBufferLogger *logger = user_data;
3281   gint pid;
3282   GThread *thread;
3283   GstClockTime elapsed;
3284   gchar *obj = NULL;
3285   gchar c;
3286   gchar *output;
3287   gsize output_len;
3288   GstRingBufferLog *log;
3289   gint64 now = g_get_monotonic_time ();
3290   const gchar *message_str = gst_debug_message_get (message);
3291 
3292   /* __FILE__ might be a file name or an absolute path or a
3293    * relative path, irrespective of the exact compiler used,
3294    * in which case we want to shorten it to the filename for
3295    * readability. */
3296   c = file[0];
3297   if (c == '.' || c == '/' || c == '\\' || (c != '\0' && file[1] == ':')) {
3298     file = gst_path_basename (file);
3299   }
3300 
3301   if (object) {
3302     obj = gst_debug_print_object (object);
3303   } else {
3304     obj = (gchar *) "";
3305   }
3306 
3307   elapsed = GST_CLOCK_DIFF (_priv_gst_start_time, gst_util_get_timestamp ());
3308   pid = getpid ();
3309   thread = g_thread_self ();
3310 
3311   /* no color, all platforms */
3312 #define PRINT_FMT " "PID_FMT" "PTR_FMT" %s "CAT_FMT" %s\n"
3313   output =
3314       g_strdup_printf ("%" GST_TIME_FORMAT PRINT_FMT, GST_TIME_ARGS (elapsed),
3315       pid, thread, gst_debug_level_get_name (level),
3316       gst_debug_category_get_name (category), file, line, function, obj,
3317       message_str);
3318 #undef PRINT_FMT
3319 
3320   output_len = strlen (output);
3321 
3322   if (object != NULL)
3323     g_free (obj);
3324 
3325   G_LOCK (ring_buffer_logger);
3326 
3327   if (logger->thread_timeout > 0) {
3328     gchar *buf;
3329 
3330     /* Remove all threads that saw no output since thread_timeout seconds.
3331      * By construction these are all at the tail of the queue, and the queue
3332      * is ordered by last use, so we just need to look at the tail.
3333      */
3334     while (logger->threads.tail) {
3335       log = logger->threads.tail->data;
3336       if (log->last_use + logger->thread_timeout * G_USEC_PER_SEC >= now)
3337         break;
3338 
3339       g_hash_table_remove (logger->thread_index, log->thread);
3340       while ((buf = g_queue_pop_head (&log->log)))
3341         g_free (buf);
3342       g_free (log);
3343       g_queue_pop_tail (&logger->threads);
3344     }
3345   }
3346 
3347   /* Get logger for this thread, and put it back at the
3348    * head of the threads queue */
3349   log = g_hash_table_lookup (logger->thread_index, thread);
3350   if (!log) {
3351     log = g_new0 (GstRingBufferLog, 1);
3352     g_queue_init (&log->log);
3353     log->log_size = 0;
3354     g_queue_push_head (&logger->threads, log);
3355     log->link = logger->threads.head;
3356     log->thread = thread;
3357     g_hash_table_insert (logger->thread_index, thread, log);
3358   } else {
3359     g_queue_unlink (&logger->threads, log->link);
3360     g_queue_push_head_link (&logger->threads, log->link);
3361   }
3362   log->last_use = now;
3363 
3364   if (output_len < logger->max_size_per_thread) {
3365     gchar *buf;
3366 
3367     /* While using a GQueue here is not the most efficient thing to do, we
3368      * have to allocate a string for every output anyway and could just store
3369      * that instead of copying it to an actual ringbuffer.
3370      * Better than GQueue would be GstQueueArray, but that one is in
3371      * libgstbase and we can't use it here. That one allocation will not make
3372      * much of a difference anymore, considering the number of allocations
3373      * needed to get to this point...
3374      */
3375     while (log->log_size + output_len > logger->max_size_per_thread) {
3376       buf = g_queue_pop_head (&log->log);
3377       log->log_size -= strlen (buf);
3378       g_free (buf);
3379     }
3380     g_queue_push_tail (&log->log, output);
3381     log->log_size += output_len;
3382   } else {
3383     gchar *buf;
3384 
3385     /* Can't really write anything as the line is bigger than the maximum
3386      * allowed log size already, so just remove everything */
3387 
3388     while ((buf = g_queue_pop_head (&log->log)))
3389       g_free (buf);
3390     g_free (output);
3391     log->log_size = 0;
3392   }
3393 
3394   G_UNLOCK (ring_buffer_logger);
3395 }
3396 
3397 /**
3398  * gst_debug_ring_buffer_logger_get_logs:
3399  *
3400  * Fetches the current logs per thread from the ring buffer logger. See
3401  * gst_debug_add_ring_buffer_logger() for details.
3402  *
3403  * Returns: (transfer full) (array zero-terminated): NULL-terminated array of
3404  * strings with the debug output per thread
3405  *
3406  * Since: 1.14
3407  */
3408 gchar **
gst_debug_ring_buffer_logger_get_logs(void)3409 gst_debug_ring_buffer_logger_get_logs (void)
3410 {
3411   gchar **logs, **tmp;
3412   GList *l;
3413 
3414   g_return_val_if_fail (ring_buffer_logger != NULL, NULL);
3415 
3416   G_LOCK (ring_buffer_logger);
3417 
3418   tmp = logs = g_new0 (gchar *, ring_buffer_logger->threads.length + 1);
3419   for (l = ring_buffer_logger->threads.head; l; l = l->next) {
3420     GstRingBufferLog *log = l->data;
3421     GList *l;
3422     gchar *p;
3423     gsize len;
3424 
3425     *tmp = p = g_new0 (gchar, log->log_size + 1);
3426 
3427     for (l = log->log.head; l; l = l->next) {
3428       len = strlen (l->data);
3429       memcpy (p, l->data, len);
3430       p += len;
3431     }
3432 
3433     tmp++;
3434   }
3435 
3436   G_UNLOCK (ring_buffer_logger);
3437 
3438   return logs;
3439 }
3440 
3441 static void
gst_ring_buffer_logger_free(GstRingBufferLogger * logger)3442 gst_ring_buffer_logger_free (GstRingBufferLogger * logger)
3443 {
3444   G_LOCK (ring_buffer_logger);
3445   if (ring_buffer_logger == logger) {
3446     GstRingBufferLog *log;
3447 
3448     while ((log = g_queue_pop_head (&logger->threads))) {
3449       gchar *buf;
3450       while ((buf = g_queue_pop_head (&log->log)))
3451         g_free (buf);
3452       g_free (log);
3453     }
3454 
3455     g_hash_table_unref (logger->thread_index);
3456 
3457     g_free (logger);
3458     ring_buffer_logger = NULL;
3459   }
3460   G_UNLOCK (ring_buffer_logger);
3461 }
3462 
3463 /**
3464  * gst_debug_add_ring_buffer_logger:
3465  * @max_size_per_thread: Maximum size of log per thread in bytes
3466  * @thread_timeout: Timeout for threads in seconds
3467  *
3468  * Adds a memory ringbuffer based debug logger that stores up to
3469  * @max_size_per_thread bytes of logs per thread and times out threads after
3470  * @thread_timeout seconds of inactivity.
3471  *
3472  * Logs can be fetched with gst_debug_ring_buffer_logger_get_logs() and the
3473  * logger can be removed again with gst_debug_remove_ring_buffer_logger().
3474  * Only one logger at a time is possible.
3475  *
3476  * Since: 1.14
3477  */
3478 void
gst_debug_add_ring_buffer_logger(guint max_size_per_thread,guint thread_timeout)3479 gst_debug_add_ring_buffer_logger (guint max_size_per_thread,
3480     guint thread_timeout)
3481 {
3482   GstRingBufferLogger *logger;
3483 
3484   G_LOCK (ring_buffer_logger);
3485 
3486   if (ring_buffer_logger) {
3487     g_warn_if_reached ();
3488     G_UNLOCK (ring_buffer_logger);
3489     return;
3490   }
3491 
3492   logger = ring_buffer_logger = g_new0 (GstRingBufferLogger, 1);
3493 
3494   logger->max_size_per_thread = max_size_per_thread;
3495   logger->thread_timeout = thread_timeout;
3496   logger->thread_index = g_hash_table_new (g_direct_hash, g_direct_equal);
3497   g_queue_init (&logger->threads);
3498 
3499   gst_debug_add_log_function (gst_ring_buffer_logger_log, logger,
3500       (GDestroyNotify) gst_ring_buffer_logger_free);
3501   G_UNLOCK (ring_buffer_logger);
3502 }
3503 
3504 /**
3505  * gst_debug_remove_ring_buffer_logger:
3506  *
3507  * Removes any previously added ring buffer logger with
3508  * gst_debug_add_ring_buffer_logger().
3509  *
3510  * Since: 1.14
3511  */
3512 void
gst_debug_remove_ring_buffer_logger(void)3513 gst_debug_remove_ring_buffer_logger (void)
3514 {
3515   gst_debug_remove_log_function (gst_ring_buffer_logger_log);
3516 }
3517 
3518 #else /* GST_DISABLE_GST_DEBUG */
3519 #ifndef GST_REMOVE_DISABLED
3520 
3521 gchar **
gst_debug_ring_buffer_logger_get_logs(void)3522 gst_debug_ring_buffer_logger_get_logs (void)
3523 {
3524   return NULL;
3525 }
3526 
3527 void
gst_debug_add_ring_buffer_logger(guint max_size_per_thread,guint thread_timeout)3528 gst_debug_add_ring_buffer_logger (guint max_size_per_thread,
3529     guint thread_timeout)
3530 {
3531 }
3532 
3533 void
gst_debug_remove_ring_buffer_logger(void)3534 gst_debug_remove_ring_buffer_logger (void)
3535 {
3536 }
3537 
3538 #endif /* GST_REMOVE_DISABLED */
3539 #endif /* GST_DISABLE_GST_DEBUG */
3540