2 * Small utility functions for winebuild
4 * Copyright 2000 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
22 #include "wine/port.h"
33 #ifdef HAVE_SYS_STAT_H
34 # include <sys/stat.h>
36 #ifdef HAVE_SYS_MMAN_H
42 #define MAX_TMP_FILES 8
43 static const char *tmp_files[MAX_TMP_FILES];
44 static unsigned int nb_tmp_files;
57 { "x86_64", CPU_x86_64 },
58 { "sparc", CPU_SPARC },
59 { "alpha", CPU_ALPHA },
60 { "powerpc", CPU_POWERPC },
64 /* atexit handler to clean tmp files */
65 static void cleanup_tmp_files(void)
68 for (i = 0; i < MAX_TMP_FILES; i++) if (tmp_files[i]) unlink( tmp_files[i] );
72 void *xmalloc (size_t size)
76 res = malloc (size ? size : 1);
79 fprintf (stderr, "Virtual memory exhausted.\n");
85 void *xrealloc (void *ptr, size_t size)
87 void *res = realloc (ptr, size);
88 if (size && res == NULL)
90 fprintf (stderr, "Virtual memory exhausted.\n");
96 char *xstrdup( const char *str )
98 char *res = strdup( str );
101 fprintf (stderr, "Virtual memory exhausted.\n");
107 char *strupper(char *s)
110 for (p = s; *p; p++) *p = toupper(*p);
114 int strendswith(const char* str, const char* end)
118 return l >= m && strcmp(str + l - m, end) == 0;
121 void fatal_error( const char *msg, ... )
124 va_start( valist, msg );
127 fprintf( stderr, "%s:", input_file_name );
129 fprintf( stderr, "%d:", current_line );
130 fputc( ' ', stderr );
132 else fprintf( stderr, "winebuild: " );
133 vfprintf( stderr, msg, valist );
138 void fatal_perror( const char *msg, ... )
141 va_start( valist, msg );
144 fprintf( stderr, "%s:", input_file_name );
146 fprintf( stderr, "%d:", current_line );
147 fputc( ' ', stderr );
149 vfprintf( stderr, msg, valist );
155 void error( const char *msg, ... )
158 va_start( valist, msg );
161 fprintf( stderr, "%s:", input_file_name );
163 fprintf( stderr, "%d:", current_line );
164 fputc( ' ', stderr );
166 vfprintf( stderr, msg, valist );
171 void warning( const char *msg, ... )
175 if (!display_warnings) return;
176 va_start( valist, msg );
179 fprintf( stderr, "%s:", input_file_name );
181 fprintf( stderr, "%d:", current_line );
182 fputc( ' ', stderr );
184 fprintf( stderr, "warning: " );
185 vfprintf( stderr, msg, valist );
189 int output( const char *format, ... )
194 va_start( valist, format );
195 ret = vfprintf( output_file, format, valist );
197 if (ret < 0) fatal_perror( "Output error" );
201 /* find a build tool in the path, trying the various names */
202 static char *find_tool( const char * const *names )
205 static unsigned int count, maxlen;
215 /* split the path in directories */
217 if (!getenv( "PATH" )) return NULL;
218 path = xstrdup( getenv( "PATH" ));
219 for (p = path, count = 2; *p; p++) if (*p == ':') count++;
220 dirs = xmalloc( count * sizeof(*dirs) );
222 dirs[count++] = p = path;
225 while (*p && *p != ':') p++;
230 for (i = 0; i < count; i++) maxlen = max( maxlen, strlen(dirs[i])+2 );
235 len = strlen(*names) + sizeof(EXEEXT) + 1;
236 file = xmalloc( maxlen + len );
238 for (i = 0; i < count; i++)
240 strcpy( file, dirs[i] );
241 p = file + strlen(file);
242 if (p == file) *p++ = '.';
243 if (p[-1] != '/') *p++ = '/';
247 if (!stat( file, &st ) && S_ISREG(st.st_mode) && (st.st_mode & 0111)) return file;
255 const char *get_as_command(void)
261 as_command = xmalloc( strlen(target_alias) + sizeof("-as") );
262 strcpy( as_command, target_alias );
263 strcat( as_command, "-as" );
267 static const char * const commands[] = { "gas", "as", NULL };
268 if (!(as_command = find_tool( commands ))) as_command = xstrdup("as");
271 if (force_pointer_size)
273 const char *args = (target_platform == PLATFORM_APPLE) ?
274 ((force_pointer_size == 8) ? " -arch x86_64" : " -arch i386") :
275 ((force_pointer_size == 8) ? " --64" : " --32");
276 as_command = xrealloc( as_command, strlen(as_command) + strlen(args) + 1 );
277 strcat( as_command, args );
283 const char *get_ld_command(void)
289 ld_command = xmalloc( strlen(target_alias) + sizeof("-ld") );
290 strcpy( ld_command, target_alias );
291 strcat( ld_command, "-ld" );
295 static const char * const commands[] = { "ld", "gld", NULL };
296 if (!(ld_command = find_tool( commands ))) ld_command = xstrdup("ld");
299 if (force_pointer_size)
303 switch (target_platform)
306 args = (force_pointer_size == 8) ? " -arch x86_64" : " -arch i386";
308 case PLATFORM_FREEBSD:
309 args = (force_pointer_size == 8) ? " -m elf_x86_64" : " -m elf_i386_fbsd";
312 args = (force_pointer_size == 8) ? " -m elf_x86_64" : " -m elf_i386";
315 ld_command = xrealloc( ld_command, strlen(ld_command) + strlen(args) + 1 );
316 strcat( ld_command, args );
322 const char *get_nm_command(void)
328 nm_command = xmalloc( strlen(target_alias) + sizeof("-nm") );
329 strcpy( nm_command, target_alias );
330 strcat( nm_command, "-nm" );
334 static const char * const commands[] = { "nm", "gnm", NULL };
335 if (!(nm_command = find_tool( commands ))) nm_command = xstrdup("nm");
341 const char *get_windres_command(void)
343 static char *windres_command;
345 if (!windres_command)
349 windres_command = xmalloc( strlen(target_alias) + sizeof("-windres") );
350 strcpy( windres_command, target_alias );
351 strcat( windres_command, "-windres" );
355 static const char * const commands[] = { "windres", NULL };
356 if (!(windres_command = find_tool( commands ))) windres_command = xstrdup("windres");
359 return windres_command;
362 /* get a name for a temp file, automatically cleaned up on exit */
363 char *get_temp_file_name( const char *prefix, const char *suffix )
369 assert( nb_tmp_files < MAX_TMP_FILES );
370 if (!nb_tmp_files && !save_temps) atexit( cleanup_tmp_files );
372 if (!prefix || !prefix[0]) prefix = "winebuild";
373 if (!suffix) suffix = "";
374 if (!(ext = strchr( prefix, '.' ))) ext = prefix + strlen(prefix);
375 name = xmalloc( sizeof("/tmp/") + (ext - prefix) + sizeof(".XXXXXX") + strlen(suffix) );
376 strcpy( name, "/tmp/" );
377 memcpy( name + 5, prefix, ext - prefix );
378 strcpy( name + 5 + (ext - prefix), ".XXXXXX" );
379 strcat( name, suffix );
381 /* first try without the /tmp/ prefix */
382 if ((fd = mkstemps( name + 5, strlen(suffix) )) != -1)
384 else if ((fd = mkstemps( name, strlen(suffix) )) == -1)
385 fatal_error( "could not generate a temp file\n" );
388 tmp_files[nb_tmp_files++] = name;
392 /*******************************************************************
395 * Function for reading from/writing to a memory buffer.
398 int byte_swapped = 0;
399 const char *input_buffer_filename;
400 const unsigned char *input_buffer;
401 size_t input_buffer_pos;
402 size_t input_buffer_size;
403 unsigned char *output_buffer;
404 size_t output_buffer_pos;
405 size_t output_buffer_size;
407 static void check_output_buffer_space( size_t size )
409 if (output_buffer_pos + size >= output_buffer_size)
411 output_buffer_size = max( output_buffer_size * 2, output_buffer_pos + size );
412 output_buffer = xrealloc( output_buffer, output_buffer_size );
416 void init_input_buffer( const char *file )
421 if ((fd = open( file, O_RDONLY | O_BINARY )) == -1) fatal_perror( "Cannot open %s", file );
422 if ((fstat( fd, &st ) == -1)) fatal_perror( "Cannot stat %s", file );
423 if (!st.st_size) fatal_error( "%s is an empty file\n", file );
425 if ((input_buffer = mmap( NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0 )) == (void*)-1)
428 unsigned char *buffer = xmalloc( st.st_size );
429 if (read( fd, buffer, st.st_size ) != st.st_size) fatal_error( "Cannot read %s\n", file );
430 input_buffer = buffer;
433 input_buffer_filename = xstrdup( file );
434 input_buffer_size = st.st_size;
435 input_buffer_pos = 0;
439 void init_output_buffer(void)
441 output_buffer_size = 1024;
442 output_buffer_pos = 0;
443 output_buffer = xmalloc( output_buffer_size );
446 void flush_output_buffer(void)
448 if (fwrite( output_buffer, 1, output_buffer_pos, output_file ) != output_buffer_pos)
449 fatal_error( "Error writing to %s\n", output_file_name );
450 free( output_buffer );
453 unsigned char get_byte(void)
455 if (input_buffer_pos >= input_buffer_size)
456 fatal_error( "%s is a truncated file\n", input_buffer_filename );
457 return input_buffer[input_buffer_pos++];
460 unsigned short get_word(void)
464 if (input_buffer_pos + sizeof(ret) > input_buffer_size)
465 fatal_error( "%s is a truncated file\n", input_buffer_filename );
466 memcpy( &ret, input_buffer + input_buffer_pos, sizeof(ret) );
467 if (byte_swapped) ret = (ret << 8) | (ret >> 8);
468 input_buffer_pos += sizeof(ret);
472 unsigned int get_dword(void)
476 if (input_buffer_pos + sizeof(ret) > input_buffer_size)
477 fatal_error( "%s is a truncated file\n", input_buffer_filename );
478 memcpy( &ret, input_buffer + input_buffer_pos, sizeof(ret) );
480 ret = ((ret << 24) | ((ret << 8) & 0x00ff0000) | ((ret >> 8) & 0x0000ff00) | (ret >> 24));
481 input_buffer_pos += sizeof(ret);
485 void put_data( const void *data, size_t size )
487 check_output_buffer_space( size );
488 memcpy( output_buffer + output_buffer_pos, data, size );
489 output_buffer_pos += size;
492 void put_byte( unsigned char val )
494 check_output_buffer_space( 1 );
495 output_buffer[output_buffer_pos++] = val;
498 void put_word( unsigned short val )
500 if (byte_swapped) val = (val << 8) | (val >> 8);
501 put_data( &val, sizeof(val) );
504 void put_dword( unsigned int val )
507 val = ((val << 24) | ((val << 8) & 0x00ff0000) | ((val >> 8) & 0x0000ff00) | (val >> 24));
508 put_data( &val, sizeof(val) );
511 void put_qword( unsigned int val )
525 /* pointer-sized word */
526 void put_pword( unsigned int val )
528 if (get_ptr_size() == 8) put_qword( val );
529 else put_dword( val );
532 void align_output( unsigned int align )
534 size_t size = align - (output_buffer_pos % align);
536 if (size == align) return;
537 check_output_buffer_space( size );
538 memset( output_buffer + output_buffer_pos, 0, size );
539 output_buffer_pos += size;
542 /* output a standard header for generated files */
543 void output_standard_file_header(void)
546 output( "/* File generated automatically from %s; do not edit! */\n", spec_file_name );
548 output( "/* File generated automatically; do not edit! */\n" );
549 output( "/* This file can be copied, modified and distributed without restriction. */\n\n" );
552 /* dump a byte stream into the assembly code */
553 void dump_bytes( const void *buffer, unsigned int size )
556 const unsigned char *ptr = buffer;
559 output( "\t.byte " );
560 for (i = 0; i < size - 1; i++, ptr++)
562 if ((i % 16) == 15) output( "0x%02x\n\t.byte ", *ptr );
563 else output( "0x%02x,", *ptr );
565 output( "0x%02x\n", *ptr );
569 /*******************************************************************
572 * Open a file in the given srcdir and set the input_file_name global variable.
574 FILE *open_input_file( const char *srcdir, const char *name )
577 FILE *file = fopen( name, "r" );
581 fullname = xmalloc( strlen(srcdir) + strlen(name) + 2 );
582 strcpy( fullname, srcdir );
583 strcat( fullname, "/" );
584 strcat( fullname, name );
585 file = fopen( fullname, "r" );
587 else fullname = xstrdup( name );
589 if (!file) fatal_error( "Cannot open file '%s'\n", fullname );
590 input_file_name = fullname;
596 /*******************************************************************
599 * Close the current input file (must have been opened with open_input_file).
601 void close_input_file( FILE *file )
604 free( input_file_name );
605 input_file_name = NULL;
610 /*******************************************************************
611 * remove_stdcall_decoration
613 * Remove a possible @xx suffix from a function name.
614 * Return the numerical value of the suffix, or -1 if none.
616 int remove_stdcall_decoration( char *name )
618 char *p, *end = strrchr( name, '@' );
619 if (!end || !end[1] || end == name) return -1;
620 /* make sure all the rest is digits */
621 for (p = end + 1; *p; p++) if (!isdigit(*p)) return -1;
623 return atoi( end + 1 );
627 /*******************************************************************
630 * Run a file through the assembler.
632 void assemble_file( const char *src_file, const char *obj_file )
634 const char *prog = get_as_command();
638 cmd = xmalloc( strlen(prog) + strlen(obj_file) + strlen(src_file) + 6 );
639 sprintf( cmd, "%s -o %s %s", prog, obj_file, src_file );
640 if (verbose) fprintf( stderr, "%s\n", cmd );
642 if (err) fatal_error( "%s failed with status %d\n", prog, err );
647 /*******************************************************************
650 * Create a new dll spec file descriptor
652 DLLSPEC *alloc_dll_spec(void)
656 spec = xmalloc( sizeof(*spec) );
657 spec->file_name = NULL;
658 spec->dll_name = NULL;
659 spec->init_func = NULL;
660 spec->main_module = NULL;
661 spec->type = SPEC_WIN32;
662 spec->base = MAX_ORDINALS;
664 spec->stack_size = 0;
666 spec->nb_entry_points = 0;
667 spec->alloc_entry_points = 0;
669 spec->nb_resources = 0;
670 spec->characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
671 if (get_ptr_size() > 4)
672 spec->characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
674 spec->characteristics |= IMAGE_FILE_32BIT_MACHINE;
675 spec->dll_characteristics = IMAGE_DLLCHARACTERISTICS_NX_COMPAT;
677 spec->subsystem_major = 4;
678 spec->subsystem_minor = 0;
679 spec->entry_points = NULL;
681 spec->ordinals = NULL;
682 spec->resources = NULL;
687 /*******************************************************************
690 * Free dll spec file descriptor
692 void free_dll_spec( DLLSPEC *spec )
696 for (i = 0; i < spec->nb_entry_points; i++)
698 ORDDEF *odp = &spec->entry_points[i];
700 free( odp->export_name );
701 free( odp->link_name );
703 free( spec->file_name );
704 free( spec->dll_name );
705 free( spec->init_func );
706 free( spec->entry_points );
708 free( spec->ordinals );
709 free( spec->resources );
714 /*******************************************************************
717 * Map a string to a valid C identifier.
719 const char *make_c_identifier( const char *str )
721 static char buffer[256];
724 for (p = buffer; *str && p < buffer+sizeof(buffer)-1; p++, str++)
726 if (isalnum(*str)) *p = *str;
734 /*******************************************************************
737 * Generate an internal name for a stub entry point.
739 const char *get_stub_name( const ORDDEF *odp, const DLLSPEC *spec )
741 static char buffer[256];
742 if (odp->name || odp->export_name)
745 sprintf( buffer, "__wine_stub_%s", odp->name ? odp->name : odp->export_name );
746 /* make sure name is a legal C identifier */
747 for (p = buffer; *p; p++) if (!isalnum(*p) && *p != '_') break;
748 if (!*p) return buffer;
750 sprintf( buffer, "__wine_stub_%s_%d", make_c_identifier(spec->file_name), odp->ordinal );
754 /* parse a cpu name and return the corresponding value */
755 enum target_cpu get_cpu_from_name( const char *name )
759 for (i = 0; i < sizeof(cpu_names)/sizeof(cpu_names[0]); i++)
760 if (!strcmp( cpu_names[i].name, name )) return cpu_names[i].cpu;
764 /*****************************************************************
765 * Function: get_alignment
768 * According to the info page for gas, the .align directive behaves
769 * differently on different systems. On some architectures, the
770 * argument of a .align directive is the number of bytes to pad to, so
771 * to align on an 8-byte boundary you'd say
773 * On other systems, the argument is "the number of low-order zero bits
774 * that the location counter must have after advancement." So to
775 * align on an 8-byte boundary you'd say
778 * The reason gas is written this way is that it's trying to mimick
779 * native assemblers for the various architectures it runs on. gas
780 * provides other directives that work consistently across
781 * architectures, but of course we want to work on all arches with or
782 * without gas. Hence this function.
786 * align -- the number of bytes to align to. Must be a power of 2.
788 unsigned int get_alignment(unsigned int align)
792 assert( !(align & (align - 1)) );
800 if (target_platform != PLATFORM_APPLE) return align;
805 while ((1u << n) != align) n++;
813 /* return the page size for the target CPU */
814 unsigned int get_page_size(void)
818 case CPU_x86: return 4096;
819 case CPU_x86_64: return 4096;
820 case CPU_POWERPC: return 4096;
821 case CPU_ARM: return 4096;
822 case CPU_SPARC: return 8192;
823 case CPU_ALPHA: return 8192;
830 /* return the size of a pointer on the target CPU */
831 unsigned int get_ptr_size(void)
849 /* return the assembly name for a C symbol */
850 const char *asm_name( const char *sym )
852 static char buffer[256];
854 switch (target_platform)
857 case PLATFORM_WINDOWS:
858 if (sym[0] == '.' && sym[1] == 'L') return sym;
860 strcpy( buffer + 1, sym );
867 /* return an assembly function declaration for a C function name */
868 const char *func_declaration( const char *func )
870 static char buffer[256];
872 switch (target_platform)
876 case PLATFORM_WINDOWS:
877 sprintf( buffer, ".def _%s; .scl 2; .type 32; .endef", func );
883 sprintf( buffer, ".type %s,%%function", func );
886 sprintf( buffer, ".type %s,@function", func );
894 /* output a size declaration for an assembly function */
895 void output_function_size( const char *name )
897 switch (target_platform)
900 case PLATFORM_WINDOWS:
903 output( "\t.size %s, .-%s\n", name, name );
908 /* output the GNU note for non-exec stack */
909 void output_gnu_stack_note(void)
911 switch (target_platform)
913 case PLATFORM_WINDOWS:
920 output( "\t.section .note.GNU-stack,\"\",%%progbits\n" );
923 output( "\t.section .note.GNU-stack,\"\",@progbits\n" );
930 /* return a global symbol declaration for an assembly symbol */
931 const char *asm_globl( const char *func )
933 static char buffer[256];
935 switch (target_platform)
938 sprintf( buffer, "\t.globl _%s\n\t.private_extern _%s\n_%s:", func, func, func );
940 case PLATFORM_WINDOWS:
941 sprintf( buffer, "\t.globl _%s\n_%s:", func, func );
944 sprintf( buffer, "\t.globl %s\n\t.hidden %s\n%s:", func, func, func );
949 const char *get_asm_ptr_keyword(void)
951 switch(get_ptr_size())
953 case 4: return ".long";
954 case 8: return ".quad";
960 const char *get_asm_string_keyword(void)
962 switch (target_platform)
971 const char *get_asm_short_keyword(void)
973 switch (target_platform)
975 default: return ".short";
979 const char *get_asm_rodata_section(void)
981 switch (target_platform)
983 case PLATFORM_APPLE: return ".const";
984 default: return ".section .rodata";
988 const char *get_asm_string_section(void)
990 switch (target_platform)
992 case PLATFORM_APPLE: return ".cstring";
993 default: return ".section .rodata";