]> git.sesse.net Git - vlc/blob - src/misc/messages.c
Introduce realloc_or_free() to src/*, and add assert() to mark unhandled ENOMEM error...
[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 #include <vlc_memory.h>
37
38 #include <stdarg.h>                                       /* va_list for BSD */
39
40 #ifdef HAVE_FCNTL_H
41 #   include <fcntl.h>                  /* O_CREAT, O_TRUNC, O_WRONLY, O_SYNC */
42 #endif
43
44 #include <errno.h>                                                  /* errno */
45
46 #ifdef WIN32
47 #   include <vlc_network.h>          /* 'net_strerror' and 'WSAGetLastError' */
48 #endif
49
50 #ifdef HAVE_UNISTD_H
51 #   include <unistd.h>                                   /* close(), write() */
52 #endif
53
54 #include <assert.h>
55
56 #include <vlc_charset.h>
57 #include "../libvlc.h"
58
59 typedef struct
60 {
61     int i_code;
62     char * psz_message;
63 } msg_context_t;
64
65 static void cleanup_msg_context (void *data)
66 {
67     msg_context_t *ctx = data;
68     free (ctx->psz_message);
69     free (ctx);
70 }
71
72 static vlc_threadvar_t msg_context;
73 static uintptr_t banks = 0;
74
75 /*****************************************************************************
76  * Local macros
77  *****************************************************************************/
78 #if defined(HAVE_VA_COPY)
79 #   define vlc_va_copy(dest,src) va_copy(dest,src)
80 #elif defined(HAVE___VA_COPY)
81 #   define vlc_va_copy(dest,src) __va_copy(dest,src)
82 #else
83 #   define vlc_va_copy(dest,src) (dest)=(src)
84 #endif
85
86 #define QUEUE priv->msg_bank
87 static inline msg_bank_t *libvlc_bank (libvlc_int_t *inst)
88 {
89     return &(libvlc_priv (inst))->msg_bank;
90 }
91
92 /*****************************************************************************
93  * Local prototypes
94  *****************************************************************************/
95 static void QueueMsg ( vlc_object_t *, int, const char *,
96                        const char *, va_list );
97 static void PrintMsg ( vlc_object_t *, msg_item_t * );
98
99 static vlc_mutex_t msg_stack_lock = VLC_STATIC_MUTEX;
100
101 /**
102  * Initialize messages queues
103  * This function initializes all message queues
104  */
105 void msg_Create (libvlc_int_t *p_libvlc)
106 {
107     libvlc_priv_t *priv = libvlc_priv (p_libvlc);
108     msg_bank_t *bank = libvlc_bank (p_libvlc);
109
110     vlc_rwlock_init (&bank->lock);
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_rwlock_wrlock( &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_rwlock_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_rwlock_wrlock( &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_rwlock_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_rwlock_destroy (&bank->lock);
187 }
188
189 struct msg_subscription_t
190 {
191     libvlc_int_t   *instance;
192     msg_callback_t  func;
193     msg_cb_data_t  *opaque;
194 };
195
196 /**
197  * Subscribe to the message queue.
198  * Whenever a message is emitted, a callback will be called.
199  * Callback invocation are serialized within a subscription.
200  *
201  * @param instance LibVLC instance to get messages from
202  * @param cb callback function
203  * @param opaque data for the callback function
204  * @return a subscription pointer, or NULL in case of failure
205  */
206 msg_subscription_t *msg_Subscribe (libvlc_int_t *instance, msg_callback_t cb,
207                                    msg_cb_data_t *opaque)
208 {
209     msg_subscription_t *sub = malloc (sizeof (*sub));
210     if (sub == NULL)
211         return NULL;
212
213     sub->instance = instance;
214     sub->func = cb;
215     sub->opaque = opaque;
216
217     msg_bank_t *bank = libvlc_bank (instance);
218     vlc_rwlock_wrlock (&bank->lock);
219     TAB_APPEND (bank->i_sub, bank->pp_sub, sub);
220     vlc_rwlock_unlock (&bank->lock);
221
222     return sub;
223 }
224
225 /**
226  * Unsubscribe from the message queue.
227  * This function waits for the message callback to return if needed.
228  */
229 void msg_Unsubscribe (msg_subscription_t *sub)
230 {
231     msg_bank_t *bank = libvlc_bank (sub->instance);
232
233     vlc_rwlock_wrlock (&bank->lock);
234     TAB_REMOVE (bank->i_sub, bank->pp_sub, sub);
235     vlc_rwlock_unlock (&bank->lock);
236     free (sub);
237 }
238
239 /*****************************************************************************
240  * __msg_*: print a message
241  *****************************************************************************
242  * These functions queue a message for later printing.
243  *****************************************************************************/
244 void __msg_Generic( vlc_object_t *p_this, int i_type, const char *psz_module,
245                     const char *psz_format, ... )
246 {
247     va_list args;
248
249     va_start( args, psz_format );
250     QueueMsg( p_this, i_type, psz_module, psz_format, args );
251     va_end( args );
252 }
253
254 void __msg_GenericVa( vlc_object_t *p_this, int i_type, const char *psz_module,
255                       const char *psz_format, va_list args )
256 {
257     QueueMsg( p_this, i_type, psz_module, psz_format, args );
258 }
259
260 /**
261  * Destroys a message.
262  */
263 static void msg_Free (gc_object_t *gc)
264 {
265     msg_item_t *msg = vlc_priv (gc, msg_item_t);
266
267     free (msg->psz_module);
268     free (msg->psz_msg);
269     free (msg->psz_header);
270     free (msg);
271 }
272
273 /**
274  * Add a message to a queue
275  *
276  * This function provides basic functionnalities to other msg_* functions.
277  * It adds a message to a queue (after having printed all stored messages if it
278  * is full). If the message can't be converted to string in memory, it issues
279  * a warning.
280  */
281 static void QueueMsg( vlc_object_t *p_this, int i_type, const char *psz_module,
282                       const char *psz_format, va_list _args )
283 {
284     assert (p_this);
285     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
286     int         i_header_size;             /* Size of the additionnal header */
287     vlc_object_t *p_obj;
288     char *       psz_str = NULL;                 /* formatted message string */
289     char *       psz_header = NULL;
290     va_list      args;
291
292     if( p_this->i_flags & OBJECT_FLAGS_QUIET ||
293         (p_this->i_flags & OBJECT_FLAGS_NODBG && i_type == VLC_MSG_DBG) )
294         return;
295
296 #ifndef __GLIBC__
297     /* Expand %m to strerror(errno) - only once */
298     char buf[strlen( psz_format ) + 2001], *ptr;
299     strcpy( buf, psz_format );
300     ptr = (char*)buf;
301     psz_format = (const char*) buf;
302
303     for( ;; )
304     {
305         ptr = strchr( ptr, '%' );
306         if( ptr == NULL )
307             break;
308
309         if( ptr[1] == 'm' )
310         {
311             char errbuf[2001];
312             size_t errlen;
313
314 #ifndef WIN32
315             strerror_r( errno, errbuf, 1001 );
316 #else
317             int sockerr = WSAGetLastError( );
318             if( sockerr )
319             {
320                 strncpy( errbuf, net_strerror( sockerr ), 1001 );
321                 WSASetLastError( sockerr );
322             }
323             if ((sockerr == 0)
324              || (strcmp ("Unknown network stack error", errbuf) == 0))
325                 strncpy( errbuf, strerror( errno ), 1001 );
326 #endif
327             errbuf[1000] = 0;
328
329             /* Escape '%' from the error string */
330             for( char *percent = strchr( errbuf, '%' );
331                  percent != NULL;
332                  percent = strchr( percent + 2, '%' ) )
333             {
334                 memmove( percent + 1, percent, strlen( percent ) + 1 );
335             }
336
337             errlen = strlen( errbuf );
338             memmove( ptr + errlen, ptr + 2, strlen( ptr + 2 ) + 1 );
339             memcpy( ptr, errbuf, errlen );
340             break; /* Only once, so we don't overflow */
341         }
342
343         /* Looks for conversion specifier... */
344         do
345             ptr++;
346         while( *ptr && ( strchr( "diouxXeEfFgGaAcspn%", *ptr ) == NULL ) );
347         if( *ptr )
348             ptr++; /* ...and skip it */
349     }
350 #endif
351
352     /* Convert message to string  */
353     vlc_va_copy( args, _args );
354     if( vasprintf( &psz_str, psz_format, args ) == -1 )
355         psz_str = NULL;
356     va_end( args );
357
358     if( psz_str == NULL )
359     {
360         int canc = vlc_savecancel (); /* Do not print half of a message... */
361 #ifdef __GLIBC__
362         fprintf( stderr, "main warning: can't store message (%m): " );
363 #else
364         char psz_err[1001];
365 #ifndef WIN32
366         /* we're not using GLIBC, so we are sure that the error description
367          * will be stored in the buffer we provide to strerror_r() */
368         strerror_r( errno, psz_err, 1001 );
369 #else
370         strncpy( psz_err, strerror( errno ), 1001 );
371 #endif
372         psz_err[1000] = '\0';
373         fprintf( stderr, "main warning: can't store message (%s): ", psz_err );
374 #endif
375         vlc_va_copy( args, _args );
376         /* We should use utf8_vfprintf - but it calls malloc()... */
377         vfprintf( stderr, psz_format, args );
378         va_end( args );
379         fputs( "\n", stderr );
380         vlc_restorecancel (canc);
381         return;
382     }
383
384     msg_item_t * p_item = malloc (sizeof (*p_item));
385     if (p_item == NULL)
386         return; /* Uho! */
387
388     vlc_gc_init (p_item, msg_Free);
389     p_item->psz_module = p_item->psz_msg = p_item->psz_header = NULL;
390
391
392
393     i_header_size = 0;
394     p_obj = p_this;
395     while( p_obj != NULL )
396     {
397         char *psz_old = NULL;
398         if( p_obj->psz_header )
399         {
400             i_header_size += strlen( p_obj->psz_header ) + 4;
401             if( psz_header )
402             {
403                 psz_old = strdup( psz_header );
404                 psz_header = realloc_or_free( psz_header, i_header_size );
405                 assert( psz_header );
406                 snprintf( psz_header, i_header_size , "[%s] %s",
407                           p_obj->psz_header, psz_old );
408             }
409             else
410             {
411                 psz_header = malloc( i_header_size );
412                 assert( psz_header );
413                 snprintf( psz_header, i_header_size, "[%s]",
414                           p_obj->psz_header );
415             }
416         }
417         free( psz_old );
418         p_obj = p_obj->p_parent;
419     }
420
421     /* Fill message information fields */
422     p_item->i_type =        i_type;
423     p_item->i_object_id =   (uintptr_t)p_this;
424     p_item->psz_object_type = p_this->psz_object_type;
425     p_item->psz_module =    strdup( psz_module );
426     p_item->psz_msg =       psz_str;
427     p_item->psz_header =    psz_header;
428
429     PrintMsg( p_this, p_item );
430
431     msg_bank_t *bank = &QUEUE;
432     vlc_rwlock_rdlock (&bank->lock);
433     for (int i = 0; i < bank->i_sub; i++)
434     {
435         msg_subscription_t *sub = bank->pp_sub[i];
436         sub->func (sub->opaque, p_item, 0);
437     }
438     vlc_rwlock_unlock (&bank->lock);
439     msg_Release (p_item);
440 }
441
442 /*****************************************************************************
443  * PrintMsg: output a standard message item to stderr
444  *****************************************************************************
445  * Print a message to stderr, with colour formatting if needed.
446  *****************************************************************************/
447 static void PrintMsg ( vlc_object_t * p_this, msg_item_t * p_item )
448 {
449 #   define COL(x)  "\033[" #x ";1m"
450 #   define RED     COL(31)
451 #   define GREEN   COL(32)
452 #   define YELLOW  COL(33)
453 #   define WHITE   COL(0)
454 #   define GRAY    "\033[0m"
455
456 #ifdef UNDER_CE
457     int i_dummy;
458 #endif
459     static const char ppsz_type[4][9] = { "", " error", " warning", " debug" };
460     static const char ppsz_color[4][8] = { WHITE, RED, YELLOW, GRAY };
461     const char *psz_object;
462     libvlc_priv_t *priv = libvlc_priv (p_this->p_libvlc);
463     int i_type = p_item->i_type;
464
465     switch( i_type )
466     {
467         case VLC_MSG_ERR:
468             if( priv->i_verbose < 0 ) return;
469             break;
470         case VLC_MSG_INFO:
471             if( priv->i_verbose < 0 ) return;
472             break;
473         case VLC_MSG_WARN:
474             if( priv->i_verbose < 1 ) return;
475             break;
476         case VLC_MSG_DBG:
477             if( priv->i_verbose < 2 ) return;
478             break;
479     }
480
481     psz_object = p_item->psz_object_type;
482     void * val = vlc_dictionary_value_for_key( &priv->msg_enabled_objects,
483                                                p_item->psz_module );
484     if( val == kObjectPrintingDisabled )
485         return;
486     if( val == kObjectPrintingEnabled )
487         /* Allowed */;
488     else
489     {
490         val = vlc_dictionary_value_for_key( &priv->msg_enabled_objects,
491                                             psz_object );
492         if( val == kObjectPrintingDisabled )
493             return;
494         if( val == kObjectPrintingEnabled )
495             /* Allowed */;
496         else if( !priv->msg_all_objects_enabled )
497             return;
498     }
499
500 #ifdef UNDER_CE
501 #   define CE_WRITE(str) WriteFile( QUEUE.logfile, \
502                                     str, strlen(str), &i_dummy, NULL );
503     CE_WRITE( p_item->psz_module );
504     CE_WRITE( " " );
505     CE_WRITE( psz_object );
506     CE_WRITE( ppsz_type[i_type] );
507     CE_WRITE( ": " );
508     CE_WRITE( p_item->psz_msg );
509     CE_WRITE( "\r\n" );
510     FlushFileBuffers( QUEUE.logfile );
511
512 #else
513     int canc = vlc_savecancel ();
514     /* Send the message to stderr */
515     utf8_fprintf( stderr, "[%s%p%s] %s%s%s %s%s: %s%s%s\n",
516                   priv->b_color ? GREEN : "",
517                   (void *)p_item->i_object_id,
518                   priv->b_color ? GRAY : "",
519                   p_item->psz_header ? p_item->psz_header : "",
520                   p_item->psz_header ? " " : "",
521                   p_item->psz_module, psz_object,
522                   ppsz_type[i_type],
523                   priv->b_color ? ppsz_color[i_type] : "",
524                   p_item->psz_msg,
525                   priv->b_color ? GRAY : "" );
526
527 #   if defined(WIN32)
528     fflush( stderr );
529 #   endif
530     vlc_restorecancel (canc);
531 #endif
532 }
533
534 static msg_context_t* GetContext(void)
535 {
536     msg_context_t *p_ctx = vlc_threadvar_get( msg_context );
537     if( p_ctx == NULL )
538     {
539         p_ctx = malloc( sizeof( msg_context_t ) );
540         if( !p_ctx )
541             return NULL;
542         p_ctx->psz_message = NULL;
543         vlc_threadvar_set( msg_context, p_ctx );
544     }
545     return p_ctx;
546 }
547
548 void msg_StackDestroy (void *data)
549 {
550     msg_context_t *p_ctx = data;
551
552     free (p_ctx->psz_message);
553     free (p_ctx);
554 }
555
556 void msg_StackSet( int i_code, const char *psz_message, ... )
557 {
558     va_list ap;
559     msg_context_t *p_ctx = GetContext();
560
561     if( p_ctx == NULL )
562         return;
563     free( p_ctx->psz_message );
564
565     va_start( ap, psz_message );
566     if( vasprintf( &p_ctx->psz_message, psz_message, ap ) == -1 )
567         p_ctx->psz_message = NULL;
568     va_end( ap );
569
570     p_ctx->i_code = i_code;
571 }
572
573 void msg_StackAdd( const char *psz_message, ... )
574 {
575     char *psz_tmp;
576     va_list ap;
577     msg_context_t *p_ctx = GetContext();
578
579     if( p_ctx == NULL )
580         return;
581
582     va_start( ap, psz_message );
583     if( vasprintf( &psz_tmp, psz_message, ap ) == -1 )
584         psz_tmp = NULL;
585     va_end( ap );
586
587     if( !p_ctx->psz_message )
588         p_ctx->psz_message = psz_tmp;
589     else
590     {
591         char *psz_new;
592         if( asprintf( &psz_new, "%s: %s", psz_tmp, p_ctx->psz_message ) == -1 )
593             psz_new = NULL;
594
595         free( p_ctx->psz_message );
596         p_ctx->psz_message = psz_new;
597         free( psz_tmp );
598     }
599 }
600
601 const char* msg_StackMsg( void )
602 {
603     msg_context_t *p_ctx = GetContext();
604     assert( p_ctx );
605     return p_ctx->psz_message;
606 }