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