msxml3: Ignore XML property ResolveExternals.
[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     { "sparc",   CPU_SPARC },
60     { "alpha",   CPU_ALPHA },
61     { "powerpc", CPU_POWERPC },
62     { "arm", CPU_ARM }
63 };
64
65 /* atexit handler to clean tmp files */
66 static 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 (target_alias) return strmake( "%s-%s", target_alias, name );
291
292     if (!dirs)
293     {
294         char *path;
295
296         /* split the path in directories */
297
298         if (!getenv( "PATH" )) return NULL;
299         path = xstrdup( getenv( "PATH" ));
300         for (p = path, count = 2; *p; p++) if (*p == ':') count++;
301         dirs = xmalloc( count * sizeof(*dirs) );
302         count = 0;
303         dirs[count++] = p = path;
304         while (*p)
305         {
306             while (*p && *p != ':') p++;
307             if (!*p) break;
308             *p++ = 0;
309             dirs[count++] = p;
310         }
311         for (i = 0; i < count; i++) maxlen = max( maxlen, strlen(dirs[i])+2 );
312     }
313
314     if (!names)
315     {
316         alt_names[0] = name;
317         alt_names[1] = NULL;
318         names = alt_names;
319     }
320
321     while (*names)
322     {
323         len = strlen(*names) + sizeof(EXEEXT) + 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             strcpy( p, *names );
333             strcat( p, EXEEXT );
334
335             if (!stat( file, &st ) && S_ISREG(st.st_mode) && (st.st_mode & 0111)) return file;
336         }
337         free( file );
338         names++;
339     }
340     return xstrdup( name );
341 }
342
343 struct strarray *get_as_command(void)
344 {
345     struct strarray *args = strarray_init();
346
347     if (!as_command)
348     {
349         static const char * const commands[] = { "gas", "as", NULL };
350         as_command = find_tool( "as", commands );
351     }
352     strarray_add_one( args, as_command );
353
354     if (force_pointer_size)
355     {
356         switch (target_platform)
357         {
358         case PLATFORM_APPLE:
359             strarray_add( args, "-arch", (force_pointer_size == 8) ? "x86_64" : "i386", NULL );
360             break;
361         default:
362             strarray_add_one( args, (force_pointer_size == 8) ? "--64" : "--32" );
363             break;
364         }
365     }
366     return args;
367 }
368
369 struct strarray *get_ld_command(void)
370 {
371     struct strarray *args = strarray_init();
372
373     if (!ld_command)
374     {
375         static const char * const commands[] = { "ld", "gld", NULL };
376         ld_command = find_tool( "ld", commands );
377     }
378     strarray_add_one( args, ld_command );
379
380     if (force_pointer_size)
381     {
382         switch (target_platform)
383         {
384         case PLATFORM_APPLE:
385             strarray_add( args, "-arch", (force_pointer_size == 8) ? "x86_64" : "i386", NULL );
386             break;
387         case PLATFORM_FREEBSD:
388             strarray_add( args, "-m", (force_pointer_size == 8) ? "elf_x86_64_fbsd" : "elf_i386_fbsd", NULL );
389             break;
390         default:
391             strarray_add( args, "-m", (force_pointer_size == 8) ? "elf_x86_64" : "elf_i386", NULL );
392             break;
393         }
394     }
395     return args;
396 }
397
398 const char *get_nm_command(void)
399 {
400     if (!nm_command)
401     {
402         static const char * const commands[] = { "nm", "gnm", NULL };
403         nm_command = find_tool( "nm", commands );
404     }
405     return nm_command;
406 }
407
408 /* get a name for a temp file, automatically cleaned up on exit */
409 char *get_temp_file_name( const char *prefix, const char *suffix )
410 {
411     char *name;
412     const char *ext;
413     int fd;
414
415     if (!nb_tmp_files && !save_temps) atexit( cleanup_tmp_files );
416
417     if (!prefix || !prefix[0]) prefix = "winebuild";
418     if (!suffix) suffix = "";
419     if (!(ext = strchr( prefix, '.' ))) ext = prefix + strlen(prefix);
420     name = xmalloc( sizeof("/tmp/") + (ext - prefix) + sizeof(".XXXXXX") + strlen(suffix) );
421     strcpy( name, "/tmp/" );
422     memcpy( name + 5, prefix, ext - prefix );
423     strcpy( name + 5 + (ext - prefix), ".XXXXXX" );
424     strcat( name, suffix );
425
426     /* first try without the /tmp/ prefix */
427     if ((fd = mkstemps( name + 5, strlen(suffix) )) != -1)
428         name += 5;
429     else if ((fd = mkstemps( name, strlen(suffix) )) == -1)
430         fatal_error( "could not generate a temp file\n" );
431
432     close( fd );
433     if (nb_tmp_files >= max_tmp_files)
434     {
435         max_tmp_files = max( 2 * max_tmp_files, 8 );
436         tmp_files = xrealloc( tmp_files, max_tmp_files * sizeof(tmp_files[0]) );
437     }
438     tmp_files[nb_tmp_files++] = name;
439     return name;
440 }
441
442 /*******************************************************************
443  *         buffer management
444  *
445  * Function for reading from/writing to a memory buffer.
446  */
447
448 int byte_swapped = 0;
449 const char *input_buffer_filename;
450 const unsigned char *input_buffer;
451 size_t input_buffer_pos;
452 size_t input_buffer_size;
453 unsigned char *output_buffer;
454 size_t output_buffer_pos;
455 size_t output_buffer_size;
456
457 static void check_output_buffer_space( size_t size )
458 {
459     if (output_buffer_pos + size >= output_buffer_size)
460     {
461         output_buffer_size = max( output_buffer_size * 2, output_buffer_pos + size );
462         output_buffer = xrealloc( output_buffer, output_buffer_size );
463     }
464 }
465
466 void init_input_buffer( const char *file )
467 {
468     int fd;
469     struct stat st;
470
471     if ((fd = open( file, O_RDONLY | O_BINARY )) == -1) fatal_perror( "Cannot open %s", file );
472     if ((fstat( fd, &st ) == -1)) fatal_perror( "Cannot stat %s", file );
473     if (!st.st_size) fatal_error( "%s is an empty file\n", file );
474 #ifdef  HAVE_MMAP
475     if ((input_buffer = mmap( NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0 )) == (void*)-1)
476 #endif
477     {
478         unsigned char *buffer = xmalloc( st.st_size );
479         if (read( fd, buffer, st.st_size ) != st.st_size) fatal_error( "Cannot read %s\n", file );
480         input_buffer = buffer;
481     }
482     close( fd );
483     input_buffer_filename = xstrdup( file );
484     input_buffer_size = st.st_size;
485     input_buffer_pos = 0;
486     byte_swapped = 0;
487 }
488
489 void init_output_buffer(void)
490 {
491     output_buffer_size = 1024;
492     output_buffer_pos = 0;
493     output_buffer = xmalloc( output_buffer_size );
494 }
495
496 void flush_output_buffer(void)
497 {
498     if (fwrite( output_buffer, 1, output_buffer_pos, output_file ) != output_buffer_pos)
499         fatal_error( "Error writing to %s\n", output_file_name );
500     free( output_buffer );
501 }
502
503 unsigned char get_byte(void)
504 {
505     if (input_buffer_pos >= input_buffer_size)
506         fatal_error( "%s is a truncated file\n", input_buffer_filename );
507     return input_buffer[input_buffer_pos++];
508 }
509
510 unsigned short get_word(void)
511 {
512     unsigned short ret;
513
514     if (input_buffer_pos + sizeof(ret) > input_buffer_size)
515         fatal_error( "%s is a truncated file\n", input_buffer_filename );
516     memcpy( &ret, input_buffer + input_buffer_pos, sizeof(ret) );
517     if (byte_swapped) ret = (ret << 8) | (ret >> 8);
518     input_buffer_pos += sizeof(ret);
519     return ret;
520 }
521
522 unsigned int get_dword(void)
523 {
524     unsigned int ret;
525
526     if (input_buffer_pos + sizeof(ret) > input_buffer_size)
527         fatal_error( "%s is a truncated file\n", input_buffer_filename );
528     memcpy( &ret, input_buffer + input_buffer_pos, sizeof(ret) );
529     if (byte_swapped)
530         ret = ((ret << 24) | ((ret << 8) & 0x00ff0000) | ((ret >> 8) & 0x0000ff00) | (ret >> 24));
531     input_buffer_pos += sizeof(ret);
532     return ret;
533 }
534
535 void put_data( const void *data, size_t size )
536 {
537     check_output_buffer_space( size );
538     memcpy( output_buffer + output_buffer_pos, data, size );
539     output_buffer_pos += size;
540 }
541
542 void put_byte( unsigned char val )
543 {
544     check_output_buffer_space( 1 );
545     output_buffer[output_buffer_pos++] = val;
546 }
547
548 void put_word( unsigned short val )
549 {
550     if (byte_swapped) val = (val << 8) | (val >> 8);
551     put_data( &val, sizeof(val) );
552 }
553
554 void put_dword( unsigned int val )
555 {
556     if (byte_swapped)
557         val = ((val << 24) | ((val << 8) & 0x00ff0000) | ((val >> 8) & 0x0000ff00) | (val >> 24));
558     put_data( &val, sizeof(val) );
559 }
560
561 void put_qword( unsigned int val )
562 {
563     if (byte_swapped)
564     {
565         put_dword( 0 );
566         put_dword( val );
567     }
568     else
569     {
570         put_dword( val );
571         put_dword( 0 );
572     }
573 }
574
575 /* pointer-sized word */
576 void put_pword( unsigned int val )
577 {
578     if (get_ptr_size() == 8) put_qword( val );
579     else put_dword( val );
580 }
581
582 void align_output( unsigned int align )
583 {
584     size_t size = align - (output_buffer_pos % align);
585
586     if (size == align) return;
587     check_output_buffer_space( size );
588     memset( output_buffer + output_buffer_pos, 0, size );
589     output_buffer_pos += size;
590 }
591
592 /* output a standard header for generated files */
593 void output_standard_file_header(void)
594 {
595     if (spec_file_name)
596         output( "/* File generated automatically from %s; do not edit! */\n", spec_file_name );
597     else
598         output( "/* File generated automatically; do not edit! */\n" );
599     output( "/* This file can be copied, modified and distributed without restriction. */\n\n" );
600 }
601
602 /* dump a byte stream into the assembly code */
603 void dump_bytes( const void *buffer, unsigned int size )
604 {
605     unsigned int i;
606     const unsigned char *ptr = buffer;
607
608     if (!size) return;
609     output( "\t.byte " );
610     for (i = 0; i < size - 1; i++, ptr++)
611     {
612         if ((i % 16) == 15) output( "0x%02x\n\t.byte ", *ptr );
613         else output( "0x%02x,", *ptr );
614     }
615     output( "0x%02x\n", *ptr );
616 }
617
618
619 /*******************************************************************
620  *         open_input_file
621  *
622  * Open a file in the given srcdir and set the input_file_name global variable.
623  */
624 FILE *open_input_file( const char *srcdir, const char *name )
625 {
626     char *fullname;
627     FILE *file = fopen( name, "r" );
628
629     if (!file && srcdir)
630     {
631         fullname = strmake( "%s/%s", srcdir, name );
632         file = fopen( fullname, "r" );
633     }
634     else fullname = xstrdup( name );
635
636     if (!file) fatal_error( "Cannot open file '%s'\n", fullname );
637     input_file_name = fullname;
638     current_line = 1;
639     return file;
640 }
641
642
643 /*******************************************************************
644  *         close_input_file
645  *
646  * Close the current input file (must have been opened with open_input_file).
647  */
648 void close_input_file( FILE *file )
649 {
650     fclose( file );
651     free( input_file_name );
652     input_file_name = NULL;
653     current_line = 0;
654 }
655
656
657 /*******************************************************************
658  *         remove_stdcall_decoration
659  *
660  * Remove a possible @xx suffix from a function name.
661  * Return the numerical value of the suffix, or -1 if none.
662  */
663 int remove_stdcall_decoration( char *name )
664 {
665     char *p, *end = strrchr( name, '@' );
666     if (!end || !end[1] || end == name) return -1;
667     if (target_cpu != CPU_x86) return -1;
668     /* make sure all the rest is digits */
669     for (p = end + 1; *p; p++) if (!isdigit(*p)) return -1;
670     *end = 0;
671     return atoi( end + 1 );
672 }
673
674
675 /*******************************************************************
676  *         assemble_file
677  *
678  * Run a file through the assembler.
679  */
680 void assemble_file( const char *src_file, const char *obj_file )
681 {
682     struct strarray *args = get_as_command();
683     strarray_add( args, "-o", obj_file, src_file, NULL );
684     spawn( args );
685     strarray_free( args );
686 }
687
688
689 /*******************************************************************
690  *         alloc_dll_spec
691  *
692  * Create a new dll spec file descriptor
693  */
694 DLLSPEC *alloc_dll_spec(void)
695 {
696     DLLSPEC *spec;
697
698     spec = xmalloc( sizeof(*spec) );
699     spec->file_name          = NULL;
700     spec->dll_name           = NULL;
701     spec->init_func          = NULL;
702     spec->main_module        = NULL;
703     spec->type               = SPEC_WIN32;
704     spec->base               = MAX_ORDINALS;
705     spec->limit              = 0;
706     spec->stack_size         = 0;
707     spec->heap_size          = 0;
708     spec->nb_entry_points    = 0;
709     spec->alloc_entry_points = 0;
710     spec->nb_names           = 0;
711     spec->nb_resources       = 0;
712     spec->characteristics    = IMAGE_FILE_EXECUTABLE_IMAGE;
713     if (get_ptr_size() > 4)
714         spec->characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
715     else
716         spec->characteristics |= IMAGE_FILE_32BIT_MACHINE;
717     spec->dll_characteristics = IMAGE_DLLCHARACTERISTICS_NX_COMPAT;
718     spec->subsystem          = 0;
719     spec->subsystem_major    = 4;
720     spec->subsystem_minor    = 0;
721     spec->entry_points       = NULL;
722     spec->names              = NULL;
723     spec->ordinals           = NULL;
724     spec->resources          = NULL;
725     return spec;
726 }
727
728
729 /*******************************************************************
730  *         free_dll_spec
731  *
732  * Free dll spec file descriptor
733  */
734 void free_dll_spec( DLLSPEC *spec )
735 {
736     int i;
737
738     for (i = 0; i < spec->nb_entry_points; i++)
739     {
740         ORDDEF *odp = &spec->entry_points[i];
741         free( odp->name );
742         free( odp->export_name );
743         free( odp->link_name );
744     }
745     free( spec->file_name );
746     free( spec->dll_name );
747     free( spec->init_func );
748     free( spec->entry_points );
749     free( spec->names );
750     free( spec->ordinals );
751     free( spec->resources );
752     free( spec );
753 }
754
755
756 /*******************************************************************
757  *         make_c_identifier
758  *
759  * Map a string to a valid C identifier.
760  */
761 const char *make_c_identifier( const char *str )
762 {
763     static char buffer[256];
764     char *p;
765
766     for (p = buffer; *str && p < buffer+sizeof(buffer)-1; p++, str++)
767     {
768         if (isalnum(*str)) *p = *str;
769         else *p = '_';
770     }
771     *p = 0;
772     return buffer;
773 }
774
775
776 /*******************************************************************
777  *         get_stub_name
778  *
779  * Generate an internal name for a stub entry point.
780  */
781 const char *get_stub_name( const ORDDEF *odp, const DLLSPEC *spec )
782 {
783     static char *buffer;
784
785     free( buffer );
786     if (odp->name || odp->export_name)
787     {
788         char *p;
789         buffer = strmake( "__wine_stub_%s", odp->name ? odp->name : odp->export_name );
790         /* make sure name is a legal C identifier */
791         for (p = buffer; *p; p++) if (!isalnum(*p) && *p != '_') break;
792         if (!*p) return buffer;
793         free( buffer );
794     }
795     buffer = strmake( "__wine_stub_%s_%d", make_c_identifier(spec->file_name), odp->ordinal );
796     return buffer;
797 }
798
799 /* parse a cpu name and return the corresponding value */
800 enum target_cpu get_cpu_from_name( const char *name )
801 {
802     unsigned int i;
803
804     for (i = 0; i < sizeof(cpu_names)/sizeof(cpu_names[0]); i++)
805         if (!strcmp( cpu_names[i].name, name )) return cpu_names[i].cpu;
806     return -1;
807 }
808
809 /*****************************************************************
810  *  Function:    get_alignment
811  *
812  *  Description:
813  *    According to the info page for gas, the .align directive behaves
814  * differently on different systems.  On some architectures, the
815  * argument of a .align directive is the number of bytes to pad to, so
816  * to align on an 8-byte boundary you'd say
817  *     .align 8
818  * On other systems, the argument is "the number of low-order zero bits
819  * that the location counter must have after advancement."  So to
820  * align on an 8-byte boundary you'd say
821  *     .align 3
822  *
823  * The reason gas is written this way is that it's trying to mimick
824  * native assemblers for the various architectures it runs on.  gas
825  * provides other directives that work consistently across
826  * architectures, but of course we want to work on all arches with or
827  * without gas.  Hence this function.
828  *
829  *
830  *  Parameters:
831  *    align  --  the number of bytes to align to. Must be a power of 2.
832  */
833 unsigned int get_alignment(unsigned int align)
834 {
835     unsigned int n;
836
837     assert( !(align & (align - 1)) );
838
839     switch(target_cpu)
840     {
841     case CPU_x86:
842     case CPU_x86_64:
843     case CPU_SPARC:
844         if (target_platform != PLATFORM_APPLE) return align;
845         /* fall through */
846     case CPU_POWERPC:
847     case CPU_ALPHA:
848     case CPU_ARM:
849         n = 0;
850         while ((1u << n) != align) n++;
851         return n;
852     }
853     /* unreached */
854     assert(0);
855     return 0;
856 }
857
858 /* return the page size for the target CPU */
859 unsigned int get_page_size(void)
860 {
861     switch(target_cpu)
862     {
863     case CPU_x86:     return 4096;
864     case CPU_x86_64:  return 4096;
865     case CPU_POWERPC: return 4096;
866     case CPU_ARM:     return 4096;
867     case CPU_SPARC:   return 8192;
868     case CPU_ALPHA:   return 8192;
869     }
870     /* unreached */
871     assert(0);
872     return 0;
873 }
874
875 /* return the size of a pointer on the target CPU */
876 unsigned int get_ptr_size(void)
877 {
878     switch(target_cpu)
879     {
880     case CPU_x86:
881     case CPU_POWERPC:
882     case CPU_SPARC:
883     case CPU_ALPHA:
884     case CPU_ARM:
885         return 4;
886     case CPU_x86_64:
887         return 8;
888     }
889     /* unreached */
890     assert(0);
891     return 0;
892 }
893
894 /* return the total size in bytes of the arguments on the stack */
895 unsigned int get_args_size( const ORDDEF *odp )
896 {
897     unsigned int i, size;
898
899     for (i = size = 0; i < odp->u.func.nb_args; i++)
900     {
901         switch (odp->u.func.args[i])
902         {
903         case ARG_INT64:
904         case ARG_DOUBLE:
905             size += 8;
906             break;
907         case ARG_INT128:
908             /* int128 is passed as pointer on x86_64 */
909             if (target_cpu != CPU_x86_64)
910             {
911                 size += 16;
912                 break;
913             }
914             /* fall through */
915         default:
916             size += get_ptr_size();
917             break;
918         }
919     }
920     return size;
921 }
922
923 /* return the assembly name for a C symbol */
924 const char *asm_name( const char *sym )
925 {
926     static char *buffer;
927
928     switch (target_platform)
929     {
930     case PLATFORM_APPLE:
931     case PLATFORM_WINDOWS:
932         if (sym[0] == '.' && sym[1] == 'L') return sym;
933         free( buffer );
934         buffer = strmake( "_%s", sym );
935         return buffer;
936     default:
937         return sym;
938     }
939 }
940
941 /* return an assembly function declaration for a C function name */
942 const char *func_declaration( const char *func )
943 {
944     static char *buffer;
945
946     switch (target_platform)
947     {
948     case PLATFORM_APPLE:
949         return "";
950     case PLATFORM_WINDOWS:
951         free( buffer );
952         buffer = strmake( ".def _%s; .scl 2; .type 32; .endef", func );
953         break;
954     default:
955         free( buffer );
956         switch(target_cpu)
957         {
958         case CPU_ARM:
959             buffer = strmake( ".type %s,%%function", func );
960             break;
961         default:
962             buffer = strmake( ".type %s,@function", func );
963             break;
964         }
965         break;
966     }
967     return buffer;
968 }
969
970 /* output a size declaration for an assembly function */
971 void output_function_size( const char *name )
972 {
973     switch (target_platform)
974     {
975     case PLATFORM_APPLE:
976     case PLATFORM_WINDOWS:
977         break;
978     default:
979         output( "\t.size %s, .-%s\n", name, name );
980         break;
981     }
982 }
983
984 /* output a .cfi directive */
985 void output_cfi( const char *format, ... )
986 {
987     va_list valist;
988
989     if (!unwind_tables) return;
990     va_start( valist, format );
991     fputc( '\t', output_file );
992     vfprintf( output_file, format, valist );
993     fputc( '\n', output_file );
994     va_end( valist );
995 }
996
997 /* output the GNU note for non-exec stack */
998 void output_gnu_stack_note(void)
999 {
1000     switch (target_platform)
1001     {
1002     case PLATFORM_WINDOWS:
1003     case PLATFORM_APPLE:
1004         break;
1005     default:
1006         switch(target_cpu)
1007         {
1008         case CPU_ARM:
1009             output( "\t.section .note.GNU-stack,\"\",%%progbits\n" );
1010             break;
1011         default:
1012             output( "\t.section .note.GNU-stack,\"\",@progbits\n" );
1013             break;
1014         }
1015         break;
1016     }
1017 }
1018
1019 /* return a global symbol declaration for an assembly symbol */
1020 const char *asm_globl( const char *func )
1021 {
1022     static char *buffer;
1023
1024     free( buffer );
1025     switch (target_platform)
1026     {
1027     case PLATFORM_APPLE:
1028         buffer = strmake( "\t.globl _%s\n\t.private_extern _%s\n_%s:", func, func, func );
1029         break;
1030     case PLATFORM_WINDOWS:
1031         buffer = strmake( "\t.globl _%s\n_%s:", func, func );
1032         break;
1033     default:
1034         buffer = strmake( "\t.globl %s\n\t.hidden %s\n%s:", func, func, func );
1035         break;
1036     }
1037     return buffer;
1038 }
1039
1040 const char *get_asm_ptr_keyword(void)
1041 {
1042     switch(get_ptr_size())
1043     {
1044     case 4: return ".long";
1045     case 8: return ".quad";
1046     }
1047     assert(0);
1048     return NULL;
1049 }
1050
1051 const char *get_asm_string_keyword(void)
1052 {
1053     switch (target_platform)
1054     {
1055     case PLATFORM_APPLE:
1056         return ".asciz";
1057     default:
1058         return ".string";
1059     }
1060 }
1061
1062 const char *get_asm_short_keyword(void)
1063 {
1064     switch (target_platform)
1065     {
1066     default:            return ".short";
1067     }
1068 }
1069
1070 const char *get_asm_rodata_section(void)
1071 {
1072     switch (target_platform)
1073     {
1074     case PLATFORM_APPLE: return ".const";
1075     default:             return ".section .rodata";
1076     }
1077 }
1078
1079 const char *get_asm_string_section(void)
1080 {
1081     switch (target_platform)
1082     {
1083     case PLATFORM_APPLE: return ".cstring";
1084     default:             return ".section .rodata";
1085     }
1086 }