Release 1.5.29.
[wine] / tools / winebuild / utils.c
1 /*
2  * Small utility functions for winebuild
3  *
4  * Copyright 2000 Alexandre Julliard
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <ctype.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #ifdef HAVE_SYS_STAT_H
34 # include <sys/stat.h>
35 #endif
36 #ifdef HAVE_SYS_MMAN_H
37 #include <sys/mman.h>
38 #endif
39
40 #include "build.h"
41
42 static const char **tmp_files;
43 static unsigned int nb_tmp_files;
44 static unsigned int max_tmp_files;
45
46 static const struct
47 {
48     const char *name;
49     enum target_cpu cpu;
50 } cpu_names[] =
51 {
52     { "i386",    CPU_x86 },
53     { "i486",    CPU_x86 },
54     { "i586",    CPU_x86 },
55     { "i686",    CPU_x86 },
56     { "i786",    CPU_x86 },
57     { "amd64",   CPU_x86_64 },
58     { "x86_64",  CPU_x86_64 },
59     { "powerpc", CPU_POWERPC },
60     { "arm",     CPU_ARM },
61     { "arm64",   CPU_ARM64 },
62     { "aarch64", CPU_ARM64 },
63 };
64
65 /* atexit handler to clean tmp files */
66 void cleanup_tmp_files(void)
67 {
68     unsigned int i;
69     for (i = 0; i < nb_tmp_files; i++) if (tmp_files[i]) unlink( tmp_files[i] );
70 }
71
72
73 void *xmalloc (size_t size)
74 {
75     void *res;
76
77     res = malloc (size ? size : 1);
78     if (res == NULL)
79     {
80         fprintf (stderr, "Virtual memory exhausted.\n");
81         exit (1);
82     }
83     return res;
84 }
85
86 void *xrealloc (void *ptr, size_t size)
87 {
88     void *res = realloc (ptr, size);
89     if (size && res == NULL)
90     {
91         fprintf (stderr, "Virtual memory exhausted.\n");
92         exit (1);
93     }
94     return res;
95 }
96
97 char *xstrdup( const char *str )
98 {
99     char *res = strdup( str );
100     if (!res)
101     {
102         fprintf (stderr, "Virtual memory exhausted.\n");
103         exit (1);
104     }
105     return res;
106 }
107
108 char *strupper(char *s)
109 {
110     char *p;
111     for (p = s; *p; p++) *p = toupper(*p);
112     return s;
113 }
114
115 int strendswith(const char* str, const char* end)
116 {
117     int l = strlen(str);
118     int m = strlen(end);
119     return l >= m && strcmp(str + l - m, end) == 0;
120 }
121
122 char *strmake( const char* fmt, ... )
123 {
124     int n;
125     size_t size = 100;
126     va_list ap;
127
128     for (;;)
129     {
130         char *p = xmalloc( size );
131         va_start( ap, fmt );
132         n = vsnprintf( p, size, fmt, ap );
133         va_end( ap );
134         if (n == -1) size *= 2;
135         else if ((size_t)n >= size) size = n + 1;
136         else return p;
137         free( p );
138     }
139 }
140
141 struct strarray *strarray_init(void)
142 {
143     struct strarray *array = xmalloc( sizeof(*array) );
144     array->count = 0;
145     array->max = 16;
146     array->str = xmalloc( array->max * sizeof(*array->str) );
147     return array;
148 }
149
150 static void strarray_add_one( struct strarray *array, const char *str )
151 {
152     if (array->count == array->max)
153     {
154         array->max *= 2;
155         array->str = xrealloc( array->str, array->max * sizeof(*array->str) );
156     }
157     array->str[array->count++] = str;
158 }
159
160 void strarray_add( struct strarray *array, ... )
161 {
162     va_list valist;
163     const char *str;
164
165     va_start( valist, array );
166     while ((str = va_arg( valist, const char *))) strarray_add_one( array, str );
167     va_end( valist );
168 }
169
170 void strarray_addv( struct strarray *array, char * const *argv )
171 {
172     while (*argv) strarray_add_one( array, *argv++ );
173 }
174
175 void strarray_free( struct strarray *array )
176 {
177     free( array->str );
178     free( array );
179 }
180
181 void fatal_error( const char *msg, ... )
182 {
183     va_list valist;
184     va_start( valist, msg );
185     if (input_file_name)
186     {
187         fprintf( stderr, "%s:", input_file_name );
188         if (current_line)
189             fprintf( stderr, "%d:", current_line );
190         fputc( ' ', stderr );
191     }
192     else fprintf( stderr, "winebuild: " );
193     vfprintf( stderr, msg, valist );
194     va_end( valist );
195     exit(1);
196 }
197
198 void fatal_perror( const char *msg, ... )
199 {
200     va_list valist;
201     va_start( valist, msg );
202     if (input_file_name)
203     {
204         fprintf( stderr, "%s:", input_file_name );
205         if (current_line)
206             fprintf( stderr, "%d:", current_line );
207         fputc( ' ', stderr );
208     }
209     vfprintf( stderr, msg, valist );
210     perror( " " );
211     va_end( valist );
212     exit(1);
213 }
214
215 void error( const char *msg, ... )
216 {
217     va_list valist;
218     va_start( valist, msg );
219     if (input_file_name)
220     {
221         fprintf( stderr, "%s:", input_file_name );
222         if (current_line)
223             fprintf( stderr, "%d:", current_line );
224         fputc( ' ', stderr );
225     }
226     vfprintf( stderr, msg, valist );
227     va_end( valist );
228     nb_errors++;
229 }
230
231 void warning( const char *msg, ... )
232 {
233     va_list valist;
234
235     if (!display_warnings) return;
236     va_start( valist, msg );
237     if (input_file_name)
238     {
239         fprintf( stderr, "%s:", input_file_name );
240         if (current_line)
241             fprintf( stderr, "%d:", current_line );
242         fputc( ' ', stderr );
243     }
244     fprintf( stderr, "warning: " );
245     vfprintf( stderr, msg, valist );
246     va_end( valist );
247 }
248
249 int output( const char *format, ... )
250 {
251     int ret;
252     va_list valist;
253
254     va_start( valist, format );
255     ret = vfprintf( output_file, format, valist );
256     va_end( valist );
257     if (ret < 0) fatal_perror( "Output error" );
258     return ret;
259 }
260
261 void spawn( struct strarray *args )
262 {
263     unsigned int i;
264     int status;
265
266     strarray_add_one( args, NULL );
267     if (verbose)
268         for (i = 0; args->str[i]; i++)
269             fprintf( stderr, "%s%c", args->str[i], args->str[i+1] ? ' ' : '\n' );
270
271     if ((status = _spawnvp( _P_WAIT, args->str[0], args->str )))
272     {
273         if (status > 0) fatal_error( "%s failed with status %u\n", args->str[0], status );
274         else fatal_perror( "winebuild" );
275         exit( 1 );
276     }
277 }
278
279 /* find a build tool in the path, trying the various names */
280 char *find_tool( const char *name, const char * const *names )
281 {
282     static char **dirs;
283     static unsigned int count, maxlen;
284
285     char *p, *file;
286     const char *alt_names[2];
287     unsigned int i, len;
288     struct stat st;
289
290     if (!dirs)
291     {
292         char *path;
293
294         /* split the path in directories */
295
296         if (!getenv( "PATH" )) return NULL;
297         path = xstrdup( getenv( "PATH" ));
298         for (p = path, count = 2; *p; p++) if (*p == ':') count++;
299         dirs = xmalloc( count * sizeof(*dirs) );
300         count = 0;
301         dirs[count++] = p = path;
302         while (*p)
303         {
304             while (*p && *p != ':') p++;
305             if (!*p) break;
306             *p++ = 0;
307             dirs[count++] = p;
308         }
309         for (i = 0; i < count; i++) maxlen = max( maxlen, strlen(dirs[i])+2 );
310     }
311
312     if (!names)
313     {
314         alt_names[0] = name;
315         alt_names[1] = NULL;
316         names = alt_names;
317     }
318
319     while (*names)
320     {
321         len = strlen(*names) + sizeof(EXEEXT) + 1;
322         if (target_alias)
323             len += strlen(target_alias) + 1;
324         file = xmalloc( maxlen + len );
325
326         for (i = 0; i < count; i++)
327         {
328             strcpy( file, dirs[i] );
329             p = file + strlen(file);
330             if (p == file) *p++ = '.';
331             if (p[-1] != '/') *p++ = '/';
332             if (target_alias)
333             {
334                 strcpy( p, target_alias );
335                 p += strlen(p);
336                 *p++ = '-';
337             }
338             strcpy( p, *names );
339             strcat( p, EXEEXT );
340
341             if (!stat( file, &st ) && S_ISREG(st.st_mode) && (st.st_mode & 0111)) return file;
342         }
343         free( file );
344         names++;
345     }
346     return NULL;
347 }
348
349 struct strarray *get_as_command(void)
350 {
351     static int as_is_clang = 0;
352     struct strarray *args = strarray_init();
353
354     if (!as_command)
355     {
356         as_command = find_tool( "clang", NULL );
357         if (as_command) as_is_clang = 1;
358     }
359
360     if (!as_command)
361     {
362         static const char * const commands[] = { "gas", "as", NULL };
363         as_command = find_tool( "as", commands );
364     }
365
366     if (!as_command)
367         fatal_error( "cannot find suitable assembler\n" );
368
369     strarray_add_one( args, as_command );
370
371     if (as_is_clang)
372     {
373         strarray_add( args, "-xassembler", "-c", NULL );
374         if (force_pointer_size)
375             strarray_add_one( args, (force_pointer_size == 8) ? "-m64" : "-m32" );
376     }
377     else if (force_pointer_size)
378     {
379         switch (target_platform)
380         {
381         case PLATFORM_APPLE:
382             strarray_add( args, "-arch", (force_pointer_size == 8) ? "x86_64" : "i386", NULL );
383             break;
384         default:
385             switch(target_cpu)
386             {
387             case CPU_POWERPC:
388                 strarray_add_one( args, (force_pointer_size == 8) ? "-a64" : "-a32" );
389                 break;
390             default:
391                 strarray_add_one( args, (force_pointer_size == 8) ? "--64" : "--32" );
392                 break;
393             }
394             break;
395         }
396     }
397
398     if (cpu_option) strarray_add_one( args, strmake("-mcpu=%s", cpu_option) );
399     return args;
400 }
401
402 struct strarray *get_ld_command(void)
403 {
404     struct strarray *args = strarray_init();
405
406     if (!ld_command)
407     {
408         static const char * const commands[] = { "ld", "gld", NULL };
409         ld_command = find_tool( "ld", commands );
410     }
411
412     if (!ld_command)
413         fatal_error( "cannot find suitable linker\n" );
414
415     strarray_add_one( args, ld_command );
416
417     if (force_pointer_size)
418     {
419         switch (target_platform)
420         {
421         case PLATFORM_APPLE:
422             strarray_add( args, "-arch", (force_pointer_size == 8) ? "x86_64" : "i386", NULL );
423             break;
424         case PLATFORM_FREEBSD:
425             strarray_add( args, "-m", (force_pointer_size == 8) ? "elf_x86_64_fbsd" : "elf_i386_fbsd", NULL );
426             break;
427         default:
428             switch(target_cpu)
429             {
430             case CPU_POWERPC:
431                 strarray_add( args, "-m", (force_pointer_size == 8) ? "elf64ppc" : "elf32ppc", NULL );
432                 break;
433             default:
434                 strarray_add( args, "-m", (force_pointer_size == 8) ? "elf_x86_64" : "elf_i386", NULL );
435                 break;
436             }
437             break;
438         }
439     }
440     return args;
441 }
442
443 const char *get_nm_command(void)
444 {
445     if (!nm_command)
446     {
447         static const char * const commands[] = { "nm", "gnm", NULL };
448         nm_command = find_tool( "nm", commands );
449     }
450
451     if (!nm_command)
452         fatal_error( "cannot find suitable name lister\n" );
453     return nm_command;
454 }
455
456 /* get a name for a temp file, automatically cleaned up on exit */
457 char *get_temp_file_name( const char *prefix, const char *suffix )
458 {
459     char *name;
460     const char *ext, *basename;
461     int fd;
462
463     if (!prefix || !prefix[0]) prefix = "winebuild";
464     if (!suffix) suffix = "";
465     if ((basename = strrchr( prefix, '/' ))) basename++;
466     else basename = prefix;
467     if (!(ext = strchr( basename, '.' ))) ext = prefix + strlen(prefix);
468     name = xmalloc( sizeof("/tmp/") + (ext - prefix) + sizeof(".XXXXXX") + strlen(suffix) );
469     memcpy( name, prefix, ext - prefix );
470     strcpy( name + (ext - prefix), ".XXXXXX" );
471     strcat( name, suffix );
472
473     if ((fd = mkstemps( name, strlen(suffix) )) == -1)
474     {
475         strcpy( name, "/tmp/" );
476         memcpy( name + 5, basename, ext - basename );
477         strcpy( name + 5 + (ext - basename), ".XXXXXX" );
478         strcat( name, suffix );
479         if ((fd = mkstemps( name, strlen(suffix) )) == -1)
480             fatal_error( "could not generate a temp file\n" );
481     }
482
483     close( fd );
484     if (nb_tmp_files >= max_tmp_files)
485     {
486         max_tmp_files = max( 2 * max_tmp_files, 8 );
487         tmp_files = xrealloc( tmp_files, max_tmp_files * sizeof(tmp_files[0]) );
488     }
489     tmp_files[nb_tmp_files++] = name;
490     return name;
491 }
492
493 /*******************************************************************
494  *         buffer management
495  *
496  * Function for reading from/writing to a memory buffer.
497  */
498
499 int byte_swapped = 0;
500 const char *input_buffer_filename;
501 const unsigned char *input_buffer;
502 size_t input_buffer_pos;
503 size_t input_buffer_size;
504 unsigned char *output_buffer;
505 size_t output_buffer_pos;
506 size_t output_buffer_size;
507
508 static void check_output_buffer_space( size_t size )
509 {
510     if (output_buffer_pos + size >= output_buffer_size)
511     {
512         output_buffer_size = max( output_buffer_size * 2, output_buffer_pos + size );
513         output_buffer = xrealloc( output_buffer, output_buffer_size );
514     }
515 }
516
517 void init_input_buffer( const char *file )
518 {
519     int fd;
520     struct stat st;
521
522     if ((fd = open( file, O_RDONLY | O_BINARY )) == -1) fatal_perror( "Cannot open %s", file );
523     if ((fstat( fd, &st ) == -1)) fatal_perror( "Cannot stat %s", file );
524     if (!st.st_size) fatal_error( "%s is an empty file\n", file );
525 #ifdef  HAVE_MMAP
526     if ((input_buffer = mmap( NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0 )) == (void*)-1)
527 #endif
528     {
529         unsigned char *buffer = xmalloc( st.st_size );
530         if (read( fd, buffer, st.st_size ) != st.st_size) fatal_error( "Cannot read %s\n", file );
531         input_buffer = buffer;
532     }
533     close( fd );
534     input_buffer_filename = xstrdup( file );
535     input_buffer_size = st.st_size;
536     input_buffer_pos = 0;
537     byte_swapped = 0;
538 }
539
540 void init_output_buffer(void)
541 {
542     output_buffer_size = 1024;
543     output_buffer_pos = 0;
544     output_buffer = xmalloc( output_buffer_size );
545 }
546
547 void flush_output_buffer(void)
548 {
549     if (fwrite( output_buffer, 1, output_buffer_pos, output_file ) != output_buffer_pos)
550         fatal_error( "Error writing to %s\n", output_file_name );
551     free( output_buffer );
552 }
553
554 unsigned char get_byte(void)
555 {
556     if (input_buffer_pos >= input_buffer_size)
557         fatal_error( "%s is a truncated file\n", input_buffer_filename );
558     return input_buffer[input_buffer_pos++];
559 }
560
561 unsigned short get_word(void)
562 {
563     unsigned short ret;
564
565     if (input_buffer_pos + sizeof(ret) > input_buffer_size)
566         fatal_error( "%s is a truncated file\n", input_buffer_filename );
567     memcpy( &ret, input_buffer + input_buffer_pos, sizeof(ret) );
568     if (byte_swapped) ret = (ret << 8) | (ret >> 8);
569     input_buffer_pos += sizeof(ret);
570     return ret;
571 }
572
573 unsigned int get_dword(void)
574 {
575     unsigned int ret;
576
577     if (input_buffer_pos + sizeof(ret) > input_buffer_size)
578         fatal_error( "%s is a truncated file\n", input_buffer_filename );
579     memcpy( &ret, input_buffer + input_buffer_pos, sizeof(ret) );
580     if (byte_swapped)
581         ret = ((ret << 24) | ((ret << 8) & 0x00ff0000) | ((ret >> 8) & 0x0000ff00) | (ret >> 24));
582     input_buffer_pos += sizeof(ret);
583     return ret;
584 }
585
586 void put_data( const void *data, size_t size )
587 {
588     check_output_buffer_space( size );
589     memcpy( output_buffer + output_buffer_pos, data, size );
590     output_buffer_pos += size;
591 }
592
593 void put_byte( unsigned char val )
594 {
595     check_output_buffer_space( 1 );
596     output_buffer[output_buffer_pos++] = val;
597 }
598
599 void put_word( unsigned short val )
600 {
601     if (byte_swapped) val = (val << 8) | (val >> 8);
602     put_data( &val, sizeof(val) );
603 }
604
605 void put_dword( unsigned int val )
606 {
607     if (byte_swapped)
608         val = ((val << 24) | ((val << 8) & 0x00ff0000) | ((val >> 8) & 0x0000ff00) | (val >> 24));
609     put_data( &val, sizeof(val) );
610 }
611
612 void put_qword( unsigned int val )
613 {
614     if (byte_swapped)
615     {
616         put_dword( 0 );
617         put_dword( val );
618     }
619     else
620     {
621         put_dword( val );
622         put_dword( 0 );
623     }
624 }
625
626 /* pointer-sized word */
627 void put_pword( unsigned int val )
628 {
629     if (get_ptr_size() == 8) put_qword( val );
630     else put_dword( val );
631 }
632
633 void align_output( unsigned int align )
634 {
635     size_t size = align - (output_buffer_pos % align);
636
637     if (size == align) return;
638     check_output_buffer_space( size );
639     memset( output_buffer + output_buffer_pos, 0, size );
640     output_buffer_pos += size;
641 }
642
643 /* output a standard header for generated files */
644 void output_standard_file_header(void)
645 {
646     if (spec_file_name)
647         output( "/* File generated automatically from %s; do not edit! */\n", spec_file_name );
648     else
649         output( "/* File generated automatically; do not edit! */\n" );
650     output( "/* This file can be copied, modified and distributed without restriction. */\n\n" );
651 }
652
653 /* dump a byte stream into the assembly code */
654 void dump_bytes( const void *buffer, unsigned int size )
655 {
656     unsigned int i;
657     const unsigned char *ptr = buffer;
658
659     if (!size) return;
660     output( "\t.byte " );
661     for (i = 0; i < size - 1; i++, ptr++)
662     {
663         if ((i % 16) == 15) output( "0x%02x\n\t.byte ", *ptr );
664         else output( "0x%02x,", *ptr );
665     }
666     output( "0x%02x\n", *ptr );
667 }
668
669
670 /*******************************************************************
671  *         open_input_file
672  *
673  * Open a file in the given srcdir and set the input_file_name global variable.
674  */
675 FILE *open_input_file( const char *srcdir, const char *name )
676 {
677     char *fullname;
678     FILE *file = fopen( name, "r" );
679
680     if (!file && srcdir)
681     {
682         fullname = strmake( "%s/%s", srcdir, name );
683         file = fopen( fullname, "r" );
684     }
685     else fullname = xstrdup( name );
686
687     if (!file) fatal_error( "Cannot open file '%s'\n", fullname );
688     input_file_name = fullname;
689     current_line = 1;
690     return file;
691 }
692
693
694 /*******************************************************************
695  *         close_input_file
696  *
697  * Close the current input file (must have been opened with open_input_file).
698  */
699 void close_input_file( FILE *file )
700 {
701     fclose( file );
702     free( input_file_name );
703     input_file_name = NULL;
704     current_line = 0;
705 }
706
707
708 /*******************************************************************
709  *         remove_stdcall_decoration
710  *
711  * Remove a possible @xx suffix from a function name.
712  * Return the numerical value of the suffix, or -1 if none.
713  */
714 int remove_stdcall_decoration( char *name )
715 {
716     char *p, *end = strrchr( name, '@' );
717     if (!end || !end[1] || end == name) return -1;
718     if (target_cpu != CPU_x86) return -1;
719     /* make sure all the rest is digits */
720     for (p = end + 1; *p; p++) if (!isdigit(*p)) return -1;
721     *end = 0;
722     return atoi( end + 1 );
723 }
724
725
726 /*******************************************************************
727  *         assemble_file
728  *
729  * Run a file through the assembler.
730  */
731 void assemble_file( const char *src_file, const char *obj_file )
732 {
733     struct strarray *args = get_as_command();
734     strarray_add( args, "-o", obj_file, src_file, NULL );
735     spawn( args );
736     strarray_free( args );
737 }
738
739
740 /*******************************************************************
741  *         alloc_dll_spec
742  *
743  * Create a new dll spec file descriptor
744  */
745 DLLSPEC *alloc_dll_spec(void)
746 {
747     DLLSPEC *spec;
748
749     spec = xmalloc( sizeof(*spec) );
750     spec->file_name          = NULL;
751     spec->dll_name           = NULL;
752     spec->init_func          = NULL;
753     spec->main_module        = NULL;
754     spec->type               = SPEC_WIN32;
755     spec->base               = MAX_ORDINALS;
756     spec->limit              = 0;
757     spec->stack_size         = 0;
758     spec->heap_size          = 0;
759     spec->nb_entry_points    = 0;
760     spec->alloc_entry_points = 0;
761     spec->nb_names           = 0;
762     spec->nb_resources       = 0;
763     spec->characteristics    = IMAGE_FILE_EXECUTABLE_IMAGE;
764     if (get_ptr_size() > 4)
765         spec->characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
766     else
767         spec->characteristics |= IMAGE_FILE_32BIT_MACHINE;
768     spec->dll_characteristics = IMAGE_DLLCHARACTERISTICS_NX_COMPAT;
769     spec->subsystem          = 0;
770     spec->subsystem_major    = 4;
771     spec->subsystem_minor    = 0;
772     spec->entry_points       = NULL;
773     spec->names              = NULL;
774     spec->ordinals           = NULL;
775     spec->resources          = NULL;
776     return spec;
777 }
778
779
780 /*******************************************************************
781  *         free_dll_spec
782  *
783  * Free dll spec file descriptor
784  */
785 void free_dll_spec( DLLSPEC *spec )
786 {
787     int i;
788
789     for (i = 0; i < spec->nb_entry_points; i++)
790     {
791         ORDDEF *odp = &spec->entry_points[i];
792         free( odp->name );
793         free( odp->export_name );
794         free( odp->link_name );
795     }
796     free( spec->file_name );
797     free( spec->dll_name );
798     free( spec->init_func );
799     free( spec->entry_points );
800     free( spec->names );
801     free( spec->ordinals );
802     free( spec->resources );
803     free( spec );
804 }
805
806
807 /*******************************************************************
808  *         make_c_identifier
809  *
810  * Map a string to a valid C identifier.
811  */
812 const char *make_c_identifier( const char *str )
813 {
814     static char buffer[256];
815     char *p;
816
817     for (p = buffer; *str && p < buffer+sizeof(buffer)-1; p++, str++)
818     {
819         if (isalnum(*str)) *p = *str;
820         else *p = '_';
821     }
822     *p = 0;
823     return buffer;
824 }
825
826
827 /*******************************************************************
828  *         get_stub_name
829  *
830  * Generate an internal name for a stub entry point.
831  */
832 const char *get_stub_name( const ORDDEF *odp, const DLLSPEC *spec )
833 {
834     static char *buffer;
835
836     free( buffer );
837     if (odp->name || odp->export_name)
838     {
839         char *p;
840         buffer = strmake( "__wine_stub_%s", odp->name ? odp->name : odp->export_name );
841         /* make sure name is a legal C identifier */
842         for (p = buffer; *p; p++) if (!isalnum(*p) && *p != '_') break;
843         if (!*p) return buffer;
844         free( buffer );
845     }
846     buffer = strmake( "__wine_stub_%s_%d", make_c_identifier(spec->file_name), odp->ordinal );
847     return buffer;
848 }
849
850 /* parse a cpu name and return the corresponding value */
851 enum target_cpu get_cpu_from_name( const char *name )
852 {
853     unsigned int i;
854
855     for (i = 0; i < sizeof(cpu_names)/sizeof(cpu_names[0]); i++)
856         if (!strcmp( cpu_names[i].name, name )) return cpu_names[i].cpu;
857     return -1;
858 }
859
860 /*****************************************************************
861  *  Function:    get_alignment
862  *
863  *  Description:
864  *    According to the info page for gas, the .align directive behaves
865  * differently on different systems.  On some architectures, the
866  * argument of a .align directive is the number of bytes to pad to, so
867  * to align on an 8-byte boundary you'd say
868  *     .align 8
869  * On other systems, the argument is "the number of low-order zero bits
870  * that the location counter must have after advancement."  So to
871  * align on an 8-byte boundary you'd say
872  *     .align 3
873  *
874  * The reason gas is written this way is that it's trying to mimick
875  * native assemblers for the various architectures it runs on.  gas
876  * provides other directives that work consistently across
877  * architectures, but of course we want to work on all arches with or
878  * without gas.  Hence this function.
879  *
880  *
881  *  Parameters:
882  *    align  --  the number of bytes to align to. Must be a power of 2.
883  */
884 unsigned int get_alignment(unsigned int align)
885 {
886     unsigned int n;
887
888     assert( !(align & (align - 1)) );
889
890     switch(target_cpu)
891     {
892     case CPU_x86:
893     case CPU_x86_64:
894         if (target_platform != PLATFORM_APPLE) return align;
895         /* fall through */
896     case CPU_POWERPC:
897     case CPU_ARM:
898     case CPU_ARM64:
899         n = 0;
900         while ((1u << n) != align) n++;
901         return n;
902     }
903     /* unreached */
904     assert(0);
905     return 0;
906 }
907
908 /* return the page size for the target CPU */
909 unsigned int get_page_size(void)
910 {
911     switch(target_cpu)
912     {
913     case CPU_x86:     return 4096;
914     case CPU_x86_64:  return 4096;
915     case CPU_POWERPC: return 4096;
916     case CPU_ARM:     return 4096;
917     case CPU_ARM64:   return 4096;
918     }
919     /* unreached */
920     assert(0);
921     return 0;
922 }
923
924 /* return the size of a pointer on the target CPU */
925 unsigned int get_ptr_size(void)
926 {
927     switch(target_cpu)
928     {
929     case CPU_x86:
930     case CPU_POWERPC:
931     case CPU_ARM:
932         return 4;
933     case CPU_x86_64:
934     case CPU_ARM64:
935         return 8;
936     }
937     /* unreached */
938     assert(0);
939     return 0;
940 }
941
942 /* return the total size in bytes of the arguments on the stack */
943 unsigned int get_args_size( const ORDDEF *odp )
944 {
945     int i, size;
946
947     for (i = size = 0; i < odp->u.func.nb_args; i++)
948     {
949         switch (odp->u.func.args[i])
950         {
951         case ARG_INT64:
952         case ARG_DOUBLE:
953             size += 8;
954             break;
955         case ARG_INT128:
956             /* int128 is passed as pointer on x86_64 */
957             if (target_cpu != CPU_x86_64)
958             {
959                 size += 16;
960                 break;
961             }
962             /* fall through */
963         default:
964             size += get_ptr_size();
965             break;
966         }
967     }
968     return size;
969 }
970
971 /* return the assembly name for a C symbol */
972 const char *asm_name( const char *sym )
973 {
974     static char *buffer;
975
976     switch (target_platform)
977     {
978     case PLATFORM_APPLE:
979     case PLATFORM_WINDOWS:
980         if (sym[0] == '.' && sym[1] == 'L') return sym;
981         free( buffer );
982         buffer = strmake( "_%s", sym );
983         return buffer;
984     default:
985         return sym;
986     }
987 }
988
989 /* return an assembly function declaration for a C function name */
990 const char *func_declaration( const char *func )
991 {
992     static char *buffer;
993
994     switch (target_platform)
995     {
996     case PLATFORM_APPLE:
997         return "";
998     case PLATFORM_WINDOWS:
999         free( buffer );
1000         buffer = strmake( ".def _%s; .scl 2; .type 32; .endef", func );
1001         break;
1002     default:
1003         free( buffer );
1004         switch(target_cpu)
1005         {
1006         case CPU_ARM:
1007         case CPU_ARM64:
1008             buffer = strmake( ".type %s,%%function", func );
1009             break;
1010         default:
1011             buffer = strmake( ".type %s,@function", func );
1012             break;
1013         }
1014         break;
1015     }
1016     return buffer;
1017 }
1018
1019 /* output a size declaration for an assembly function */
1020 void output_function_size( const char *name )
1021 {
1022     switch (target_platform)
1023     {
1024     case PLATFORM_APPLE:
1025     case PLATFORM_WINDOWS:
1026         break;
1027     default:
1028         output( "\t.size %s, .-%s\n", name, name );
1029         break;
1030     }
1031 }
1032
1033 /* output a .cfi directive */
1034 void output_cfi( const char *format, ... )
1035 {
1036     va_list valist;
1037
1038     if (!unwind_tables) return;
1039     va_start( valist, format );
1040     fputc( '\t', output_file );
1041     vfprintf( output_file, format, valist );
1042     fputc( '\n', output_file );
1043     va_end( valist );
1044 }
1045
1046 /* output the GNU note for non-exec stack */
1047 void output_gnu_stack_note(void)
1048 {
1049     switch (target_platform)
1050     {
1051     case PLATFORM_WINDOWS:
1052     case PLATFORM_APPLE:
1053         break;
1054     default:
1055         switch(target_cpu)
1056         {
1057         case CPU_ARM:
1058         case CPU_ARM64:
1059             output( "\t.section .note.GNU-stack,\"\",%%progbits\n" );
1060             break;
1061         default:
1062             output( "\t.section .note.GNU-stack,\"\",@progbits\n" );
1063             break;
1064         }
1065         break;
1066     }
1067 }
1068
1069 /* return a global symbol declaration for an assembly symbol */
1070 const char *asm_globl( const char *func )
1071 {
1072     static char *buffer;
1073
1074     free( buffer );
1075     switch (target_platform)
1076     {
1077     case PLATFORM_APPLE:
1078         buffer = strmake( "\t.globl _%s\n\t.private_extern _%s\n_%s:", func, func, func );
1079         break;
1080     case PLATFORM_WINDOWS:
1081         buffer = strmake( "\t.globl _%s\n_%s:", func, func );
1082         break;
1083     default:
1084         buffer = strmake( "\t.globl %s\n\t.hidden %s\n%s:", func, func, func );
1085         break;
1086     }
1087     return buffer;
1088 }
1089
1090 const char *get_asm_ptr_keyword(void)
1091 {
1092     switch(get_ptr_size())
1093     {
1094     case 4: return ".long";
1095     case 8: return ".quad";
1096     }
1097     assert(0);
1098     return NULL;
1099 }
1100
1101 const char *get_asm_string_keyword(void)
1102 {
1103     switch (target_platform)
1104     {
1105     case PLATFORM_APPLE:
1106         return ".asciz";
1107     default:
1108         return ".string";
1109     }
1110 }
1111
1112 const char *get_asm_rodata_section(void)
1113 {
1114     switch (target_platform)
1115     {
1116     case PLATFORM_APPLE: return ".const";
1117     default:             return ".section .rodata";
1118     }
1119 }
1120
1121 const char *get_asm_string_section(void)
1122 {
1123     switch (target_platform)
1124     {
1125     case PLATFORM_APPLE: return ".cstring";
1126     default:             return ".section .rodata";
1127     }
1128 }