1 /*****************************************************************************
2 * libc.c: Extra libc function for some systems.
3 *****************************************************************************
4 * Copyright (C) 2002 the VideoLAN team
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>
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program; if not, write to the Free Software
25 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
26 *****************************************************************************/
27 #include <string.h> /* strdup() */
38 #if defined(HAVE_ICONV)
47 # include <sys/time.h>
50 # include <sys/wait.h>
53 /*****************************************************************************
54 * getenv: just in case, but it should never be called
55 *****************************************************************************/
56 #if !defined( HAVE_GETENV )
57 char *vlc_getenv( const char *name )
63 /*****************************************************************************
64 * strdup: returns a malloc'd copy of a string
65 *****************************************************************************/
66 #if !defined( HAVE_STRDUP )
67 char *vlc_strdup( const char *string )
69 return strndup( string, strlen( string ) );
73 /*****************************************************************************
74 * strndup: returns a malloc'd copy of at most n bytes of string
75 * Does anyone know whether or not it will be present in Jaguar?
76 *****************************************************************************/
77 #if !defined( HAVE_STRNDUP )
78 char *vlc_strndup( const char *string, size_t n )
81 size_t len = strlen( string );
83 len = __MIN( len, n );
84 psz = (char*)malloc( len + 1 );
88 memcpy( (void*)psz, (const void*)string, len );
96 /*****************************************************************************
97 * strcasecmp: compare two strings ignoring case
98 *****************************************************************************/
99 #if !defined( HAVE_STRCASECMP ) && !defined( HAVE_STRICMP )
100 int vlc_strcasecmp( const char *s1, const char *s2 )
103 if( !s1 || !s2 ) return -1;
110 if( c1 != c2 ) return (c1 < c2 ? -1 : 1);
114 if( !*s1 && !*s2 ) return 0;
115 else return (*s1 ? 1 : -1);
119 /*****************************************************************************
120 * strncasecmp: compare n chars from two strings ignoring case
121 *****************************************************************************/
122 #if !defined( HAVE_STRNCASECMP ) && !defined( HAVE_STRNICMP )
123 int vlc_strncasecmp( const char *s1, const char *s2, size_t n )
126 if( !s1 || !s2 ) return -1;
128 while( n > 0 && *s1 && *s2 )
133 if( c1 != c2 ) return (c1 < c2 ? -1 : 1);
137 if( !n || (!*s1 && !*s2) ) return 0;
138 else return (*s1 ? 1 : -1);
142 /******************************************************************************
143 * strcasestr: find a substring (little) in another substring (big)
144 * Case sensitive. Return NULL if not found, return big if little == null
145 *****************************************************************************/
146 #if !defined( HAVE_STRCASESTR ) && !defined( HAVE_STRISTR )
147 char * vlc_strcasestr( const char *psz_big, const char *psz_little )
149 char *p_pos = (char *)psz_big;
151 if( !psz_big || !psz_little || !*psz_little ) return p_pos;
155 if( toupper( *p_pos ) == toupper( *psz_little ) )
157 char * psz_cur1 = p_pos + 1;
158 char * psz_cur2 = (char *)psz_little + 1;
159 while( *psz_cur1 && *psz_cur2 &&
160 toupper( *psz_cur1 ) == toupper( *psz_cur2 ) )
165 if( !*psz_cur2 ) return p_pos;
173 /*****************************************************************************
175 *****************************************************************************/
176 #if !defined(HAVE_VASPRINTF) || defined(SYS_DARWIN) || defined(SYS_BEOS)
177 int vlc_vasprintf(char **strp, const char *fmt, va_list ap)
179 /* Guess we need no more than 100 bytes. */
181 char *p = malloc( i_size );
192 /* Try to print in the allocated space. */
193 n = vsnprintf( p, i_size, fmt, ap );
195 /* If that worked, return the string. */
196 if (n > -1 && n < i_size)
201 /* Else try again with more space. */
202 if (n > -1) /* glibc 2.1 */
204 i_size = n+1; /* precisely what is needed */
208 i_size *= 2; /* twice the old size */
210 if( (p = realloc( p, i_size ) ) == NULL)
219 /*****************************************************************************
221 *****************************************************************************/
222 #if !defined(HAVE_ASPRINTF) || defined(SYS_DARWIN) || defined(SYS_BEOS)
223 int vlc_asprintf( char **strp, const char *fmt, ... )
228 va_start( args, fmt );
229 i_ret = vasprintf( strp, fmt, args );
236 /*****************************************************************************
237 * atof: convert a string to a double.
238 *****************************************************************************/
239 #if !defined( HAVE_ATOF )
240 double vlc_atof( const char *nptr )
244 int i_len = strlen( nptr ) + 1;
246 psz_tmp = malloc( i_len * sizeof(wchar_t) );
247 MultiByteToWideChar( CP_ACP, 0, nptr, -1, psz_tmp, i_len );
248 f_result = wcstod( psz_tmp, NULL );
255 /*****************************************************************************
256 * strtoll: convert a string to a 64 bits int.
257 *****************************************************************************/
258 #if !defined( HAVE_STRTOLL )
259 int64_t vlc_strtoll( const char *nptr, char **endptr, int base )
262 int sign = 1, newbase = base ? base : 10;
264 while( isspace(*nptr) ) nptr++;
272 /* Try to detect base */
285 if( base && newbase != base )
287 if( endptr ) *endptr = (char *)nptr;
294 while( *nptr >= '0' && *nptr <= '9' )
297 i_value += ( *nptr++ - '0' );
299 if( endptr ) *endptr = (char *)nptr;
303 while( (*nptr >= '0' && *nptr <= '9') ||
304 (*nptr >= 'a' && *nptr <= 'f') ||
305 (*nptr >= 'A' && *nptr <= 'F') )
308 if(*nptr >= '0' && *nptr <= '9') i_valc = *nptr - '0';
309 else if(*nptr >= 'a' && *nptr <= 'f') i_valc = *nptr - 'a' +10;
310 else if(*nptr >= 'A' && *nptr <= 'F') i_valc = *nptr - 'A' +10;
315 if( endptr ) *endptr = (char *)nptr;
319 i_value = strtol( nptr, endptr, newbase );
323 return i_value * sign;
327 /*****************************************************************************
328 * atoll: convert a string to a 64 bits int.
329 *****************************************************************************/
330 #if !defined( HAVE_ATOLL )
331 int64_t vlc_atoll( const char *nptr )
333 return strtoll( nptr, (char **)NULL, 10 );
337 /*****************************************************************************
338 * vlc_*dir_wrapper: wrapper under Windows to return the list of drive letters
339 * when called with an empty argument or just '\'
340 *****************************************************************************/
341 #if defined(WIN32) || defined(UNDER_CE)
343 #define WIN32_LEAN_AND_MEAN
344 #include <windows.h> /* for GetLogicalDrives */
346 typedef struct vlc_DIR
350 struct dirent dd_dir;
351 vlc_bool_t b_insert_back;
354 void *vlc_opendir_wrapper( const char *psz_path )
359 if ( psz_path == NULL || psz_path[0] == '\0'
360 || (psz_path[0] == '\\' && psz_path[1] == '\0') )
362 /* Special mode to list drive letters */
363 p_dir = malloc( sizeof(vlc_DIR) );
364 p_dir->p_real_dir = NULL;
365 p_dir->i_drives = GetLogicalDrives();
366 return (void *)p_dir;
369 p_real_dir = opendir( psz_path );
370 if ( p_real_dir == NULL )
373 p_dir = malloc( sizeof(vlc_DIR) );
374 p_dir->p_real_dir = p_real_dir;
375 p_dir->b_insert_back = ( psz_path[1] == ':' && psz_path[2] == '\\'
376 && psz_path[3] =='\0' );
377 return (void *)p_dir;
380 struct dirent *vlc_readdir_wrapper( void *_p_dir )
382 vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
386 if ( p_dir->p_real_dir != NULL )
388 if ( p_dir->b_insert_back )
390 p_dir->dd_dir.d_ino = 0;
391 p_dir->dd_dir.d_reclen = 0;
392 p_dir->dd_dir.d_namlen = 2;
393 strcpy( p_dir->dd_dir.d_name, ".." );
394 p_dir->b_insert_back = VLC_FALSE;
395 return &p_dir->dd_dir;
398 return readdir( p_dir->p_real_dir );
401 /* Drive letters mode */
402 i_drives = p_dir->i_drives;
404 return NULL; /* end */
406 for ( i = 0; i < sizeof(DWORD)*8; i++, i_drives >>= 1 )
407 if ( i_drives & 1 ) break;
410 return NULL; /* this should not happen */
412 sprintf( p_dir->dd_dir.d_name, "%c:\\", 'A' + i );
413 p_dir->dd_dir.d_namlen = strlen(p_dir->dd_dir.d_name);
414 p_dir->i_drives &= ~(1UL << i);
415 return &p_dir->dd_dir;
418 int vlc_closedir_wrapper( void *_p_dir )
420 vlc_DIR *p_dir = (vlc_DIR *)_p_dir;
422 if ( p_dir->p_real_dir != NULL )
424 int i_ret = closedir( p_dir->p_real_dir );
433 void *vlc_opendir_wrapper( const char *psz_path )
435 return (void *)opendir( psz_path );
437 struct dirent *vlc_readdir_wrapper( void *_p_dir )
439 return readdir( (DIR *)_p_dir );
441 int vlc_closedir_wrapper( void *_p_dir )
443 return closedir( (DIR *)_p_dir );
447 /*****************************************************************************
448 * scandir: scan a directory alpha-sorted
449 *****************************************************************************/
450 #if !defined( HAVE_SCANDIR )
451 int vlc_alphasort( const struct dirent **a, const struct dirent **b )
453 return strcoll( (*a)->d_name, (*b)->d_name );
456 int vlc_scandir( const char *name, struct dirent ***namelist,
457 int (*filter) ( const struct dirent * ),
458 int (*compar) ( const struct dirent **,
459 const struct dirent ** ) )
462 struct dirent * p_content;
463 struct dirent ** pp_list;
466 if( !namelist || !( p_dir = vlc_opendir_wrapper( name ) ) ) return -1;
470 while( ( p_content = vlc_readdir_wrapper( p_dir ) ) )
472 if( filter && !filter( p_content ) )
476 pp_list = realloc( pp_list, ( ret + 1 ) * sizeof( struct dirent * ) );
477 size = sizeof( struct dirent ) + strlen( p_content->d_name ) + 1;
478 pp_list[ret] = malloc( size );
479 memcpy( pp_list[ret], p_content, size );
483 vlc_closedir_wrapper( p_dir );
487 qsort( pp_list, ret, sizeof( struct dirent * ),
488 (int (*)(const void *, const void *)) compar );
496 /*****************************************************************************
497 * dgettext: gettext for plugins.
498 *****************************************************************************/
499 char *vlc_dgettext( const char *package, const char *msgid )
501 #if defined( ENABLE_NLS ) \
502 && ( defined(HAVE_GETTEXT) || defined(HAVE_INCLUDED_GETTEXT) )
503 return dgettext( package, msgid );
505 return (char *)msgid;
509 /*****************************************************************************
510 * count_utf8_string: returns the number of characters in the string.
511 *****************************************************************************/
512 static int count_utf8_string( const char *psz_string )
514 int i = 0, i_count = 0;
515 while( psz_string[ i ] != 0 )
517 if( ((unsigned char *)psz_string)[ i ] < 0x80UL ) i_count++;
523 /*****************************************************************************
524 * wraptext: inserts \n at convenient places to wrap the text.
525 * Returns the modified string in a new buffer.
526 *****************************************************************************/
527 char *vlc_wraptext( const char *psz_text, int i_line, vlc_bool_t b_utf8 )
530 char *psz_line, *psz_new_text;
532 psz_line = psz_new_text = strdup( psz_text );
535 i_len = count_utf8_string( psz_text );
537 i_len = strlen( psz_text );
539 while( i_len > i_line )
541 /* Look if there is a newline somewhere. */
542 char *psz_parser = psz_line;
544 while( i_count <= i_line && *psz_parser != '\n' )
548 while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
553 if( *psz_parser == '\n' )
555 i_len -= (i_count + 1);
556 psz_line = psz_parser + 1;
560 /* Find the furthest space. */
561 while( psz_parser > psz_line && *psz_parser != ' ' )
565 while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser--;
570 if( *psz_parser == ' ' )
573 i_len -= (i_count + 1);
574 psz_line = psz_parser + 1;
578 /* Wrapping has failed. Find the first space or newline */
579 while( i_count < i_len && *psz_parser != ' ' && *psz_parser != '\n' )
583 while( *((unsigned char *)psz_parser) >= 0x80UL ) psz_parser++;
588 if( i_count < i_len ) *psz_parser = '\n';
589 i_len -= (i_count + 1);
590 psz_line = psz_parser + 1;
596 /*****************************************************************************
598 *****************************************************************************/
599 vlc_iconv_t vlc_iconv_open( const char *tocode, const char *fromcode )
601 #if defined(HAVE_ICONV)
602 return iconv_open( tocode, fromcode );
608 size_t vlc_iconv( vlc_iconv_t cd, char **inbuf, size_t *inbytesleft,
609 char **outbuf, size_t *outbytesleft )
611 #if defined(HAVE_ICONV)
612 return iconv( cd, inbuf, inbytesleft, outbuf, outbytesleft );
614 int i_bytes = __MIN(*inbytesleft, *outbytesleft);
615 if( !inbuf || !outbuf || !i_bytes ) return (size_t)(-1);
616 memcpy( *outbuf, *inbuf, i_bytes );
619 inbytesleft -= i_bytes;
620 outbytesleft -= i_bytes;
625 int vlc_iconv_close( vlc_iconv_t cd )
627 #if defined(HAVE_ICONV)
628 return iconv_close( cd );
634 /*****************************************************************************
636 * (adapted from libavcodec, author Michael Niedermayer <michaelni@gmx.at>)
637 *****************************************************************************/
638 vlc_bool_t vlc_ureduce( unsigned *pi_dst_nom, unsigned *pi_dst_den,
639 uint64_t i_nom, uint64_t i_den, uint64_t i_max )
641 vlc_bool_t b_exact = 1;
651 i_gcd = GCD( i_nom, i_den );
655 if( i_max == 0 ) i_max = I64C(0xFFFFFFFF);
657 if( i_nom > i_max || i_den > i_max )
659 uint64_t i_a0_num = 0, i_a0_den = 1, i_a1_num = 1, i_a1_den = 0;
664 uint64_t i_x = i_nom / i_den;
665 uint64_t i_a2n = i_x * i_a1_num + i_a0_num;
666 uint64_t i_a2d = i_x * i_a1_den + i_a0_den;
668 if( i_a2n > i_max || i_a2d > i_max ) break;
672 i_a0_num = i_a1_num; i_a0_den = i_a1_den;
673 i_a1_num = i_a2n; i_a1_den = i_a2d;
674 if( i_nom == 0 ) break;
675 i_x = i_nom; i_nom = i_den; i_den = i_x;
687 /*************************************************************************
688 * vlc_parse_cmdline: Command line parsing into elements.
690 * The command line is composed of space/tab separated arguments.
691 * Quotes can be used as argument delimiters and a backslash can be used to
693 *************************************************************************/
694 static void find_end_quote( char **s, char **ppsz_parser, int i_quote )
703 (*ppsz_parser)++; (*s)++;
706 else if( **s == '"' || **s == '\'' )
708 /* Preceeded by a number of '\' which we erase. */
709 *ppsz_parser -= i_bcount / 2;
712 /* '\\' followed by a '"' or '\'' */
715 (*ppsz_parser)++; (*s)++;
727 /* Different quoting */
730 (*ppsz_parser)++; (*s)++;
731 find_end_quote( s, ppsz_parser, i_quote );
733 (*ppsz_parser)++; (*s)++;
740 /* A regular character */
742 (*ppsz_parser)++; (*s)++;
748 char **vlc_parse_cmdline( const char *psz_cmdline, int *i_args )
752 char *s, *psz_parser, *psz_arg, *psz_orig;
755 if( !psz_cmdline ) return 0;
756 psz_orig = strdup( psz_cmdline );
757 psz_arg = psz_parser = s = psz_orig;
761 if( *s == '\t' || *s == ' ' )
763 /* We have a complete argument */
765 TAB_APPEND( argc, argv, strdup(psz_arg) );
767 /* Skip trailing spaces/tabs */
768 do{ s++; } while( *s == '\t' || *s == ' ' );
771 psz_arg = psz_parser = s;
774 else if( *s == '\\' )
776 *psz_parser++ = *s++;
779 else if( *s == '"' || *s == '\'' )
781 if( ( i_bcount & 1 ) == 0 )
783 /* Preceeded by an even number of '\', this is half that
784 * number of '\', plus a quote which we erase. */
786 psz_parser -= i_bcount / 2;
788 find_end_quote( &s, &psz_parser, i_quote );
793 /* Preceeded by an odd number of '\', this is half that
794 * number of '\' followed by a '"' */
795 psz_parser = psz_parser - i_bcount/2 - 1;
803 /* A regular character */
804 *psz_parser++ = *s++;
809 /* Take care of the last arg */
813 TAB_APPEND( argc, argv, strdup(psz_arg) );
816 if( i_args ) *i_args = argc;
821 /*************************************************************************
822 * vlc_execve: Execute an external program with a given environment,
823 * wait until it finishes and return its standard output
824 *************************************************************************/
825 int __vlc_execve( vlc_object_t *p_object, int i_argc, char **ppsz_argv,
826 char **ppsz_env, char *psz_cwd, char *p_in, int i_in,
827 char **pp_data, int *pi_data )
837 if ( (i_child_pid = fork()) == -1 )
839 msg_Err( p_object, "unable to fork (%s)", strerror(errno) );
843 if ( i_child_pid == 0 )
855 if ( psz_cwd != NULL )
857 execve( ppsz_argv[0], ppsz_argv, ppsz_env );
864 close( pi_stdin[0] );
867 *pp_data = malloc( 1025 ); /* +1 for \0 */
869 while ( !p_object->b_die )
872 fd_set readfds, writefds;
876 FD_ZERO( &writefds );
877 FD_SET( pi_stdout[0], &readfds );
879 FD_SET( pi_stdin[0], &writefds );
884 i_ret = select( pi_stdin[0] > pi_stdout[0] ? pi_stdin[0] + 1 :
885 pi_stdout[0] + 1, &readfds, &writefds, NULL, &tv );
888 if ( FD_ISSET( pi_stdout[0], &readfds ) )
890 ssize_t i_read = read( pi_stdout[0], &(*pp_data)[*pi_data],
895 *pp_data = realloc( *pp_data, *pi_data + 1025 );
898 if ( FD_ISSET( pi_stdin[0], &writefds ) )
900 ssize_t i_write = write( pi_stdin[0], p_in, __MIN(i_in, 1024) );
908 close( pi_stdin[0] );
912 if ( waitpid( i_child_pid, &i_status, WNOHANG ) == i_child_pid )
914 if ( WIFEXITED( i_status ) )
916 if ( WEXITSTATUS( i_status ) )
919 "child %s returned with error code %d",
920 ppsz_argv[0], WEXITSTATUS( i_status ) );
925 if ( WIFSIGNALED( i_status ) )
928 "child %s quit on signal %d", ppsz_argv[0],
929 WTERMSIG( i_status ) );
933 close( pi_stdin[0] );
934 close( pi_stdout[0] );
938 if ( i_ret < 0 && errno != EINTR )
940 msg_Warn( p_object, "select failed (%s)", strerror(errno) );
945 msg_Err( p_object, "vlc_execve called but no implementation is available" );
950 (*pp_data)[*pi_data] = '\0';