2 * Helper functions for the Wine tools
4 * Copyright 2021 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #ifndef __WINE_TOOLS_H
22 #define __WINE_TOOLS_H
24 #ifndef __WINE_CONFIG_H
25 # error You must include config.h to use this header
33 #include <sys/types.h>
39 #ifdef HAVE_SYS_SYSCTL_H
40 # include <sys/sysctl.h>
47 # define mkdir(path,mode) mkdir(path)
49 # define S_ISREG(mod) (((mod) & _S_IFMT) == _S_IFREG)
53 # define pclose _pclose
54 # define strtoll _strtoi64
55 # define strtoull _strtoui64
56 # define strncasecmp _strnicmp
57 # define strcasecmp _stricmp
60 extern char **environ
;
62 # include <sys/wait.h>
68 # if defined(__x86_64__) || defined(__aarch64__) || defined(__powerpc64__)
71 # define __int64 long long
76 #if !defined(__GNUC__) && !defined(__attribute__)
77 #define __attribute__(x)
81 #define max(a,b) (((a) > (b)) ? (a) : (b))
84 #define min(a,b) (((a) < (b)) ? (a) : (b))
88 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
93 enum { CPU_i386
, CPU_x86_64
, CPU_ARM
, CPU_ARM64
} cpu
;
109 static inline void *xmalloc( size_t size
)
111 void *res
= malloc( size
? size
: 1 );
115 fprintf( stderr
, "Virtual memory exhausted.\n" );
121 static inline void *xrealloc (void *ptr
, size_t size
)
123 void *res
= realloc( ptr
, size
);
125 if (size
&& res
== NULL
)
127 fprintf( stderr
, "Virtual memory exhausted.\n" );
133 static inline char *xstrdup( const char *str
)
135 return strcpy( xmalloc( strlen(str
)+1 ), str
);
138 static inline int strendswith( const char *str
, const char *end
)
140 int l
= strlen( str
);
141 int m
= strlen( end
);
142 return l
>= m
&& !strcmp( str
+ l
- m
, end
);
145 static char *strmake( const char* fmt
, ... ) __attribute__ ((__format__ (__printf__
, 1, 2)));
146 static inline char *strmake( const char* fmt
, ... )
154 char *p
= xmalloc( size
);
156 n
= vsnprintf( p
, size
, fmt
, ap
);
158 if (n
== -1) size
*= 2;
159 else if ((size_t)n
>= size
) size
= n
+ 1;
165 /* string array functions */
169 unsigned int count
; /* strings in use */
170 unsigned int size
; /* total allocated size */
174 static const struct strarray empty_strarray
;
176 static inline void strarray_add( struct strarray
*array
, const char *str
)
178 if (array
->count
== array
->size
)
180 if (array
->size
) array
->size
*= 2;
181 else array
->size
= 16;
182 array
->str
= xrealloc( array
->str
, sizeof(array
->str
[0]) * array
->size
);
184 array
->str
[array
->count
++] = str
;
187 static inline void strarray_addall( struct strarray
*array
, struct strarray added
)
191 for (i
= 0; i
< added
.count
; i
++) strarray_add( array
, added
.str
[i
] );
194 static inline int strarray_exists( const struct strarray
*array
, const char *str
)
198 for (i
= 0; i
< array
->count
; i
++) if (!strcmp( array
->str
[i
], str
)) return 1;
202 static inline void strarray_add_uniq( struct strarray
*array
, const char *str
)
204 if (!strarray_exists( array
, str
)) strarray_add( array
, str
);
207 static inline void strarray_addall_uniq( struct strarray
*array
, struct strarray added
)
211 for (i
= 0; i
< added
.count
; i
++) strarray_add_uniq( array
, added
.str
[i
] );
214 static inline struct strarray
strarray_fromstring( const char *str
, const char *delim
)
216 struct strarray array
= empty_strarray
;
217 char *buf
= xstrdup( str
);
220 for (tok
= strtok( buf
, delim
); tok
; tok
= strtok( NULL
, delim
))
221 strarray_add( &array
, xstrdup( tok
));
226 static inline struct strarray
strarray_frompath( const char *path
)
228 if (!path
) return empty_strarray
;
230 return strarray_fromstring( path
, ";" );
232 return strarray_fromstring( path
, ":" );
236 static inline char *strarray_tostring( struct strarray array
, const char *sep
)
239 unsigned int i
, len
= 1 + (array
.count
- 1) * strlen(sep
);
241 if (!array
.count
) return xstrdup("");
242 for (i
= 0; i
< array
.count
; i
++) len
+= strlen( array
.str
[i
] );
243 str
= xmalloc( len
);
244 strcpy( str
, array
.str
[0] );
245 for (i
= 1; i
< array
.count
; i
++)
248 strcat( str
, array
.str
[i
] );
253 static inline void strarray_qsort( struct strarray
*array
, int (*func
)(const char **, const char **) )
255 if (array
->count
) qsort( array
->str
, array
->count
, sizeof(*array
->str
), (void *)func
);
258 static inline const char *strarray_bsearch( const struct strarray
*array
, const char *str
,
259 int (*func
)(const char **, const char **) )
263 if (array
->count
) res
= bsearch( &str
, array
->str
, array
->count
, sizeof(*array
->str
), (void *)func
);
264 return res
? *res
: NULL
;
267 static inline void strarray_trace( struct strarray args
)
271 for (i
= 0; i
< args
.count
; i
++)
273 if (strpbrk( args
.str
[i
], " \t\n\r")) printf( "\"%s\"", args
.str
[i
] );
274 else printf( "%s", args
.str
[i
] );
275 putchar( i
< args
.count
- 1 ? ' ' : '\n' );
279 static inline int strarray_spawn( struct strarray args
)
282 strarray_add( &args
, NULL
);
283 return _spawnvp( _P_WAIT
, args
.str
[0], args
.str
);
288 strarray_add( &args
, NULL
);
289 if (posix_spawnp( &pid
, args
.str
[0], NULL
, NULL
, (char **)args
.str
, environ
))
292 while (pid
!= (wret
= waitpid( pid
, &status
, 0 )))
293 if (wret
== -1 && errno
!= EINTR
) break;
295 if (pid
== wret
&& WIFEXITED(status
)) return WEXITSTATUS(status
);
296 return 255; /* abnormal exit with an abort or an interrupt */
300 static inline char *get_basename( const char *file
)
302 const char *ret
= strrchr( file
, '/' );
303 return xstrdup( ret
? ret
+ 1 : file
);
306 static inline char *get_basename_noext( const char *file
)
308 char *ext
, *ret
= get_basename( file
);
309 if ((ext
= strrchr( ret
, '.' ))) *ext
= 0;
313 static inline char *get_dirname( const char *file
)
315 const char *end
= strrchr( file
, '/' );
316 if (!end
) return xstrdup( "." );
317 if (end
== file
) end
++;
318 return strmake( "%.*s", (int)(end
- file
), file
);
321 static inline char *replace_extension( const char *name
, const char *old_ext
, const char *new_ext
)
323 int name_len
= strlen( name
);
325 if (strendswith( name
, old_ext
)) name_len
-= strlen( old_ext
);
326 return strmake( "%.*s%s", name_len
, name
, new_ext
);
329 /* temp files management */
331 extern const char *temp_dir
;
332 extern struct strarray temp_files
;
334 static inline char *make_temp_dir(void)
336 unsigned int value
= time(NULL
) + getpid();
339 const char *tmpdir
= NULL
;
341 for (count
= 0; count
< 0x8000; count
++)
344 name
= strmake( "%s/tmp%08x", tmpdir
, value
);
346 name
= strmake( "tmp%08x", value
);
347 if (!mkdir( name
, 0700 )) return name
;
349 if (errno
== EACCES
&& !tmpdir
)
351 if (!(tmpdir
= getenv("TMPDIR"))) tmpdir
= "/tmp";
355 fprintf( stderr
, "failed to create directory for temp files\n" );
359 static inline char *make_temp_file( const char *prefix
, const char *suffix
)
361 static unsigned int value
;
365 if (!temp_dir
) temp_dir
= make_temp_dir();
366 if (!suffix
) suffix
= "";
367 if (!prefix
) prefix
= "tmp";
368 else prefix
= get_basename_noext( prefix
);
370 for (count
= 0; count
< 0x8000; count
++)
372 name
= strmake( "%s/%s-%08x%s", temp_dir
, prefix
, value
++, suffix
);
373 fd
= open( name
, O_RDWR
| O_CREAT
| O_EXCL
, 0600 );
376 #ifdef HAVE_SIGPROCMASK /* block signals while manipulating the temp files list */
377 sigset_t mask_set
, old_set
;
379 sigemptyset( &mask_set
);
380 sigaddset( &mask_set
, SIGHUP
);
381 sigaddset( &mask_set
, SIGTERM
);
382 sigaddset( &mask_set
, SIGINT
);
383 sigprocmask( SIG_BLOCK
, &mask_set
, &old_set
);
384 strarray_add( &temp_files
, name
);
385 sigprocmask( SIG_SETMASK
, &old_set
, NULL
);
387 strarray_add( &temp_files
, name
);
394 fprintf( stderr
, "failed to create temp file for %s%s in %s\n", prefix
, suffix
, temp_dir
);
398 static inline void remove_temp_files(void)
402 for (i
= 0; i
< temp_files
.count
; i
++) if (temp_files
.str
[i
]) unlink( temp_files
.str
[i
] );
403 if (temp_dir
) rmdir( temp_dir
);
407 static inline void init_signals( void (*cleanup
)(int) )
409 signal( SIGTERM
, cleanup
);
410 signal( SIGINT
, cleanup
);
412 signal( SIGHUP
, cleanup
);
417 static inline void *read_file( const char *name
, size_t *size
)
423 if ((fd
= open( name
, O_RDONLY
| O_BINARY
)) == -1) return NULL
;
425 data
= xmalloc( st
.st_size
);
426 res
= read( fd
, data
, st
.st_size
);
439 static inline struct target
get_default_target(void)
441 struct target target
;
443 target
.cpu
= CPU_i386
;
444 #elif defined(__x86_64__)
445 target
.cpu
= CPU_x86_64
;
446 #elif defined(__arm__)
447 target
.cpu
= CPU_ARM
;
448 #elif defined(__aarch64__)
449 target
.cpu
= CPU_ARM64
;
451 #error Unsupported CPU
455 target
.platform
= PLATFORM_APPLE
;
456 #elif defined(__ANDROID__)
457 target
.platform
= PLATFORM_ANDROID
;
458 #elif defined(__linux__)
459 target
.platform
= PLATFORM_LINUX
;
460 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
461 target
.platform
= PLATFORM_FREEBSD
;
463 target
.platform
= PLATFORM_SOLARIS
;
464 #elif defined(__CYGWIN__)
465 target
.platform
= PLATFORM_CYGWIN
;
466 #elif defined(_WIN32)
467 target
.platform
= PLATFORM_MINGW
;
469 target
.platform
= PLATFORM_UNSPECIFIED
;
476 static inline unsigned int get_target_ptr_size( struct target target
)
478 static const unsigned int sizes
[] =
485 return sizes
[target
.cpu
];
489 static inline void set_target_ptr_size( struct target
*target
, unsigned int size
)
494 if (size
== 8) target
->cpu
= CPU_x86_64
;
497 if (size
== 4) target
->cpu
= CPU_i386
;
500 if (size
== 8) target
->cpu
= CPU_ARM64
;
503 if (size
== 4) target
->cpu
= CPU_ARM
;
509 static inline int get_cpu_from_name( const char *name
)
517 { "i386", CPU_i386
},
518 { "i486", CPU_i386
},
519 { "i586", CPU_i386
},
520 { "i686", CPU_i386
},
521 { "i786", CPU_i386
},
522 { "x86_64", CPU_x86_64
},
523 { "amd64", CPU_x86_64
},
524 { "aarch64", CPU_ARM64
},
525 { "arm64", CPU_ARM64
},
530 for (i
= 0; i
< ARRAY_SIZE(cpu_names
); i
++)
531 if (!strncmp( cpu_names
[i
].name
, name
, strlen(cpu_names
[i
].name
) )) return cpu_names
[i
].cpu
;
536 static inline int get_platform_from_name( const char *name
)
544 { "macos", PLATFORM_APPLE
},
545 { "darwin", PLATFORM_APPLE
},
546 { "android", PLATFORM_ANDROID
},
547 { "linux", PLATFORM_LINUX
},
548 { "freebsd", PLATFORM_FREEBSD
},
549 { "solaris", PLATFORM_SOLARIS
},
550 { "mingw32", PLATFORM_MINGW
},
551 { "windows-gnu", PLATFORM_MINGW
},
552 { "winnt", PLATFORM_MINGW
},
553 { "windows", PLATFORM_WINDOWS
},
554 { "cygwin", PLATFORM_CYGWIN
},
558 for (i
= 0; i
< ARRAY_SIZE(platform_names
); i
++)
559 if (!strncmp( platform_names
[i
].name
, name
, strlen(platform_names
[i
].name
) ))
560 return platform_names
[i
].platform
;
565 static inline const char *get_arch_dir( struct target target
)
567 static const char *cpu_names
[] =
570 [CPU_x86_64
] = "x86_64",
572 [CPU_ARM64
] = "aarch64"
575 if (!cpu_names
[target
.cpu
]) return "";
577 switch (target
.platform
)
579 case PLATFORM_WINDOWS
:
580 case PLATFORM_CYGWIN
:
582 return strmake( "/%s-windows", cpu_names
[target
.cpu
] );
584 return strmake( "/%s-unix", cpu_names
[target
.cpu
] );
588 static inline int parse_target( const char *name
, struct target
*target
)
591 char *p
, *spec
= xstrdup( name
);
593 /* target specification is in the form CPU-MANUFACTURER-OS or CPU-MANUFACTURER-KERNEL-OS */
595 /* get the CPU part */
597 if ((p
= strchr( spec
, '-' )))
600 if ((res
= get_cpu_from_name( spec
)) == -1)
607 else if (!strcmp( spec
, "mingw32" ))
609 target
->cpu
= CPU_i386
;
618 /* get the OS part */
620 target
->platform
= PLATFORM_UNSPECIFIED
; /* default value */
623 if ((res
= get_platform_from_name( p
)) != -1)
625 target
->platform
= res
;
628 if (!(p
= strchr( p
, '-' ))) break;
637 static inline struct target
init_argv0_target( const char *argv0
)
639 char *name
= get_basename( argv0
);
640 struct target target
;
642 if (!strchr( name
, '-' ) || !parse_target( name
, &target
))
643 target
= get_default_target();
650 static inline char *get_argv0_dir( const char *argv0
)
655 #if defined(__linux__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
656 dir
= realpath( "/proc/self/exe", NULL
);
657 #elif defined (__FreeBSD__) || defined(__DragonFly__)
658 static int pathname
[] = { CTL_KERN
, KERN_PROC
, KERN_PROC_PATHNAME
, -1 };
659 size_t path_size
= PATH_MAX
;
660 char *path
= xmalloc( path_size
);
661 if (!sysctl( pathname
, ARRAY_SIZE(pathname
), path
, &path_size
, NULL
, 0 ))
662 dir
= realpath( path
, NULL
);
665 if (!dir
&& !(dir
= realpath( argv0
, NULL
))) return NULL
;
666 return get_dirname( dir
);
668 return get_dirname( argv0
);
673 /* output buffer management */
675 extern unsigned char *output_buffer
;
676 extern size_t output_buffer_pos
;
677 extern size_t output_buffer_size
;
679 static inline void check_output_buffer_space( size_t size
)
681 if (output_buffer_pos
+ size
>= output_buffer_size
)
683 output_buffer_size
= max( output_buffer_size
* 2, output_buffer_pos
+ size
);
684 output_buffer
= xrealloc( output_buffer
, output_buffer_size
);
688 static inline void init_output_buffer(void)
690 output_buffer_size
= 1024;
691 output_buffer_pos
= 0;
692 output_buffer
= xmalloc( output_buffer_size
);
695 static inline void put_data( const void *data
, size_t size
)
697 check_output_buffer_space( size
);
698 memcpy( output_buffer
+ output_buffer_pos
, data
, size
);
699 output_buffer_pos
+= size
;
702 static inline void put_byte( unsigned char val
)
704 check_output_buffer_space( 1 );
705 output_buffer
[output_buffer_pos
++] = val
;
708 static inline void put_word( unsigned short val
)
710 check_output_buffer_space( 2 );
711 output_buffer
[output_buffer_pos
++] = val
;
712 output_buffer
[output_buffer_pos
++] = val
>> 8;
715 static inline void put_dword( unsigned int val
)
717 check_output_buffer_space( 4 );
718 output_buffer
[output_buffer_pos
++] = val
;
719 output_buffer
[output_buffer_pos
++] = val
>> 8;
720 output_buffer
[output_buffer_pos
++] = val
>> 16;
721 output_buffer
[output_buffer_pos
++] = val
>> 24;
724 static inline void put_qword( unsigned int val
)
730 static inline void align_output( unsigned int align
)
732 size_t size
= align
- (output_buffer_pos
% align
);
734 if (size
== align
) return;
735 check_output_buffer_space( size
);
736 memset( output_buffer
+ output_buffer_pos
, 0, size
);
737 output_buffer_pos
+= size
;
740 static inline void flush_output_buffer( const char *name
)
742 int fd
= open( name
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
, 0666 );
744 if (fd
== -1 || write( fd
, output_buffer
, output_buffer_pos
) != output_buffer_pos
)
750 free( output_buffer
);
753 /* command-line option parsing */
754 /* partly based on the Glibc getopt() implementation */
763 static inline struct strarray
parse_options( int argc
, char **argv
, const char *short_opts
,
764 const struct long_option
*long_opts
, int long_only
,
765 void (*callback
)( int, char* ) )
767 struct strarray ret
= empty_strarray
;
772 #define OPT_ERR(fmt) { callback( '?', strmake( fmt, argv[1] )); continue; }
774 for (i
= 1; i
< argc
; i
++)
776 if (argv
[i
][0] != '-' || !argv
[i
][1]) /* not an option */
778 strarray_add( &ret
, argv
[i
] );
781 if (!strcmp( argv
[i
], "--" ))
783 /* add remaining args */
784 while (++i
< argc
) strarray_add( &ret
, argv
[i
] );
787 start
= argv
[i
] + 1 + (argv
[i
][1] == '-');
789 if (argv
[i
][1] == '-' || (long_only
&& (argv
[i
][2] || !strchr( short_opts
, argv
[i
][1] ))))
791 /* handle long option */
792 const struct long_option
*opt
, *found
= NULL
;
795 if (!(end
= strchr( start
, '=' ))) end
= start
+ strlen(start
);
796 for (opt
= long_opts
; opt
&& opt
->name
; opt
++)
798 if (strncmp( opt
->name
, start
, end
- start
)) continue;
799 if (!opt
->name
[end
- start
]) /* exact match */
810 else if (long_only
|| found
->has_arg
!= opt
->has_arg
|| found
->val
!= opt
->val
)
816 if (count
> 1) OPT_ERR( "option '%s' is ambiguous" );
822 if (!found
->has_arg
) OPT_ERR( "argument not allowed in '%s'" );
823 end
++; /* skip '=' */
825 else if (found
->has_arg
== 1)
827 if (i
== argc
- 1) OPT_ERR( "option '%s' requires an argument" );
832 callback( found
->val
, end
);
835 if (argv
[i
][1] == '-' || !long_only
|| !strchr( short_opts
, argv
[i
][1] ))
836 OPT_ERR( "unrecognized option '%s'" );
839 /* handle short option */
840 for ( ; *start
; start
++)
842 if (!(flag
= strchr( short_opts
, *start
))) OPT_ERR( "invalid option '%s'" );
846 if (!*end
) end
= NULL
;
847 if (flag
[2] != ':' && !end
)
849 if (i
== argc
- 1) OPT_ERR( "option '%s' requires an argument" );
852 callback( *start
, end
);
855 callback( *start
, NULL
);
862 #endif /* __WINE_TOOLS_H */