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
28 #include <sys/types.h>
38 # define mkdir(path,mode) mkdir(path)
40 # define S_ISREG(mod) (((mod) & _S_IFMT) == _S_IFREG)
44 # define pclose _pclose
45 # define strtoll _strtoi64
46 # define strtoull _strtoui64
47 # define strncasecmp _strnicmp
48 # define strcasecmp _stricmp
51 # include <sys/wait.h>
57 # if defined(__x86_64__) || defined(__aarch64__) || defined(__powerpc64__)
60 # define __int64 long long
65 #if !defined(__GNUC__) && !defined(__attribute__)
66 #define __attribute__(x)
70 #define max(a,b) (((a) > (b)) ? (a) : (b))
73 #define min(a,b) (((a) < (b)) ? (a) : (b))
77 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
82 enum { CPU_i386
, CPU_x86_64
, CPU_ARM
, CPU_ARM64
} cpu
;
98 static inline void *xmalloc( size_t size
)
100 void *res
= malloc( size
? size
: 1 );
104 fprintf( stderr
, "Virtual memory exhausted.\n" );
110 static inline void *xrealloc (void *ptr
, size_t size
)
112 void *res
= realloc( ptr
, size
);
114 if (size
&& res
== NULL
)
116 fprintf( stderr
, "Virtual memory exhausted.\n" );
122 static inline char *xstrdup( const char *str
)
124 return strcpy( xmalloc( strlen(str
)+1 ), str
);
127 static inline int strendswith( const char *str
, const char *end
)
129 int l
= strlen( str
);
130 int m
= strlen( end
);
131 return l
>= m
&& !strcmp( str
+ l
- m
, end
);
134 static char *strmake( const char* fmt
, ... ) __attribute__ ((__format__ (__printf__
, 1, 2)));
135 static inline char *strmake( const char* fmt
, ... )
143 char *p
= xmalloc( size
);
145 n
= vsnprintf( p
, size
, fmt
, ap
);
147 if (n
== -1) size
*= 2;
148 else if ((size_t)n
>= size
) size
= n
+ 1;
154 /* string array functions */
158 unsigned int count
; /* strings in use */
159 unsigned int size
; /* total allocated size */
163 static const struct strarray empty_strarray
;
165 static inline void strarray_add( struct strarray
*array
, const char *str
)
167 if (array
->count
== array
->size
)
169 if (array
->size
) array
->size
*= 2;
170 else array
->size
= 16;
171 array
->str
= xrealloc( array
->str
, sizeof(array
->str
[0]) * array
->size
);
173 array
->str
[array
->count
++] = str
;
176 static inline void strarray_addall( struct strarray
*array
, struct strarray added
)
180 for (i
= 0; i
< added
.count
; i
++) strarray_add( array
, added
.str
[i
] );
183 static inline int strarray_exists( const struct strarray
*array
, const char *str
)
187 for (i
= 0; i
< array
->count
; i
++) if (!strcmp( array
->str
[i
], str
)) return 1;
191 static inline void strarray_add_uniq( struct strarray
*array
, const char *str
)
193 if (!strarray_exists( array
, str
)) strarray_add( array
, str
);
196 static inline void strarray_addall_uniq( struct strarray
*array
, struct strarray added
)
200 for (i
= 0; i
< added
.count
; i
++) strarray_add_uniq( array
, added
.str
[i
] );
203 static inline struct strarray
strarray_fromstring( const char *str
, const char *delim
)
205 struct strarray array
= empty_strarray
;
206 char *buf
= xstrdup( str
);
209 for (tok
= strtok( buf
, delim
); tok
; tok
= strtok( NULL
, delim
))
210 strarray_add( &array
, xstrdup( tok
));
215 static inline struct strarray
strarray_frompath( const char *path
)
217 if (!path
) return empty_strarray
;
219 return strarray_fromstring( path
, ";" );
221 return strarray_fromstring( path
, ":" );
225 static inline char *strarray_tostring( struct strarray array
, const char *sep
)
228 unsigned int i
, len
= 1 + (array
.count
- 1) * strlen(sep
);
230 if (!array
.count
) return xstrdup("");
231 for (i
= 0; i
< array
.count
; i
++) len
+= strlen( array
.str
[i
] );
232 str
= xmalloc( len
);
233 strcpy( str
, array
.str
[0] );
234 for (i
= 1; i
< array
.count
; i
++)
237 strcat( str
, array
.str
[i
] );
242 static inline void strarray_qsort( struct strarray
*array
, int (*func
)(const char **, const char **) )
244 if (array
->count
) qsort( array
->str
, array
->count
, sizeof(*array
->str
), (void *)func
);
247 static inline const char *strarray_bsearch( const struct strarray
*array
, const char *str
,
248 int (*func
)(const char **, const char **) )
252 if (array
->count
) res
= bsearch( &str
, array
->str
, array
->count
, sizeof(*array
->str
), (void *)func
);
253 return res
? *res
: NULL
;
256 static inline void strarray_trace( struct strarray args
)
260 for (i
= 0; i
< args
.count
; i
++)
262 if (strpbrk( args
.str
[i
], " \t\n\r")) printf( "\"%s\"", args
.str
[i
] );
263 else printf( "%s", args
.str
[i
] );
264 putchar( i
< args
.count
- 1 ? ' ' : '\n' );
268 static inline int strarray_spawn( struct strarray args
)
271 strarray_add( &args
, NULL
);
272 return _spawnvp( _P_WAIT
, args
.str
[0], args
.str
);
279 strarray_add( &args
, NULL
);
280 execvp( args
.str
[0], (char **)args
.str
);
283 if (pid
== -1) return -1;
285 while (pid
!= (wret
= waitpid( pid
, &status
, 0 )))
286 if (wret
== -1 && errno
!= EINTR
) break;
288 if (pid
== wret
&& WIFEXITED(status
)) return WEXITSTATUS(status
);
289 return 255; /* abnormal exit with an abort or an interrupt */
293 static inline char *get_basename( const char *file
)
295 const char *ret
= strrchr( file
, '/' );
296 return xstrdup( ret
? ret
+ 1 : file
);
299 static inline char *get_basename_noext( const char *file
)
301 char *ext
, *ret
= get_basename( file
);
302 if ((ext
= strrchr( ret
, '.' ))) *ext
= 0;
306 static inline char *get_dirname( const char *file
)
308 const char *end
= strrchr( file
, '/' );
309 if (!end
) return xstrdup( "." );
310 if (end
== file
) end
++;
311 return strmake( "%.*s", (int)(end
- file
), file
);
314 static inline char *replace_extension( const char *name
, const char *old_ext
, const char *new_ext
)
316 int name_len
= strlen( name
);
318 if (strendswith( name
, old_ext
)) name_len
-= strlen( old_ext
);
319 return strmake( "%.*s%s", name_len
, name
, new_ext
);
323 static inline int make_temp_file( const char *prefix
, const char *suffix
, char **name
)
325 static unsigned int value
;
327 const char *tmpdir
= NULL
;
329 if (!prefix
) prefix
= "tmp";
330 if (!suffix
) suffix
= "";
331 value
+= time(NULL
) + getpid();
333 for (count
= 0; count
< 0x8000; count
++)
336 *name
= strmake( "%s/%s-%08x%s", tmpdir
, prefix
, value
, suffix
);
338 *name
= strmake( "%s-%08x%s", prefix
, value
, suffix
);
339 fd
= open( *name
, O_RDWR
| O_CREAT
| O_EXCL
, 0600 );
340 if (fd
>= 0) return fd
;
342 if (errno
== EACCES
&& !tmpdir
&& !strchr( prefix
, '/' ))
344 if (!(tmpdir
= getenv("TMPDIR"))) tmpdir
= "/tmp";
348 fprintf( stderr
, "failed to create temp file for %s%s\n", prefix
, suffix
);
353 static inline void *read_file( const char *name
, size_t *size
)
359 if ((fd
= open( name
, O_RDONLY
| O_BINARY
)) == -1) return NULL
;
361 data
= xmalloc( st
.st_size
);
362 res
= read( fd
, data
, st
.st_size
);
375 static inline struct target
get_default_target(void)
377 struct target target
;
379 target
.cpu
= CPU_i386
;
380 #elif defined(__x86_64__)
381 target
.cpu
= CPU_x86_64
;
382 #elif defined(__arm__)
383 target
.cpu
= CPU_ARM
;
384 #elif defined(__aarch64__)
385 target
.cpu
= CPU_ARM64
;
387 #error Unsupported CPU
391 target
.platform
= PLATFORM_APPLE
;
392 #elif defined(__ANDROID__)
393 target
.platform
= PLATFORM_ANDROID
;
394 #elif defined(__linux__)
395 target
.platform
= PLATFORM_LINUX
;
396 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
397 target
.platform
= PLATFORM_FREEBSD
;
399 target
.platform
= PLATFORM_SOLARIS
;
400 #elif defined(__CYGWIN__)
401 target
.platform
= PLATFORM_CYGWIN
;
402 #elif defined(_WIN32)
403 target
.platform
= PLATFORM_MINGW
;
405 target
.platform
= PLATFORM_UNSPECIFIED
;
412 static inline unsigned int get_target_ptr_size( struct target target
)
414 static const unsigned int sizes
[] =
421 return sizes
[target
.cpu
];
425 static inline void set_target_ptr_size( struct target
*target
, unsigned int size
)
430 if (size
== 8) target
->cpu
= CPU_x86_64
;
433 if (size
== 4) target
->cpu
= CPU_i386
;
436 if (size
== 8) target
->cpu
= CPU_ARM64
;
439 if (size
== 4) target
->cpu
= CPU_ARM
;
445 static inline int get_cpu_from_name( const char *name
)
453 { "i386", CPU_i386
},
454 { "i486", CPU_i386
},
455 { "i586", CPU_i386
},
456 { "i686", CPU_i386
},
457 { "i786", CPU_i386
},
458 { "x86_64", CPU_x86_64
},
459 { "amd64", CPU_x86_64
},
460 { "aarch64", CPU_ARM64
},
461 { "arm64", CPU_ARM64
},
466 for (i
= 0; i
< ARRAY_SIZE(cpu_names
); i
++)
467 if (!strncmp( cpu_names
[i
].name
, name
, strlen(cpu_names
[i
].name
) )) return cpu_names
[i
].cpu
;
472 static inline int get_platform_from_name( const char *name
)
480 { "macos", PLATFORM_APPLE
},
481 { "darwin", PLATFORM_APPLE
},
482 { "android", PLATFORM_ANDROID
},
483 { "linux", PLATFORM_LINUX
},
484 { "freebsd", PLATFORM_FREEBSD
},
485 { "solaris", PLATFORM_SOLARIS
},
486 { "mingw32", PLATFORM_MINGW
},
487 { "windows-gnu", PLATFORM_MINGW
},
488 { "winnt", PLATFORM_MINGW
},
489 { "windows", PLATFORM_WINDOWS
},
490 { "cygwin", PLATFORM_CYGWIN
},
494 for (i
= 0; i
< ARRAY_SIZE(platform_names
); i
++)
495 if (!strncmp( platform_names
[i
].name
, name
, strlen(platform_names
[i
].name
) ))
496 return platform_names
[i
].platform
;
501 static inline const char *get_arch_dir( struct target target
)
503 static const char *cpu_names
[] =
506 [CPU_x86_64
] = "x86_64",
508 [CPU_ARM64
] = "aarch64"
511 if (!cpu_names
[target
.cpu
]) return "";
513 switch (target
.platform
)
515 case PLATFORM_WINDOWS
:
516 case PLATFORM_CYGWIN
:
518 return strmake( "/%s-windows", cpu_names
[target
.cpu
] );
520 return strmake( "/%s-unix", cpu_names
[target
.cpu
] );
524 static inline int parse_target( const char *name
, struct target
*target
)
527 char *p
, *spec
= xstrdup( name
);
529 /* target specification is in the form CPU-MANUFACTURER-OS or CPU-MANUFACTURER-KERNEL-OS */
531 /* get the CPU part */
533 if ((p
= strchr( spec
, '-' )))
536 if ((res
= get_cpu_from_name( spec
)) == -1)
543 else if (!strcmp( spec
, "mingw32" ))
545 target
->cpu
= CPU_i386
;
554 /* get the OS part */
556 target
->platform
= PLATFORM_UNSPECIFIED
; /* default value */
559 if ((res
= get_platform_from_name( p
)) != -1)
561 target
->platform
= res
;
564 if (!(p
= strchr( p
, '-' ))) break;
573 static inline struct target
init_argv0_target( const char *argv0
)
575 char *name
= get_basename( argv0
);
576 struct target target
;
578 if (!strchr( name
, '-' ) || !parse_target( name
, &target
))
579 target
= get_default_target();
586 /* output buffer management */
588 extern unsigned char *output_buffer
;
589 extern size_t output_buffer_pos
;
590 extern size_t output_buffer_size
;
592 static inline void check_output_buffer_space( size_t size
)
594 if (output_buffer_pos
+ size
>= output_buffer_size
)
596 output_buffer_size
= max( output_buffer_size
* 2, output_buffer_pos
+ size
);
597 output_buffer
= xrealloc( output_buffer
, output_buffer_size
);
601 static inline void init_output_buffer(void)
603 output_buffer_size
= 1024;
604 output_buffer_pos
= 0;
605 output_buffer
= xmalloc( output_buffer_size
);
608 static inline void put_data( const void *data
, size_t size
)
610 check_output_buffer_space( size
);
611 memcpy( output_buffer
+ output_buffer_pos
, data
, size
);
612 output_buffer_pos
+= size
;
615 static inline void put_byte( unsigned char val
)
617 check_output_buffer_space( 1 );
618 output_buffer
[output_buffer_pos
++] = val
;
621 static inline void put_word( unsigned short val
)
623 check_output_buffer_space( 2 );
624 output_buffer
[output_buffer_pos
++] = val
;
625 output_buffer
[output_buffer_pos
++] = val
>> 8;
628 static inline void put_dword( unsigned int val
)
630 check_output_buffer_space( 4 );
631 output_buffer
[output_buffer_pos
++] = val
;
632 output_buffer
[output_buffer_pos
++] = val
>> 8;
633 output_buffer
[output_buffer_pos
++] = val
>> 16;
634 output_buffer
[output_buffer_pos
++] = val
>> 24;
637 static inline void put_qword( unsigned int val
)
643 static inline void align_output( unsigned int align
)
645 size_t size
= align
- (output_buffer_pos
% align
);
647 if (size
== align
) return;
648 check_output_buffer_space( size
);
649 memset( output_buffer
+ output_buffer_pos
, 0, size
);
650 output_buffer_pos
+= size
;
653 static inline void flush_output_buffer( const char *name
)
655 int fd
= open( name
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
, 0666 );
657 if (fd
== -1 || write( fd
, output_buffer
, output_buffer_pos
) != output_buffer_pos
)
663 free( output_buffer
);
666 /* command-line option parsing */
667 /* partly based on the Glibc getopt() implementation */
676 static inline struct strarray
parse_options( int argc
, char **argv
, const char *short_opts
,
677 const struct long_option
*long_opts
, int long_only
,
678 void (*callback
)( int, char* ) )
680 struct strarray ret
= empty_strarray
;
685 #define OPT_ERR(fmt) { callback( '?', strmake( fmt, argv[1] )); continue; }
687 for (i
= 1; i
< argc
; i
++)
689 if (argv
[i
][0] != '-' || !argv
[i
][1]) /* not an option */
691 strarray_add( &ret
, argv
[i
] );
694 if (!strcmp( argv
[i
], "--" ))
696 /* add remaining args */
697 while (++i
< argc
) strarray_add( &ret
, argv
[i
] );
700 start
= argv
[i
] + 1 + (argv
[i
][1] == '-');
702 if (argv
[i
][1] == '-' || (long_only
&& (argv
[i
][2] || !strchr( short_opts
, argv
[i
][1] ))))
704 /* handle long option */
705 const struct long_option
*opt
, *found
= NULL
;
708 if (!(end
= strchr( start
, '=' ))) end
= start
+ strlen(start
);
709 for (opt
= long_opts
; opt
&& opt
->name
; opt
++)
711 if (strncmp( opt
->name
, start
, end
- start
)) continue;
712 if (!opt
->name
[end
- start
]) /* exact match */
723 else if (long_only
|| found
->has_arg
!= opt
->has_arg
|| found
->val
!= opt
->val
)
729 if (count
> 1) OPT_ERR( "option '%s' is ambiguous" );
735 if (!found
->has_arg
) OPT_ERR( "argument not allowed in '%s'" );
736 end
++; /* skip '=' */
738 else if (found
->has_arg
== 1)
740 if (i
== argc
- 1) OPT_ERR( "option '%s' requires an argument" );
745 callback( found
->val
, end
);
748 if (argv
[i
][1] == '-' || !long_only
|| !strchr( short_opts
, argv
[i
][1] ))
749 OPT_ERR( "unrecognized option '%s'" );
752 /* handle short option */
753 for ( ; *start
; start
++)
755 if (!(flag
= strchr( short_opts
, *start
))) OPT_ERR( "invalid option '%s'" );
759 if (!*end
) end
= NULL
;
760 if (flag
[2] != ':' && !end
)
762 if (i
== argc
- 1) OPT_ERR( "option '%s' requires an argument" );
765 callback( *start
, end
);
768 callback( *start
, NULL
);
775 #endif /* __WINE_TOOLS_H */