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