]> git.sesse.net Git - vlc/blob - src/extras/libc.c
Separate and refactor the win32 main code
[vlc] / src / extras / libc.c
1 /*****************************************************************************
2  * libc.c: Extra libc function for some systems.
3  *****************************************************************************
4  * Copyright (C) 2002-2006 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Jon Lech Johansen <jon-vl@nanocrew.net>
8  *          Samuel Hocevar <sam@zoy.org>
9  *          Gildas Bazin <gbazin@videolan.org>
10  *          Derk-Jan Hartman <hartman at videolan dot org>
11  *          Christophe Massiot <massiot@via.ecp.fr>
12  *          Rémi Denis-Courmont <rem à videolan.org>
13  *
14  * This program is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 2 of the License, or
17  * (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
27  *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc/vlc.h>
33
34 #include <ctype.h>
35
36
37 #undef iconv_t
38 #undef iconv_open
39 #undef iconv
40 #undef iconv_close
41
42 #if defined(HAVE_ICONV)
43 #   include <iconv.h>
44 #endif
45
46 #ifdef HAVE_DIRENT_H
47 #   include <dirent.h>
48 #endif
49
50 #ifdef HAVE_SIGNAL_H
51 #   include <signal.h>
52 #endif
53
54 #ifdef HAVE_FORK
55 #   include <sys/time.h>
56 #   include <unistd.h>
57 #   include <errno.h>
58 #   include <sys/wait.h>
59 #   include <fcntl.h>
60 #   include <sys/socket.h>
61 #   include <sys/poll.h>
62 #endif
63
64 #if defined(WIN32) || defined(UNDER_CE)
65 #   undef _wopendir
66 #   undef _wreaddir
67 #   undef _wclosedir
68 #   undef rewinddir
69 #   undef seekdir
70 #   undef telldir
71 #   define WIN32_LEAN_AND_MEAN
72 #   include <windows.h>
73 #endif
74
75 #ifdef UNDER_CE
76 #   define strcoll strcmp
77 #endif
78
79 /*****************************************************************************
80  * getenv: just in case, but it should never be called
81  *****************************************************************************/
82 #if !defined( HAVE_GETENV )
83 char *vlc_getenv( const char *name )
84 {
85     return NULL;
86 }
87 #endif
88
89 /*****************************************************************************
90  * strdup: returns a malloc'd copy of a string
91  *****************************************************************************/
92 #if !defined( HAVE_STRDUP )
93 char *vlc_strdup( const char *string )
94 {
95     return strndup( string, strlen( string ) );
96 }
97 #endif
98
99 /*****************************************************************************
100  * strndup: returns a malloc'd copy of at most n bytes of string
101  * Does anyone know whether or not it will be present in Jaguar?
102  *****************************************************************************/
103 #if !defined( HAVE_STRNDUP )
104 char *vlc_strndup( const char *string, size_t n )
105 {
106     char *psz;
107     size_t len = strlen( string );
108
109     len = __MIN( len, n );
110     psz = (char*)malloc( len + 1 );
111     if( psz != NULL )
112     {
113         memcpy( (void*)psz, (const void*)string, len );
114         psz[ len ] = 0;
115     }
116
117     return psz;
118 }
119 #endif
120
121 /*****************************************************************************
122  * strnlen:
123  *****************************************************************************/
124 #if !defined( HAVE_STRNLEN )
125 size_t vlc_strnlen( const char *psz, size_t n )
126 {
127     const char *psz_end = memchr( psz, 0, n );
128     return psz_end ? (size_t)( psz_end - psz ) : n;
129 }
130 #endif
131
132 /*****************************************************************************
133  * strcasecmp: compare two strings ignoring case
134  *****************************************************************************/
135 #if !defined( HAVE_STRCASECMP ) && !defined( HAVE_STRICMP )
136 int vlc_strcasecmp( const char *s1, const char *s2 )
137 {
138     int c1, c2;
139     if( !s1 || !s2 ) return  -1;
140
141     while( *s1 && *s2 )
142     {
143         c1 = tolower(*s1);
144         c2 = tolower(*s2);
145
146         if( c1 != c2 ) return (c1 < c2 ? -1 : 1);
147         s1++; s2++;
148     }
149
150     if( !*s1 && !*s2 ) return 0;
151     else return (*s1 ? 1 : -1);
152 }
153 #endif
154
155 /*****************************************************************************
156  * strncasecmp: compare n chars from two strings ignoring case
157  *****************************************************************************/
158 #if !defined( HAVE_STRNCASECMP ) && !defined( HAVE_STRNICMP )
159 int vlc_strncasecmp( const char *s1, const char *s2, size_t n )
160 {
161     int c1, c2;
162     if( !s1 || !s2 ) return  -1;
163
164     while( n > 0 && *s1 && *s2 )
165     {
166         c1 = tolower(*s1);
167         c2 = tolower(*s2);
168
169         if( c1 != c2 ) return (c1 < c2 ? -1 : 1);
170         s1++; s2++; n--;
171     }
172
173     if( !n || (!*s1 && !*s2) ) return 0;
174     else return (*s1 ? 1 : -1);
175 }
176 #endif
177
178 /******************************************************************************
179  * strcasestr: find a substring (little) in another substring (big)
180  * Case sensitive. Return NULL if not found, return big if little == null
181  *****************************************************************************/
182 #if !defined( HAVE_STRCASESTR ) && !defined( HAVE_STRISTR )
183 char * vlc_strcasestr( const char *psz_big, const char *psz_little )
184 {
185     char *p_pos = (char *)psz_big;
186
187     if( !psz_big || !psz_little || !*psz_little ) return p_pos;
188  
189     while( *p_pos )
190     {
191         if( toupper( *p_pos ) == toupper( *psz_little ) )
192         {
193             char * psz_cur1 = p_pos + 1;
194             char * psz_cur2 = (char *)psz_little + 1;
195             while( *psz_cur1 && *psz_cur2 &&
196                    toupper( *psz_cur1 ) == toupper( *psz_cur2 ) )
197             {
198                 psz_cur1++;
199                 psz_cur2++;
200             }
201             if( !*psz_cur2 ) return p_pos;
202         }
203         p_pos++;
204     }
205     return NULL;
206 }
207 #endif
208
209 /*****************************************************************************
210  * vasprintf:
211  *****************************************************************************/
212 #if !defined(HAVE_VASPRINTF) || defined(__APPLE__) || defined(SYS_BEOS)
213 int vlc_vasprintf(char **strp, const char *fmt, va_list ap)
214 {
215     /* Guess we need no more than 100 bytes. */
216     int     i_size = 100;
217     char    *p = malloc( i_size );
218     int     n;
219
220     if( p == NULL )
221     {
222         *strp = NULL;
223         return -1;
224     }
225
226     for( ;; )
227     {
228         /* Try to print in the allocated space. */
229         n = vsnprintf( p, i_size, fmt, ap );
230
231         /* If that worked, return the string. */
232         if (n > -1 && n < i_size)
233         {
234             *strp = p;
235             return strlen( p );
236         }
237         /* Else try again with more space. */
238         if (n > -1)    /* glibc 2.1 */
239         {
240            i_size = n+1; /* precisely what is needed */
241         }
242         else           /* glibc 2.0 */
243         {
244            i_size *= 2;  /* twice the old size */
245         }
246         if( (p = realloc( p, i_size ) ) == NULL)
247         {
248             *strp = NULL;
249             return -1;
250         }
251     }
252 }
253 #endif
254
255 /*****************************************************************************
256  * asprintf:
257  *****************************************************************************/
258 #if !defined(HAVE_ASPRINTF) || defined(__APPLE__) || defined(SYS_BEOS)
259 int vlc_asprintf( char **strp, const char *fmt, ... )
260 {
261     va_list args;
262     int i_ret;
263
264     va_start( args, fmt );
265     i_ret = vasprintf( strp, fmt, args );
266     va_end( args );
267
268     return i_ret;
269 }
270 #endif
271
272 /*****************************************************************************
273  * atof: convert a string to a double.
274  *****************************************************************************/
275 #if !defined( HAVE_ATOF )
276 double vlc_atof( const char *nptr )
277 {
278     double f_result;
279     wchar_t *psz_tmp = NULL;
280     int i_len = strlen( nptr ) + 1;
281
282     psz_tmp = malloc( i_len * sizeof(wchar_t) );
283     if( !psz_tmp )
284         return NULL;
285     MultiByteToWideChar( CP_ACP, 0, nptr, -1, psz_tmp, i_len );
286     f_result = wcstod( psz_tmp, NULL );
287     free( psz_tmp );
288
289     return f_result;
290 }
291 #endif
292
293 /*****************************************************************************
294  * strtoll: convert a string to a 64 bits int.
295  *****************************************************************************/
296 #if !defined( HAVE_STRTOLL )
297 int64_t vlc_strtoll( const char *nptr, char **endptr, int base )
298 {
299     int64_t i_value = 0;
300     int sign = 1, newbase = base ? base : 10;
301
302     while( isspace(*nptr) ) nptr++;
303
304     if( *nptr == '-' )
305     {
306         sign = -1;
307         nptr++;
308     }
309
310     /* Try to detect base */
311     if( *nptr == '0' )
312     {
313         newbase = 8;
314         nptr++;
315
316         if( *nptr == 'x' )
317         {
318             newbase = 16;
319             nptr++;
320         }
321     }
322
323     if( base && newbase != base )
324     {
325         if( endptr ) *endptr = (char *)nptr;
326         return i_value;
327     }
328
329     switch( newbase )
330     {
331         case 10:
332             while( *nptr >= '0' && *nptr <= '9' )
333             {
334                 i_value *= 10;
335                 i_value += ( *nptr++ - '0' );
336             }
337             if( endptr ) *endptr = (char *)nptr;
338             break;
339
340         case 16:
341             while( (*nptr >= '0' && *nptr <= '9') ||
342                    (*nptr >= 'a' && *nptr <= 'f') ||
343                    (*nptr >= 'A' && *nptr <= 'F') )
344             {
345                 int i_valc = 0;
346                 if(*nptr >= '0' && *nptr <= '9') i_valc = *nptr - '0';
347                 else if(*nptr >= 'a' && *nptr <= 'f') i_valc = *nptr - 'a' +10;
348                 else if(*nptr >= 'A' && *nptr <= 'F') i_valc = *nptr - 'A' +10;
349                 i_value *= 16;
350                 i_value += i_valc;
351                 nptr++;
352             }
353             if( endptr ) *endptr = (char *)nptr;
354             break;
355
356         default:
357             i_value = strtol( nptr, endptr, newbase );
358             break;
359     }
360
361     return i_value * sign;
362 }
363 #endif
364
365 /*****************************************************************************
366  * atoll: convert a string to a 64 bits int.
367  *****************************************************************************/
368 #if !defined( HAVE_ATOLL )
369 int64_t vlc_atoll( const char *nptr )
370 {
371     return strtoll( nptr, (char **)NULL, 10 );
372 }
373 #endif
374
375 /*****************************************************************************
376  * lldiv: returns quotient and remainder
377  *****************************************************************************/
378 #if !defined( HAVE_LLDIV )
379 lldiv_t vlc_lldiv( long long numer, long long denom )
380 {
381     lldiv_t d;
382     d.quot = numer / denom;
383     d.rem  = numer % denom;
384     return d;
385 }
386 #endif
387
388
389 /**
390  * Copy a string to a sized buffer. The result is always nul-terminated
391  * (contrary to strncpy()).
392  *
393  * @param dest destination buffer
394  * @param src string to be copied
395  * @param len maximum number of characters to be copied plus one for the
396  * terminating nul.
397  *
398  * @return strlen(src)
399  */
400 #ifndef HAVE_STRLCPY
401 extern size_t vlc_strlcpy (char *tgt, const char *src, size_t bufsize)
402 {
403     size_t length;
404
405     for (length = 1; (length < bufsize) && *src; length++)
406         *tgt++ = *src++;
407
408     if (bufsize)
409         *tgt = '\0';
410
411     while (*src++)
412         length++;
413
414     return length - 1;
415 }
416 #endif
417
418 /*****************************************************************************
419  * vlc_*dir_wrapper: wrapper under Windows to return the list of drive letters
420  * when called with an empty argument or just '\'
421  *****************************************************************************/
422 #if defined(WIN32) && !defined(UNDER_CE)
423 #   include <assert.h>
424
425 typedef struct vlc_DIR
426 {
427     _WDIR *p_real_dir;
428     int i_drives;
429     struct _wdirent dd_dir;
430     bool b_insert_back;
431 } vlc_DIR;
432
433 void *vlc_wopendir( const wchar_t *wpath )
434 {
435     vlc_DIR *p_dir = NULL;
436     _WDIR *p_real_dir = NULL;
437
438     if ( wpath == NULL || wpath[0] == '\0'
439           || (wcscmp (wpath, L"\\") == 0) )
440     {
441         /* Special mode to list drive letters */
442         p_dir = malloc( sizeof(vlc_DIR) );
443         if( !p_dir )
444             return NULL;
445         p_dir->p_real_dir = NULL;
446         p_dir->i_drives = GetLogicalDrives();
447         return (void *)p_dir;
448     }
449
450     p_real_dir = _wopendir( wpath );
451     if ( p_real_dir == NULL )
452         return NULL;
453
454     p_dir = malloc( sizeof(vlc_DIR) );
455     if( !p_dir )
456     {
457         _wclosedir( p_real_dir );
458         return NULL;
459     }
460     p_dir->p_real_dir = p_real_dir;
461
462     assert (wpath[0]); // wpath[1] is defined
463     p_dir->b_insert_back = !wcscmp (wpath + 1, L":\\");
464     return (void *)p_dir;
465 }
466
467 struct _wdirent *vlc_wreaddir( void *_p_dir )
468 {
469     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
470     unsigned int i;
471     DWORD i_drives;
472
473     if ( p_dir->p_real_dir != NULL )
474     {
475         if ( p_dir->b_insert_back )
476         {
477             /* Adds "..", gruik! */
478             p_dir->dd_dir.d_ino = 0;
479             p_dir->dd_dir.d_reclen = 0;
480             p_dir->dd_dir.d_namlen = 2;
481             wcscpy( p_dir->dd_dir.d_name, L".." );
482             p_dir->b_insert_back = false;
483             return &p_dir->dd_dir;
484         }
485
486         return _wreaddir( p_dir->p_real_dir );
487     }
488
489     /* Drive letters mode */
490     i_drives = p_dir->i_drives;
491     if ( !i_drives )
492         return NULL; /* end */
493
494     for ( i = 0; i < sizeof(DWORD)*8; i++, i_drives >>= 1 )
495         if ( i_drives & 1 ) break;
496
497     if ( i >= 26 )
498         return NULL; /* this should not happen */
499
500     swprintf( p_dir->dd_dir.d_name, L"%c:\\", 'A' + i );
501     p_dir->dd_dir.d_namlen = wcslen(p_dir->dd_dir.d_name);
502     p_dir->i_drives &= ~(1UL << i);
503     return &p_dir->dd_dir;
504 }
505
506 int vlc_wclosedir( void *_p_dir )
507 {
508     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
509     int i_ret = 0;
510
511     if ( p_dir->p_real_dir != NULL )
512         i_ret = _wclosedir( p_dir->p_real_dir );
513
514     free( p_dir );
515     return i_ret;
516 }
517
518 void vlc_rewinddir( void *_p_dir )
519 {
520     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
521
522     if ( p_dir->p_real_dir != NULL )
523         _wrewinddir( p_dir->p_real_dir );
524 }
525
526 void vlc_seekdir( void *_p_dir, long loc)
527 {
528     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
529
530     if ( p_dir->p_real_dir != NULL )
531         _wseekdir( p_dir->p_real_dir, loc );
532 }
533
534 long vlc_telldir( void *_p_dir )
535 {
536     vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
537
538     if ( p_dir->p_real_dir != NULL )
539         return _wtelldir( p_dir->p_real_dir );
540     return 0;
541 }
542 #endif
543
544 /*****************************************************************************
545  * scandir: scan a directory alpha-sorted
546  *****************************************************************************/
547 #if !defined( HAVE_SCANDIR )
548 /* FIXME: I suspect this is dead code -> utf8_scandir */
549 #ifdef WIN32
550 # undef opendir
551 # undef readdir
552 # undef closedir
553 #endif
554 int vlc_alphasort( const struct dirent **a, const struct dirent **b )
555 {
556     return strcoll( (*a)->d_name, (*b)->d_name );
557 }
558
559 int vlc_scandir( const char *name, struct dirent ***namelist,
560                     int (*filter) ( const struct dirent * ),
561                     int (*compar) ( const struct dirent **,
562                                     const struct dirent ** ) )
563 {
564     DIR            * p_dir;
565     struct dirent  * p_content;
566     struct dirent ** pp_list;
567     int              ret, size;
568
569     if( !namelist || !( p_dir = opendir( name ) ) ) return -1;
570
571     ret     = 0;
572     pp_list = NULL;
573     while( ( p_content = readdir( p_dir ) ) )
574     {
575         if( filter && !filter( p_content ) )
576         {
577             continue;
578         }
579         pp_list = realloc( pp_list, ( ret + 1 ) * sizeof( struct dirent * ) );
580         size = sizeof( struct dirent ) + strlen( p_content->d_name ) + 1;
581         pp_list[ret] = malloc( size );
582         if( pp_list[ret] )
583         {
584             memcpy( pp_list[ret], p_content, size );
585             ret++;
586         }
587         else
588         {
589             /* Continuing is useless when no more memory can be allocted,
590              * so better return what we have found.
591              */
592             ret = -1;
593             break;
594         }
595     }
596
597     closedir( p_dir );
598
599     if( compar )
600     {
601         qsort( pp_list, ret, sizeof( struct dirent * ),
602                (int (*)(const void *, const void *)) compar );
603     }
604
605     *namelist = pp_list;
606     return ret;
607 }
608 #endif
609
610 #if defined (WIN32)
611 /**
612  * gettext callbacks for plugins.
613  * LibVLC links libintl statically on Windows.
614  */
615 char *vlc_dgettext( const char *package, const char *msgid )
616 {
617     return dgettext( package, msgid );
618 }
619 #endif
620
621 /**
622  * In-tree plugins share their gettext domain with LibVLC.
623  */
624 char *vlc_gettext( const char *msgid )
625 {
626     return dgettext( PACKAGE_NAME, msgid );
627 }
628
629 /*****************************************************************************
630  * count_utf8_string: returns the number of characters in the string.
631  *****************************************************************************/
632 static int count_utf8_string( const char *psz_string )
633 {
634     int i = 0, i_count = 0;
635     while( psz_string[ i ] != 0 )
636     {
637         if( ((unsigned char *)psz_string)[ i ] <  0x80UL ) i_count++;
638         i++;
639     }
640     return i_count;
641 }
642
643 /*****************************************************************************
644  * wraptext: inserts \n at convenient places to wrap the text.
645  *           Returns the modified string in a new buffer.
646  *****************************************************************************/
647 char *vlc_wraptext( const char *psz_text, int i_line )
648 {
649     int i_len;
650     char *psz_line, *psz_new_text;
651
652     psz_line = psz_new_text = strdup( psz_text );
653
654     i_len = count_utf8_string( psz_text );
655
656     while( i_len > i_line )
657     {
658         /* Look if there is a newline somewhere. */
659         char *psz_parser = psz_line;
660         int i_count = 0;
661         while( i_count <= i_line && *psz_parser != '\n' )
662         {
663             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
664             psz_parser++;
665             i_count++;
666         }
667         if( *psz_parser == '\n' )
668         {
669             i_len -= (i_count + 1);
670             psz_line = psz_parser + 1;
671             continue;
672         }
673
674         /* Find the furthest space. */
675         while( psz_parser > psz_line && *psz_parser != ' ' )
676         {
677             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser--;
678             psz_parser--;
679             i_count--;
680         }
681         if( *psz_parser == ' ' )
682         {
683             *psz_parser = '\n';
684             i_len -= (i_count + 1);
685             psz_line = psz_parser + 1;
686             continue;
687         }
688
689         /* Wrapping has failed. Find the first space or newline */
690         while( i_count < i_len && *psz_parser != ' ' && *psz_parser != '\n' )
691         {
692             while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
693             psz_parser++;
694             i_count++;
695         }
696         if( i_count < i_len ) *psz_parser = '\n';
697         i_len -= (i_count + 1);
698         psz_line = psz_parser + 1;
699     }
700
701     return psz_new_text;
702 }
703
704 /*****************************************************************************
705  * iconv wrapper
706  *****************************************************************************/
707 vlc_iconv_t vlc_iconv_open( const char *tocode, const char *fromcode )
708 {
709 #if defined(HAVE_ICONV)
710     return iconv_open( tocode, fromcode );
711 #else
712     return NULL;
713 #endif
714 }
715
716 size_t vlc_iconv( vlc_iconv_t cd, const char **inbuf, size_t *inbytesleft,
717                   char **outbuf, size_t *outbytesleft )
718 {
719 #if defined(HAVE_ICONV)
720     return iconv( cd, (ICONV_CONST char **)inbuf, inbytesleft,
721                   outbuf, outbytesleft );
722 #else
723     int i_bytes;
724
725     if (inbytesleft == NULL || outbytesleft == NULL)
726     {
727         return 0;
728     }
729
730     i_bytes = __MIN(*inbytesleft, *outbytesleft);
731     if( !inbuf || !outbuf || !i_bytes ) return (size_t)(-1);
732     memcpy( *outbuf, *inbuf, i_bytes );
733     inbuf += i_bytes;
734     outbuf += i_bytes;
735     inbytesleft -= i_bytes;
736     outbytesleft -= i_bytes;
737     return i_bytes;
738 #endif
739 }
740
741 int vlc_iconv_close( vlc_iconv_t cd )
742 {
743 #if defined(HAVE_ICONV)
744     return iconv_close( cd );
745 #else
746     return 0;
747 #endif
748 }
749
750 /*****************************************************************************
751  * reduce a fraction
752  *   (adapted from libavcodec, author Michael Niedermayer <michaelni@gmx.at>)
753  *****************************************************************************/
754 bool vlc_ureduce( unsigned *pi_dst_nom, unsigned *pi_dst_den,
755                         uint64_t i_nom, uint64_t i_den, uint64_t i_max )
756 {
757     bool b_exact = 1;
758     uint64_t i_gcd;
759
760     if( i_den == 0 )
761     {
762         *pi_dst_nom = 0;
763         *pi_dst_den = 1;
764         return 1;
765     }
766
767     i_gcd = GCD( i_nom, i_den );
768     i_nom /= i_gcd;
769     i_den /= i_gcd;
770
771     if( i_max == 0 ) i_max = INT64_C(0xFFFFFFFF);
772
773     if( i_nom > i_max || i_den > i_max )
774     {
775         uint64_t i_a0_num = 0, i_a0_den = 1, i_a1_num = 1, i_a1_den = 0;
776         b_exact = 0;
777
778         for( ; ; )
779         {
780             uint64_t i_x = i_nom / i_den;
781             uint64_t i_a2n = i_x * i_a1_num + i_a0_num;
782             uint64_t i_a2d = i_x * i_a1_den + i_a0_den;
783
784             if( i_a2n > i_max || i_a2d > i_max ) break;
785
786             i_nom %= i_den;
787
788             i_a0_num = i_a1_num; i_a0_den = i_a1_den;
789             i_a1_num = i_a2n; i_a1_den = i_a2d;
790             if( i_nom == 0 ) break;
791             i_x = i_nom; i_nom = i_den; i_den = i_x;
792         }
793         i_nom = i_a1_num;
794         i_den = i_a1_den;
795     }
796
797     *pi_dst_nom = i_nom;
798     *pi_dst_den = i_den;
799
800     return b_exact;
801 }
802
803 /*************************************************************************
804  * vlc_execve: Execute an external program with a given environment,
805  * wait until it finishes and return its standard output
806  *************************************************************************/
807 int __vlc_execve( vlc_object_t *p_object, int i_argc, char *const *ppsz_argv,
808                   char *const *ppsz_env, const char *psz_cwd,
809                   const char *p_in, size_t i_in,
810                   char **pp_data, size_t *pi_data )
811 {
812     (void)i_argc; // <-- hmph
813 #ifdef HAVE_FORK
814 # define BUFSIZE 1024
815     int fds[2], i_status;
816
817     if (socketpair (AF_LOCAL, SOCK_STREAM, 0, fds))
818         return -1;
819
820     pid_t pid = -1;
821     if ((fds[0] > 2) && (fds[1] > 2))
822         pid = fork ();
823
824     switch (pid)
825     {
826         case -1:
827             msg_Err (p_object, "unable to fork (%m)");
828             close (fds[0]);
829             close (fds[1]);
830             return -1;
831
832         case 0:
833         {
834             sigset_t set;
835             sigemptyset (&set);
836             pthread_sigmask (SIG_SETMASK, &set, NULL);
837
838             /* NOTE:
839              * Like it or not, close can fail (and not only with EBADF)
840              */
841             if ((close (0) == 0) && (close (1) == 0) && (close (2) == 0)
842              && (dup (fds[1]) == 0) && (dup (fds[1]) == 1)
843              && (open ("/dev/null", O_RDONLY) == 2)
844              && ((psz_cwd == NULL) || (chdir (psz_cwd) == 0)))
845                 execve (ppsz_argv[0], ppsz_argv, ppsz_env);
846
847             exit (EXIT_FAILURE);
848         }
849     }
850
851     close (fds[1]);
852
853     *pi_data = 0;
854     if (*pp_data)
855         free (*pp_data);
856     *pp_data = NULL;
857
858     if (i_in == 0)
859         shutdown (fds[0], SHUT_WR);
860
861     while (!p_object->b_die)
862     {
863         struct pollfd ufd[1];
864         memset (ufd, 0, sizeof (ufd));
865         ufd[0].fd = fds[0];
866         ufd[0].events = POLLIN;
867
868         if (i_in > 0)
869             ufd[0].events |= POLLOUT;
870
871         if (poll (ufd, 1, 10) <= 0)
872             continue;
873
874         if (ufd[0].revents & ~POLLOUT)
875         {
876             char *ptr = realloc (*pp_data, *pi_data + BUFSIZE + 1);
877             if (ptr == NULL)
878                 break; /* safely abort */
879
880             *pp_data = ptr;
881
882             ssize_t val = read (fds[0], ptr + *pi_data, BUFSIZE);
883             switch (val)
884             {
885                 case -1:
886                 case 0:
887                     shutdown (fds[0], SHUT_RD);
888                     break;
889
890                 default:
891                     *pi_data += val;
892             }
893         }
894
895         if (ufd[0].revents & POLLOUT)
896         {
897             ssize_t val = write (fds[0], p_in, i_in);
898             switch (val)
899             {
900                 case -1:
901                 case 0:
902                     i_in = 0;
903                     shutdown (fds[0], SHUT_WR);
904                     break;
905
906                 default:
907                     i_in -= val;
908                     p_in += val;
909             }
910         }
911     }
912
913     close (fds[0]);
914
915     while (waitpid (pid, &i_status, 0) == -1);
916
917     if (WIFEXITED (i_status))
918     {
919         i_status = WEXITSTATUS (i_status);
920         if (i_status)
921             msg_Warn (p_object,  "child %s (PID %d) exited with error code %d",
922                       ppsz_argv[0], (int)pid, i_status);
923     }
924     else
925     if (WIFSIGNALED (i_status)) // <-- this should be redumdant a check
926     {
927         i_status = WTERMSIG (i_status);
928         msg_Warn (p_object, "child %s (PID %d) exited on signal %d (%s)",
929                   ppsz_argv[0], (int)pid, i_status, strsignal (i_status));
930     }
931
932 #elif defined( WIN32 ) && !defined( UNDER_CE )
933     SECURITY_ATTRIBUTES saAttr;
934     PROCESS_INFORMATION piProcInfo;
935     STARTUPINFO siStartInfo;
936     BOOL bFuncRetn = FALSE;
937     HANDLE hChildStdinRd, hChildStdinWr, hChildStdoutRd, hChildStdoutWr;
938     DWORD i_status;
939     char *psz_cmd = NULL, *p_env = NULL, *p = NULL;
940     char **ppsz_parser;
941     int i_size;
942
943     /* Set the bInheritHandle flag so pipe handles are inherited. */
944     saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
945     saAttr.bInheritHandle = TRUE;
946     saAttr.lpSecurityDescriptor = NULL;
947
948     /* Create a pipe for the child process's STDOUT. */
949     if ( !CreatePipe( &hChildStdoutRd, &hChildStdoutWr, &saAttr, 0 ) )
950     {
951         msg_Err( p_object, "stdout pipe creation failed" );
952         return -1;
953     }
954
955     /* Ensure the read handle to the pipe for STDOUT is not inherited. */
956     SetHandleInformation( hChildStdoutRd, HANDLE_FLAG_INHERIT, 0 );
957
958     /* Create a pipe for the child process's STDIN. */
959     if ( !CreatePipe( &hChildStdinRd, &hChildStdinWr, &saAttr, 0 ) )
960     {
961         msg_Err( p_object, "stdin pipe creation failed" );
962         return -1;
963     }
964
965     /* Ensure the write handle to the pipe for STDIN is not inherited. */
966     SetHandleInformation( hChildStdinWr, HANDLE_FLAG_INHERIT, 0 );
967
968     /* Set up members of the PROCESS_INFORMATION structure. */
969     ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
970
971     /* Set up members of the STARTUPINFO structure. */
972     ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
973     siStartInfo.cb = sizeof(STARTUPINFO);
974     siStartInfo.hStdError = hChildStdoutWr;
975     siStartInfo.hStdOutput = hChildStdoutWr;
976     siStartInfo.hStdInput = hChildStdinRd;
977     siStartInfo.wShowWindow = SW_HIDE;
978     siStartInfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
979
980     /* Set up the command line. */
981     psz_cmd = malloc(32768);
982     if( !psz_cmd )
983         return -1;
984     psz_cmd[0] = '\0';
985     i_size = 32768;
986     ppsz_parser = &ppsz_argv[0];
987     while ( ppsz_parser[0] != NULL && i_size > 0 )
988     {
989         /* Protect the last argument with quotes ; the other arguments
990          * are supposed to be already protected because they have been
991          * passed as a command-line option. */
992         if ( ppsz_parser[1] == NULL )
993         {
994             strncat( psz_cmd, "\"", i_size );
995             i_size--;
996         }
997         strncat( psz_cmd, *ppsz_parser, i_size );
998         i_size -= strlen( *ppsz_parser );
999         if ( ppsz_parser[1] == NULL )
1000         {
1001             strncat( psz_cmd, "\"", i_size );
1002             i_size--;
1003         }
1004         strncat( psz_cmd, " ", i_size );
1005         i_size--;
1006         ppsz_parser++;
1007     }
1008
1009     /* Set up the environment. */
1010     p = p_env = malloc(32768);
1011     if( !p )
1012     {
1013         free( psz_cmd );
1014         return -1;
1015     }
1016
1017     i_size = 32768;
1018     ppsz_parser = &ppsz_env[0];
1019     while ( *ppsz_parser != NULL && i_size > 0 )
1020     {
1021         memcpy( p, *ppsz_parser,
1022                 __MIN((int)(strlen(*ppsz_parser) + 1), i_size) );
1023         p += strlen(*ppsz_parser) + 1;
1024         i_size -= strlen(*ppsz_parser) + 1;
1025         ppsz_parser++;
1026     }
1027     *p = '\0';
1028
1029     /* Create the child process. */
1030     bFuncRetn = CreateProcess( NULL,
1031           psz_cmd,       // command line
1032           NULL,          // process security attributes
1033           NULL,          // primary thread security attributes
1034           TRUE,          // handles are inherited
1035           0,             // creation flags
1036           p_env,
1037           psz_cwd,
1038           &siStartInfo,  // STARTUPINFO pointer
1039           &piProcInfo ); // receives PROCESS_INFORMATION
1040
1041     free( psz_cmd );
1042     free( p_env );
1043
1044     if ( bFuncRetn == 0 )
1045     {
1046         msg_Err( p_object, "child creation failed" );
1047         return -1;
1048     }
1049
1050     /* Read from a file and write its contents to a pipe. */
1051     while ( i_in > 0 && !p_object->b_die )
1052     {
1053         DWORD i_written;
1054         if ( !WriteFile( hChildStdinWr, p_in, i_in, &i_written, NULL ) )
1055             break;
1056         i_in -= i_written;
1057         p_in += i_written;
1058     }
1059
1060     /* Close the pipe handle so the child process stops reading. */
1061     CloseHandle(hChildStdinWr);
1062
1063     /* Close the write end of the pipe before reading from the
1064      * read end of the pipe. */
1065     CloseHandle(hChildStdoutWr);
1066
1067     /* Read output from the child process. */
1068     *pi_data = 0;
1069     if( *pp_data )
1070         free( pp_data );
1071     *pp_data = NULL;
1072     *pp_data = malloc( 1025 );  /* +1 for \0 */
1073
1074     while ( !p_object->b_die )
1075     {
1076         DWORD i_read;
1077         if ( !ReadFile( hChildStdoutRd, &(*pp_data)[*pi_data], 1024, &i_read,
1078                         NULL )
1079               || i_read == 0 )
1080             break;
1081         *pi_data += i_read;
1082         *pp_data = realloc( *pp_data, *pi_data + 1025 );
1083     }
1084
1085     while ( !p_object->b_die
1086              && !GetExitCodeProcess( piProcInfo.hProcess, &i_status )
1087              && i_status != STILL_ACTIVE )
1088         msleep( 10000 );
1089
1090     CloseHandle(piProcInfo.hProcess);
1091     CloseHandle(piProcInfo.hThread);
1092
1093     if ( i_status )
1094         msg_Warn( p_object,
1095                   "child %s returned with error code %ld",
1096                   ppsz_argv[0], i_status );
1097
1098 #else
1099     msg_Err( p_object, "vlc_execve called but no implementation is available" );
1100     return -1;
1101
1102 #endif
1103
1104     if (*pp_data == NULL)
1105         return -1;
1106
1107     (*pp_data)[*pi_data] = '\0';
1108     return 0;
1109 }