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