]> git.sesse.net Git - vlc/blob - src/misc/messages.c
Fix message leak
[vlc] / src / misc / messages.c
1 /*****************************************************************************
2  * messages.c: messages interface
3  * This library provides an interface to the message queue to be used by other
4  * modules, especially intf modules. See vlc_config.h for output configuration.
5  *****************************************************************************
6  * Copyright (C) 1998-2005 the VideoLAN team
7  * $Id$
8  *
9  * Authors: Vincent Seguin <seguin@via.ecp.fr>
10  *          Samuel Hocevar <sam@zoy.org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #endif
34
35 #include <vlc_common.h>
36
37 #include <stdarg.h>                                       /* va_list for BSD */
38
39 #ifdef HAVE_FCNTL_H
40 #   include <fcntl.h>                  /* O_CREAT, O_TRUNC, O_WRONLY, O_SYNC */
41 #endif
42
43 #include <errno.h>                                                  /* errno */
44
45 #ifdef WIN32
46 #   include <vlc_network.h>          /* 'net_strerror' and 'WSAGetLastError' */
47 #endif
48
49 #ifdef HAVE_UNISTD_H
50 #   include <unistd.h>                                   /* close(), write() */
51 #endif
52
53 #include <assert.h>
54
55 #include <vlc_charset.h>
56 #include "../libvlc.h"
57
58 typedef struct
59 {
60     int i_code;
61     char * psz_message;
62 } msg_context_t;
63
64 static vlc_threadvar_t msg_context;
65 static uintptr_t banks = 0;
66
67 /*****************************************************************************
68  * Local macros
69  *****************************************************************************/
70 #if defined(HAVE_VA_COPY)
71 #   define vlc_va_copy(dest,src) va_copy(dest,src)
72 #elif defined(HAVE___VA_COPY)
73 #   define vlc_va_copy(dest,src) __va_copy(dest,src)
74 #else
75 #   define vlc_va_copy(dest,src) (dest)=(src)
76 #endif
77
78 #define QUEUE priv->msg_bank
79 static inline msg_bank_t *libvlc_bank (libvlc_int_t *inst)
80 {
81     return &(libvlc_priv (inst))->msg_bank;
82 }
83
84 /*****************************************************************************
85  * Local prototypes
86  *****************************************************************************/
87 static void QueueMsg ( vlc_object_t *, int, const char *,
88                        const char *, va_list );
89 static void PrintMsg ( vlc_object_t *, msg_item_t * );
90
91 static vlc_mutex_t msg_stack_lock = VLC_STATIC_MUTEX;
92
93 /**
94  * Initialize messages queues
95  * This function initializes all message queues
96  */
97 void msg_Create (libvlc_int_t *p_libvlc)
98 {
99     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
100     msg_bank_t *bank = libvlc_bank (p_libvlc);
101
102     vlc_mutex_init (&bank->lock);
103     vlc_cond_init (&bank->wait);
104     vlc_dictionary_init( &priv->msg_enabled_objects, 0 );
105     priv->msg_all_objects_enabled = true;
106
107     QUEUE.i_sub = 0;
108     QUEUE.pp_sub = NULL;
109
110 #ifdef UNDER_CE
111     QUEUE.logfile =
112         CreateFile( L"vlc-log.txt", GENERIC_WRITE,
113                     FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
114                     CREATE_ALWAYS, 0, NULL );
115     SetFilePointer( QUEUE.logfile, 0, NULL, FILE_END );
116 #endif
117
118     vlc_mutex_lock( &msg_stack_lock );
119     if( banks++ == 0 )
120         vlc_threadvar_create( &msg_context, NULL );
121     vlc_mutex_unlock( &msg_stack_lock );
122 }
123
124 /**
125  * Object Printing selection
126  */
127 static void const * kObjectPrintingEnabled = &kObjectPrintingEnabled;
128 static void const * kObjectPrintingDisabled = &kObjectPrintingDisabled;
129
130 void __msg_EnableObjectPrinting (vlc_object_t *p_this, char * psz_object)
131 {
132     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
133     vlc_mutex_lock( &QUEUE.lock );
134     if( !strcmp(psz_object, "all") )
135         priv->msg_all_objects_enabled = true;
136     else
137         vlc_dictionary_insert( &priv->msg_enabled_objects, psz_object, (void *)kObjectPrintingEnabled );
138     vlc_mutex_unlock( &QUEUE.lock );
139 }
140
141 void __msg_DisableObjectPrinting (vlc_object_t *p_this, char * psz_object)
142 {
143     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
144     vlc_mutex_lock( &QUEUE.lock );
145     if( !strcmp(psz_object, "all") )
146         priv->msg_all_objects_enabled = false;
147     else
148         vlc_dictionary_insert( &priv->msg_enabled_objects, psz_object, (void *)kObjectPrintingDisabled );
149     vlc_mutex_unlock( &QUEUE.lock );
150 }
151
152 /**
153  * Destroy the message queues
154  *
155  * This functions prints all messages remaining in the queues,
156  * then frees all the allocated ressources
157  * No other messages interface functions should be called after this one.
158  */
159 void msg_Destroy (libvlc_int_t *p_libvlc)
160 {
161     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
162     msg_bank_t *bank = libvlc_bank (p_libvlc);
163
164     if( QUEUE.i_sub )
165         msg_Err( p_libvlc, "stale interface subscribers (VLC might crash)" );
166
167     vlc_mutex_lock( &msg_stack_lock );
168     if( --banks == 0 )
169         vlc_threadvar_delete( &msg_context );
170     vlc_mutex_unlock( &msg_stack_lock );
171
172 #ifdef UNDER_CE
173     CloseHandle( QUEUE.logfile );
174 #endif
175
176     vlc_dictionary_clear( &priv->msg_enabled_objects, NULL, NULL );
177
178     vlc_cond_destroy (&bank->wait);
179     vlc_mutex_destroy (&bank->lock);
180 }
181
182 struct msg_subscription_t
183 {
184     vlc_thread_t    thread;
185     libvlc_int_t   *instance;
186     msg_callback_t  func;
187     msg_cb_data_t  *opaque;
188     msg_item_t     *items[VLC_MSG_QSIZE];
189     unsigned        begin, end;
190     unsigned        overruns;
191 };
192
193 static void *msg_thread (void *data)
194 {
195     msg_subscription_t *sub = data;
196     msg_bank_t *bank = libvlc_bank (sub->instance);
197
198     vlc_mutex_lock (&bank->lock);
199     for (;;)
200     {
201         /* Wait for messages */
202         assert (sub->begin < VLC_MSG_QSIZE);
203         assert (sub->end < VLC_MSG_QSIZE);
204         while (sub->begin != sub->end)
205         {
206             msg_item_t *msg = sub->items[sub->begin];
207             unsigned overruns = sub->overruns;
208
209             if (++sub->begin == VLC_MSG_QSIZE)
210                 sub->begin = 0;
211             sub->overruns = 0;
212             vlc_mutex_unlock (&bank->lock);
213
214             sub->func (sub->opaque, msg, overruns);
215             msg_Release (msg);
216
217             vlc_mutex_lock (&bank->lock);
218         }
219
220         mutex_cleanup_push (&bank->lock);
221         vlc_cond_wait (&bank->wait, &bank->lock);
222         vlc_cleanup_pop ();
223     }
224     assert (0);
225 }
226
227 /**
228  * Subscribe to the message queue.
229  * Whenever a message is emitted, a callback will be called.
230  * Callback invocation are serialized within a subscription.
231  *
232  * @param instance LibVLC instance to get messages from
233  * @param cb callback function
234  * @param opaque data for the callback function
235  * @return a subscription pointer, or NULL in case of failure
236  */
237 msg_subscription_t *msg_Subscribe (libvlc_int_t *instance, msg_callback_t cb,
238                                    msg_cb_data_t *opaque)
239 {
240     msg_subscription_t *sub = malloc (sizeof (*sub));
241     if (sub == NULL)
242         return NULL;
243
244     sub->instance = instance;
245     sub->func = cb;
246     sub->opaque = opaque;
247     sub->begin = sub->end = sub->overruns = 0;
248
249     if (vlc_clone (&sub->thread, msg_thread, sub, VLC_THREAD_PRIORITY_LOW))
250     {
251         free (sub);
252         return NULL;
253     }
254
255     msg_bank_t *bank = libvlc_bank (instance);
256     vlc_mutex_lock (&bank->lock);
257     TAB_APPEND (bank->i_sub, bank->pp_sub, sub);
258     vlc_mutex_unlock (&bank->lock);
259
260     return sub;
261 }
262
263 /**
264  * Unsubscribe from the message queue.
265  * This function waits for the message callback to return if needed.
266  */
267 void msg_Unsubscribe (msg_subscription_t *sub)
268 {
269     msg_bank_t *bank = libvlc_bank (sub->instance);
270
271     /* TODO: flush support? */
272     vlc_cancel (sub->thread);
273     vlc_mutex_lock (&bank->lock);
274     TAB_REMOVE (bank->i_sub, bank->pp_sub, sub);
275     vlc_mutex_unlock (&bank->lock);
276
277     vlc_join (sub->thread, NULL);
278     free (sub);
279 }
280
281 /*****************************************************************************
282  * __msg_*: print a message
283  *****************************************************************************
284  * These functions queue a message for later printing.
285  *****************************************************************************/
286 void __msg_Generic( vlc_object_t *p_this, int i_type, const char *psz_module,
287                     const char *psz_format, ... )
288 {
289     va_list args;
290
291     va_start( args, psz_format );
292     QueueMsg( p_this, i_type, psz_module, psz_format, args );
293     va_end( args );
294 }
295
296 void __msg_GenericVa( vlc_object_t *p_this, int i_type, const char *psz_module,
297                       const char *psz_format, va_list args )
298 {
299     QueueMsg( p_this, i_type, psz_module, psz_format, args );
300 }
301
302 /**
303  * Destroys a message.
304  */
305 static void msg_Free (gc_object_t *gc)
306 {
307     msg_item_t *msg = vlc_priv (gc, msg_item_t);
308
309     free (msg->psz_module);
310     free (msg->psz_msg);
311     free (msg->psz_header);
312     free (msg);
313 }
314
315 /**
316  * Add a message to a queue
317  *
318  * This function provides basic functionnalities to other msg_* functions.
319  * It adds a message to a queue (after having printed all stored messages if it
320  * is full). If the message can't be converted to string in memory, it issues
321  * a warning.
322  */
323 static void QueueMsg( vlc_object_t *p_this, int i_type, const char *psz_module,
324                       const char *psz_format, va_list _args )
325 {
326     assert (p_this);
327     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
328     int         i_header_size;             /* Size of the additionnal header */
329     vlc_object_t *p_obj;
330     char *       psz_str = NULL;                 /* formatted message string */
331     char *       psz_header = NULL;
332     va_list      args;
333     msg_item_t * p_item = malloc (sizeof (*p_item));
334
335     if (p_item == NULL)
336         return; /* Uho! */
337
338     vlc_gc_init (p_item, msg_Free);
339     p_item->psz_module = p_item->psz_msg = p_item->psz_header = NULL;
340
341 #if !defined(HAVE_VASPRINTF) || defined(__APPLE__) || defined(SYS_BEOS)
342     int          i_size = strlen(psz_format) + INTF_MAX_MSG_SIZE;
343 #endif
344
345     if( p_this->i_flags & OBJECT_FLAGS_QUIET ||
346         (p_this->i_flags & OBJECT_FLAGS_NODBG && i_type == VLC_MSG_DBG) )
347         goto out;
348
349 #ifndef __GLIBC__
350     /* Expand %m to strerror(errno) - only once */
351     char buf[strlen( psz_format ) + 2001], *ptr;
352     strcpy( buf, psz_format );
353     ptr = (char*)buf;
354     psz_format = (const char*) buf;
355
356     for( ;; )
357     {
358         ptr = strchr( ptr, '%' );
359         if( ptr == NULL )
360             break;
361
362         if( ptr[1] == 'm' )
363         {
364             char errbuf[2001];
365             size_t errlen;
366
367 #ifndef WIN32
368             strerror_r( errno, errbuf, 1001 );
369 #else
370             int sockerr = WSAGetLastError( );
371             if( sockerr )
372             {
373                 strncpy( errbuf, net_strerror( sockerr ), 1001 );
374                 WSASetLastError( sockerr );
375             }
376             if ((sockerr == 0)
377              || (strcmp ("Unknown network stack error", errbuf) == 0))
378                 strncpy( errbuf, strerror( errno ), 1001 );
379 #endif
380             errbuf[1000] = 0;
381
382             /* Escape '%' from the error string */
383             for( char *percent = strchr( errbuf, '%' );
384                  percent != NULL;
385                  percent = strchr( percent + 2, '%' ) )
386             {
387                 memmove( percent + 1, percent, strlen( percent ) + 1 );
388             }
389
390             errlen = strlen( errbuf );
391             memmove( ptr + errlen, ptr + 2, strlen( ptr + 2 ) + 1 );
392             memcpy( ptr, errbuf, errlen );
393             break; /* Only once, so we don't overflow */
394         }
395
396         /* Looks for conversion specifier... */
397         do
398             ptr++;
399         while( *ptr && ( strchr( "diouxXeEfFgGaAcspn%", *ptr ) == NULL ) );
400         if( *ptr )
401             ptr++; /* ...and skip it */
402     }
403 #endif
404
405     /* Convert message to string  */
406 #if defined(HAVE_VASPRINTF) && !defined(__APPLE__) && !defined( SYS_BEOS )
407     vlc_va_copy( args, _args );
408     if( vasprintf( &psz_str, psz_format, args ) == -1 )
409         psz_str = NULL;
410     va_end( args );
411 #else
412     psz_str = (char*) malloc( i_size );
413 #endif
414
415     if( psz_str == NULL )
416     {
417         int canc = vlc_savecancel (); /* Do not print half of a message... */
418 #ifdef __GLIBC__
419         fprintf( stderr, "main warning: can't store message (%m): " );
420 #else
421         char psz_err[1001];
422 #ifndef WIN32
423         /* we're not using GLIBC, so we are sure that the error description
424          * will be stored in the buffer we provide to strerror_r() */
425         strerror_r( errno, psz_err, 1001 );
426 #else
427         strncpy( psz_err, strerror( errno ), 1001 );
428 #endif
429         psz_err[1000] = '\0';
430         fprintf( stderr, "main warning: can't store message (%s): ", psz_err );
431 #endif
432         vlc_va_copy( args, _args );
433         /* We should use utf8_vfprintf - but it calls malloc()... */
434         vfprintf( stderr, psz_format, args );
435         va_end( args );
436         fputs( "\n", stderr );
437         vlc_restorecancel (canc);
438         goto out;
439     }
440
441     i_header_size = 0;
442     p_obj = p_this;
443     while( p_obj != NULL )
444     {
445         char *psz_old = NULL;
446         if( p_obj->psz_header )
447         {
448             i_header_size += strlen( p_obj->psz_header ) + 4;
449             if( psz_header )
450             {
451                 psz_old = strdup( psz_header );
452                 psz_header = (char*)realloc( psz_header, i_header_size );
453                 snprintf( psz_header, i_header_size , "[%s] %s",
454                           p_obj->psz_header, psz_old );
455             }
456             else
457             {
458                 psz_header = (char *)malloc( i_header_size );
459                 snprintf( psz_header, i_header_size, "[%s]",
460                           p_obj->psz_header );
461             }
462         }
463         free( psz_old );
464         p_obj = p_obj->p_parent;
465     }
466
467 #if !defined(HAVE_VASPRINTF) || defined(__APPLE__) || defined(SYS_BEOS)
468     vlc_va_copy( args, _args );
469     vsnprintf( psz_str, i_size, psz_format, args );
470     va_end( args );
471     psz_str[ i_size - 1 ] = 0; /* Just in case */
472 #endif
473
474     msg_bank_t *p_queue = &QUEUE;
475     vlc_mutex_lock( &p_queue->lock );
476
477     /* Fill message information fields */
478     p_item->i_type =        i_type;
479     p_item->i_object_id =   (uintptr_t)p_this;
480     p_item->psz_object_type = p_this->psz_object_type;
481     p_item->psz_module =    strdup( psz_module );
482     p_item->psz_msg =       psz_str;
483     p_item->psz_header =    psz_header;
484
485     PrintMsg( p_this, p_item );
486 #define bank p_queue
487     for (int i = 0; i < bank->i_sub; i++)
488     {
489         msg_subscription_t *sub = bank->pp_sub[i];
490         if ((sub->end + 1 - sub->begin) % VLC_MSG_QSIZE)
491         {
492             sub->items[sub->end++] = msg_Hold (p_item);
493             if (sub->end == VLC_MSG_QSIZE)
494                 sub->end = 0;
495         }
496         else
497             sub->overruns++;
498     }
499     vlc_cond_broadcast (&bank->wait);
500     vlc_mutex_unlock (&bank->lock);
501 out:
502     msg_Release (p_item);
503 }
504
505 /*****************************************************************************
506  * PrintMsg: output a standard message item to stderr
507  *****************************************************************************
508  * Print a message to stderr, with colour formatting if needed.
509  *****************************************************************************/
510 static void PrintMsg ( vlc_object_t * p_this, msg_item_t * p_item )
511 {
512 #   define COL(x)  "\033[" #x ";1m"
513 #   define RED     COL(31)
514 #   define GREEN   COL(32)
515 #   define YELLOW  COL(33)
516 #   define WHITE   COL(0)
517 #   define GRAY    "\033[0m"
518
519 #ifdef UNDER_CE
520     int i_dummy;
521 #endif
522     static const char ppsz_type[4][9] = { "", " error", " warning", " debug" };
523     static const char ppsz_color[4][8] = { WHITE, RED, YELLOW, GRAY };
524     const char *psz_object;
525     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
526     int i_type = p_item->i_type;
527
528     switch( i_type )
529     {
530         case VLC_MSG_ERR:
531             if( priv->i_verbose < 0 ) return;
532             break;
533         case VLC_MSG_INFO:
534             if( priv->i_verbose < 0 ) return;
535             break;
536         case VLC_MSG_WARN:
537             if( priv->i_verbose < 1 ) return;
538             break;
539         case VLC_MSG_DBG:
540             if( priv->i_verbose < 2 ) return;
541             break;
542     }
543
544     psz_object = p_item->psz_object_type;
545     void * val = vlc_dictionary_value_for_key( &priv->msg_enabled_objects,
546                                                p_item->psz_module );
547     if( val == kObjectPrintingDisabled )
548         return;
549     if( val == kObjectPrintingEnabled )
550         /* Allowed */;
551     else
552     {
553         val = vlc_dictionary_value_for_key( &priv->msg_enabled_objects,
554                                             psz_object );
555         if( val == kObjectPrintingDisabled )
556             return;
557         if( val == kObjectPrintingEnabled )
558             /* Allowed */;
559         else if( !priv->msg_all_objects_enabled )
560             return;
561     }
562
563     int canc = vlc_savecancel ();
564 #ifdef UNDER_CE
565 #   define CE_WRITE(str) WriteFile( QUEUE.logfile, \
566                                     str, strlen(str), &i_dummy, NULL );
567     CE_WRITE( p_item->psz_module );
568     CE_WRITE( " " );
569     CE_WRITE( psz_object );
570     CE_WRITE( ppsz_type[i_type] );
571     CE_WRITE( ": " );
572     CE_WRITE( p_item->psz_msg );
573     CE_WRITE( "\r\n" );
574     FlushFileBuffers( QUEUE.logfile );
575
576 #else
577     /* Send the message to stderr */
578     utf8_fprintf( stderr, "[%s%p%s] %s%s%s %s%s: %s%s%s\n",
579                   priv->b_color ? GREEN : "",
580                   (void *)p_item->i_object_id,
581                   priv->b_color ? GRAY : "",
582                   p_item->psz_header ? p_item->psz_header : "",
583                   p_item->psz_header ? " " : "",
584                   p_item->psz_module, psz_object,
585                   ppsz_type[i_type],
586                   priv->b_color ? ppsz_color[i_type] : "",
587                   p_item->psz_msg,
588                   priv->b_color ? GRAY : "" );
589
590 #   if defined(WIN32)
591     fflush( stderr );
592 #   endif
593     vlc_restorecancel (canc);
594 #endif
595 }
596
597 static msg_context_t* GetContext(void)
598 {
599     msg_context_t *p_ctx = vlc_threadvar_get( &msg_context );
600     if( p_ctx == NULL )
601     {
602         MALLOC_NULL( p_ctx, msg_context_t );
603         p_ctx->psz_message = NULL;
604         vlc_threadvar_set( &msg_context, p_ctx );
605     }
606     return p_ctx;
607 }
608
609 void msg_StackDestroy (void *data)
610 {
611     msg_context_t *p_ctx = data;
612
613     free (p_ctx->psz_message);
614     free (p_ctx);
615 }
616
617 void msg_StackSet( int i_code, const char *psz_message, ... )
618 {
619     va_list ap;
620     msg_context_t *p_ctx = GetContext();
621
622     if( p_ctx == NULL )
623         return;
624     free( p_ctx->psz_message );
625
626     va_start( ap, psz_message );
627     if( vasprintf( &p_ctx->psz_message, psz_message, ap ) == -1 )
628         p_ctx->psz_message = NULL;
629     va_end( ap );
630
631     p_ctx->i_code = i_code;
632 }
633
634 void msg_StackAdd( const char *psz_message, ... )
635 {
636     char *psz_tmp;
637     va_list ap;
638     msg_context_t *p_ctx = GetContext();
639
640     if( p_ctx == NULL )
641         return;
642
643     va_start( ap, psz_message );
644     if( vasprintf( &psz_tmp, psz_message, ap ) == -1 )
645         psz_tmp = NULL;
646     va_end( ap );
647
648     if( !p_ctx->psz_message )
649         p_ctx->psz_message = psz_tmp;
650     else
651     {
652         char *psz_new;
653         if( asprintf( &psz_new, "%s: %s", psz_tmp, p_ctx->psz_message ) == -1 )
654             psz_new = NULL;
655
656         free( p_ctx->psz_message );
657         p_ctx->psz_message = psz_new;
658         free( psz_tmp );
659     }
660 }
661
662 const char* msg_StackMsg( void )
663 {
664     msg_context_t *p_ctx = GetContext();
665     assert( p_ctx );
666     return p_ctx->psz_message;
667 }