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