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