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_ARM64EC
} 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
[] =
486 return sizes
[target
.cpu
];
490 static inline void set_target_ptr_size( struct target
*target
, unsigned int size
)
495 if (size
== 8) target
->cpu
= CPU_x86_64
;
498 if (size
== 4) target
->cpu
= CPU_i386
;
501 if (size
== 8) target
->cpu
= CPU_ARM64
;
505 if (size
== 4) target
->cpu
= CPU_ARM
;
511 static inline int get_cpu_from_name( const char *name
)
519 { "i386", CPU_i386
},
520 { "i486", CPU_i386
},
521 { "i586", CPU_i386
},
522 { "i686", CPU_i386
},
523 { "i786", CPU_i386
},
524 { "x86_64", CPU_x86_64
},
525 { "amd64", CPU_x86_64
},
526 { "aarch64", CPU_ARM64
},
527 { "arm64ec", CPU_ARM64EC
},
528 { "arm64", CPU_ARM64
},
533 for (i
= 0; i
< ARRAY_SIZE(cpu_names
); i
++)
534 if (!strncmp( cpu_names
[i
].name
, name
, strlen(cpu_names
[i
].name
) )) return cpu_names
[i
].cpu
;
539 static inline int get_platform_from_name( const char *name
)
547 { "macos", PLATFORM_APPLE
},
548 { "darwin", PLATFORM_APPLE
},
549 { "android", PLATFORM_ANDROID
},
550 { "linux", PLATFORM_LINUX
},
551 { "freebsd", PLATFORM_FREEBSD
},
552 { "solaris", PLATFORM_SOLARIS
},
553 { "mingw32", PLATFORM_MINGW
},
554 { "windows-gnu", PLATFORM_MINGW
},
555 { "winnt", PLATFORM_MINGW
},
556 { "windows", PLATFORM_WINDOWS
},
557 { "cygwin", PLATFORM_CYGWIN
},
561 for (i
= 0; i
< ARRAY_SIZE(platform_names
); i
++)
562 if (!strncmp( platform_names
[i
].name
, name
, strlen(platform_names
[i
].name
) ))
563 return platform_names
[i
].platform
;
568 static inline const char *get_arch_dir( struct target target
)
570 static const char *cpu_names
[] =
573 [CPU_x86_64
] = "x86_64",
575 [CPU_ARM64
] = "aarch64",
576 [CPU_ARM64EC
] = "arm64ec",
579 if (!cpu_names
[target
.cpu
]) return "";
581 switch (target
.platform
)
583 case PLATFORM_WINDOWS
:
584 case PLATFORM_CYGWIN
:
586 return strmake( "/%s-windows", cpu_names
[target
.cpu
] );
588 return strmake( "/%s-unix", cpu_names
[target
.cpu
] );
592 static inline int parse_target( const char *name
, struct target
*target
)
595 char *p
, *spec
= xstrdup( name
);
597 /* target specification is in the form CPU-MANUFACTURER-OS or CPU-MANUFACTURER-KERNEL-OS */
599 /* get the CPU part */
601 if ((p
= strchr( spec
, '-' )))
604 if ((res
= get_cpu_from_name( spec
)) == -1)
611 else if (!strcmp( spec
, "mingw32" ))
613 target
->cpu
= CPU_i386
;
622 /* get the OS part */
624 target
->platform
= PLATFORM_UNSPECIFIED
; /* default value */
627 if ((res
= get_platform_from_name( p
)) != -1)
629 target
->platform
= res
;
632 if (!(p
= strchr( p
, '-' ))) break;
641 static inline struct target
init_argv0_target( const char *argv0
)
643 char *name
= get_basename( argv0
);
644 struct target target
;
646 if (!strchr( name
, '-' ) || !parse_target( name
, &target
))
647 target
= get_default_target();
654 static inline char *get_argv0_dir( const char *argv0
)
659 #if defined(__linux__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__)
660 dir
= realpath( "/proc/self/exe", NULL
);
661 #elif defined (__FreeBSD__) || defined(__DragonFly__)
662 static int pathname
[] = { CTL_KERN
, KERN_PROC
, KERN_PROC_PATHNAME
, -1 };
663 size_t path_size
= PATH_MAX
;
664 char *path
= xmalloc( path_size
);
665 if (!sysctl( pathname
, ARRAY_SIZE(pathname
), path
, &path_size
, NULL
, 0 ))
666 dir
= realpath( path
, NULL
);
669 if (!dir
&& !(dir
= realpath( argv0
, NULL
))) return NULL
;
670 return get_dirname( dir
);
672 return get_dirname( argv0
);
677 /* output buffer management */
679 extern unsigned char *output_buffer
;
680 extern size_t output_buffer_pos
;
681 extern size_t output_buffer_size
;
683 static inline void check_output_buffer_space( size_t size
)
685 if (output_buffer_pos
+ size
>= output_buffer_size
)
687 output_buffer_size
= max( output_buffer_size
* 2, output_buffer_pos
+ size
);
688 output_buffer
= xrealloc( output_buffer
, output_buffer_size
);
692 static inline void init_output_buffer(void)
694 output_buffer_size
= 1024;
695 output_buffer_pos
= 0;
696 output_buffer
= xmalloc( output_buffer_size
);
699 static inline void put_data( const void *data
, size_t size
)
701 check_output_buffer_space( size
);
702 memcpy( output_buffer
+ output_buffer_pos
, data
, size
);
703 output_buffer_pos
+= size
;
706 static inline void put_byte( unsigned char val
)
708 check_output_buffer_space( 1 );
709 output_buffer
[output_buffer_pos
++] = val
;
712 static inline void put_word( unsigned short val
)
714 check_output_buffer_space( 2 );
715 output_buffer
[output_buffer_pos
++] = val
;
716 output_buffer
[output_buffer_pos
++] = val
>> 8;
719 static inline void put_dword( unsigned int val
)
721 check_output_buffer_space( 4 );
722 output_buffer
[output_buffer_pos
++] = val
;
723 output_buffer
[output_buffer_pos
++] = val
>> 8;
724 output_buffer
[output_buffer_pos
++] = val
>> 16;
725 output_buffer
[output_buffer_pos
++] = val
>> 24;
728 static inline void put_qword( unsigned int val
)
734 static inline void align_output( unsigned int align
)
736 size_t size
= align
- (output_buffer_pos
% align
);
738 if (size
== align
) return;
739 check_output_buffer_space( size
);
740 memset( output_buffer
+ output_buffer_pos
, 0, size
);
741 output_buffer_pos
+= size
;
744 static inline void flush_output_buffer( const char *name
)
746 int fd
= open( name
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
, 0666 );
748 if (fd
== -1 || write( fd
, output_buffer
, output_buffer_pos
) != output_buffer_pos
)
754 free( output_buffer
);
757 /* command-line option parsing */
758 /* partly based on the Glibc getopt() implementation */
767 static inline struct strarray
parse_options( int argc
, char **argv
, const char *short_opts
,
768 const struct long_option
*long_opts
, int long_only
,
769 void (*callback
)( int, char* ) )
771 struct strarray ret
= empty_strarray
;
776 #define OPT_ERR(fmt) { callback( '?', strmake( fmt, argv[i] )); continue; }
778 for (i
= 1; i
< argc
; i
++)
780 if (argv
[i
][0] != '-' || !argv
[i
][1]) /* not an option */
782 strarray_add( &ret
, argv
[i
] );
785 if (!strcmp( argv
[i
], "--" ))
787 /* add remaining args */
788 while (++i
< argc
) strarray_add( &ret
, argv
[i
] );
791 start
= argv
[i
] + 1 + (argv
[i
][1] == '-');
793 if (argv
[i
][1] == '-' || (long_only
&& (argv
[i
][2] || !strchr( short_opts
, argv
[i
][1] ))))
795 /* handle long option */
796 const struct long_option
*opt
, *found
= NULL
;
799 if (!(end
= strchr( start
, '=' ))) end
= start
+ strlen(start
);
800 for (opt
= long_opts
; opt
&& opt
->name
; opt
++)
802 if (strncmp( opt
->name
, start
, end
- start
)) continue;
803 if (!opt
->name
[end
- start
]) /* exact match */
814 else if (long_only
|| found
->has_arg
!= opt
->has_arg
|| found
->val
!= opt
->val
)
820 if (count
> 1) OPT_ERR( "option '%s' is ambiguous" );
826 if (!found
->has_arg
) OPT_ERR( "argument not allowed in '%s'" );
827 end
++; /* skip '=' */
829 else if (found
->has_arg
== 1)
831 if (i
== argc
- 1) OPT_ERR( "option '%s' requires an argument" );
836 callback( found
->val
, end
);
839 if (argv
[i
][1] == '-' || !long_only
|| !strchr( short_opts
, argv
[i
][1] ))
840 OPT_ERR( "unrecognized option '%s'" );
843 /* handle short option */
844 for ( ; *start
; start
++)
846 if (!(flag
= strchr( short_opts
, *start
))) OPT_ERR( "invalid option '%s'" );
850 if (!*end
) end
= NULL
;
851 if (flag
[2] != ':' && !end
)
853 if (i
== argc
- 1) OPT_ERR( "option '%s' requires an argument" );
856 callback( *start
, end
);
859 callback( *start
, NULL
);
866 #endif /* __WINE_TOOLS_H */