winebuild: Determine the appropriate as/ld/nm commands at the time they are needed.
[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
34 #include "windef.h"
35 #include "winnt.h"
36 #include "build.h"
37
38 #define MAX_TMP_FILES 8
39 static const char *tmp_files[MAX_TMP_FILES];
40 static unsigned int nb_tmp_files;
41
42 static const struct
43 {
44     const char *name;
45     enum target_cpu cpu;
46 } cpu_names[] =
47 {
48     { "i386",    CPU_x86 },
49     { "i486",    CPU_x86 },
50     { "i586",    CPU_x86 },
51     { "i686",    CPU_x86 },
52     { "i786",    CPU_x86 },
53     { "x86_64",  CPU_x86_64 },
54     { "sparc",   CPU_SPARC },
55     { "alpha",   CPU_ALPHA },
56     { "powerpc", CPU_POWERPC }
57 };
58
59 /* atexit handler to clean tmp files */
60 static void cleanup_tmp_files(void)
61 {
62     unsigned int i;
63     for (i = 0; i < MAX_TMP_FILES; i++) if (tmp_files[i]) unlink( tmp_files[i] );
64 }
65
66
67 void *xmalloc (size_t size)
68 {
69     void *res;
70
71     res = malloc (size ? size : 1);
72     if (res == NULL)
73     {
74         fprintf (stderr, "Virtual memory exhausted.\n");
75         exit (1);
76     }
77     return res;
78 }
79
80 void *xrealloc (void *ptr, size_t size)
81 {
82     void *res = realloc (ptr, size);
83     if (size && res == NULL)
84     {
85         fprintf (stderr, "Virtual memory exhausted.\n");
86         exit (1);
87     }
88     return res;
89 }
90
91 char *xstrdup( const char *str )
92 {
93     char *res = strdup( str );
94     if (!res)
95     {
96         fprintf (stderr, "Virtual memory exhausted.\n");
97         exit (1);
98     }
99     return res;
100 }
101
102 char *strupper(char *s)
103 {
104     char *p;
105     for (p = s; *p; p++) *p = toupper(*p);
106     return s;
107 }
108
109 int strendswith(const char* str, const char* end)
110 {
111     int l = strlen(str);
112     int m = strlen(end);
113     return l >= m && strcmp(str + l - m, end) == 0;
114 }
115
116 void fatal_error( const char *msg, ... )
117 {
118     va_list valist;
119     va_start( valist, msg );
120     if (input_file_name)
121     {
122         fprintf( stderr, "%s:", input_file_name );
123         if (current_line)
124             fprintf( stderr, "%d:", current_line );
125         fputc( ' ', stderr );
126     }
127     else fprintf( stderr, "winebuild: " );
128     vfprintf( stderr, msg, valist );
129     va_end( valist );
130     exit(1);
131 }
132
133 void fatal_perror( const char *msg, ... )
134 {
135     va_list valist;
136     va_start( valist, msg );
137     if (input_file_name)
138     {
139         fprintf( stderr, "%s:", input_file_name );
140         if (current_line)
141             fprintf( stderr, "%d:", current_line );
142         fputc( ' ', stderr );
143     }
144     vfprintf( stderr, msg, valist );
145     perror( " " );
146     va_end( valist );
147     exit(1);
148 }
149
150 void error( const char *msg, ... )
151 {
152     va_list valist;
153     va_start( valist, msg );
154     if (input_file_name)
155     {
156         fprintf( stderr, "%s:", input_file_name );
157         if (current_line)
158             fprintf( stderr, "%d:", current_line );
159         fputc( ' ', stderr );
160     }
161     vfprintf( stderr, msg, valist );
162     va_end( valist );
163     nb_errors++;
164 }
165
166 void warning( const char *msg, ... )
167 {
168     va_list valist;
169
170     if (!display_warnings) return;
171     va_start( valist, msg );
172     if (input_file_name)
173     {
174         fprintf( stderr, "%s:", input_file_name );
175         if (current_line)
176             fprintf( stderr, "%d:", current_line );
177         fputc( ' ', stderr );
178     }
179     fprintf( stderr, "warning: " );
180     vfprintf( stderr, msg, valist );
181     va_end( valist );
182 }
183
184 int output( const char *format, ... )
185 {
186     int ret;
187     va_list valist;
188
189     va_start( valist, format );
190     ret = vfprintf( output_file, format, valist );
191     va_end( valist );
192     if (ret < 0) fatal_perror( "Output error" );
193     return ret;
194 }
195
196 const char *get_as_command(void)
197 {
198     if (!as_command)
199     {
200         if (target_alias)
201         {
202             as_command = xmalloc( strlen(target_alias) + sizeof("-as") );
203             strcpy( as_command, target_alias );
204             strcat( as_command, "-as" );
205         }
206         else
207         {
208             as_command = xstrdup( "as" );
209         }
210     }
211     return as_command;
212 }
213
214 const char *get_ld_command(void)
215 {
216     if (!ld_command)
217     {
218         if (target_alias)
219         {
220             ld_command = xmalloc( strlen(target_alias) + sizeof("-ld") );
221             strcpy( ld_command, target_alias );
222             strcat( ld_command, "-ld" );
223         }
224         else
225         {
226             ld_command = xstrdup( "ld" );
227         }
228     }
229     return ld_command;
230 }
231
232 const char *get_nm_command(void)
233 {
234     if (!nm_command)
235     {
236         if (target_alias)
237         {
238             nm_command = xmalloc( strlen(target_alias) + sizeof("-nm") );
239             strcpy( nm_command, target_alias );
240             strcat( nm_command, "-nm" );
241         }
242         else
243         {
244             nm_command = xstrdup( "nm" );
245         }
246     }
247     return nm_command;
248 }
249
250 /* get a name for a temp file, automatically cleaned up on exit */
251 char *get_temp_file_name( const char *prefix, const char *suffix )
252 {
253     char *name;
254     const char *ext;
255     int fd;
256
257     assert( nb_tmp_files < MAX_TMP_FILES );
258     if (!nb_tmp_files && !save_temps) atexit( cleanup_tmp_files );
259
260     if (!prefix || !prefix[0]) prefix = "winebuild";
261     if (!suffix) suffix = "";
262     if (!(ext = strchr( prefix, '.' ))) ext = prefix + strlen(prefix);
263     name = xmalloc( sizeof("/tmp/") + (ext - prefix) + sizeof(".XXXXXX") + strlen(suffix) );
264     strcpy( name, "/tmp/" );
265     memcpy( name + 5, prefix, ext - prefix );
266     strcpy( name + 5 + (ext - prefix), ".XXXXXX" );
267     strcat( name, suffix );
268
269     /* first try without the /tmp/ prefix */
270     if ((fd = mkstemps( name + 5, strlen(suffix) )) != -1)
271         name += 5;
272     else if ((fd = mkstemps( name, strlen(suffix) )) == -1)
273         fatal_error( "could not generate a temp file\n" );
274
275     close( fd );
276     tmp_files[nb_tmp_files++] = name;
277     return name;
278 }
279
280 /* output a standard header for generated files */
281 void output_standard_file_header(void)
282 {
283     if (spec_file_name)
284         output( "/* File generated automatically from %s; do not edit! */\n", spec_file_name );
285     else
286         output( "/* File generated automatically; do not edit! */\n" );
287     output( "/* This file can be copied, modified and distributed without restriction. */\n\n" );
288 }
289
290 /* dump a byte stream into the assembly code */
291 void dump_bytes( const void *buffer, unsigned int size )
292 {
293     unsigned int i;
294     const unsigned char *ptr = buffer;
295
296     if (!size) return;
297     output( "\t.byte " );
298     for (i = 0; i < size - 1; i++, ptr++)
299     {
300         if ((i % 16) == 15) output( "0x%02x\n\t.byte ", *ptr );
301         else output( "0x%02x,", *ptr );
302     }
303     output( "0x%02x\n", *ptr );
304 }
305
306
307 /*******************************************************************
308  *         open_input_file
309  *
310  * Open a file in the given srcdir and set the input_file_name global variable.
311  */
312 FILE *open_input_file( const char *srcdir, const char *name )
313 {
314     char *fullname;
315     FILE *file = fopen( name, "r" );
316
317     if (!file && srcdir)
318     {
319         fullname = xmalloc( strlen(srcdir) + strlen(name) + 2 );
320         strcpy( fullname, srcdir );
321         strcat( fullname, "/" );
322         strcat( fullname, name );
323         file = fopen( fullname, "r" );
324     }
325     else fullname = xstrdup( name );
326
327     if (!file) fatal_error( "Cannot open file '%s'\n", fullname );
328     input_file_name = fullname;
329     current_line = 1;
330     return file;
331 }
332
333
334 /*******************************************************************
335  *         close_input_file
336  *
337  * Close the current input file (must have been opened with open_input_file).
338  */
339 void close_input_file( FILE *file )
340 {
341     fclose( file );
342     free( input_file_name );
343     input_file_name = NULL;
344     current_line = 0;
345 }
346
347
348 /*******************************************************************
349  *         remove_stdcall_decoration
350  *
351  * Remove a possible @xx suffix from a function name.
352  * Return the numerical value of the suffix, or -1 if none.
353  */
354 int remove_stdcall_decoration( char *name )
355 {
356     char *p, *end = strrchr( name, '@' );
357     if (!end || !end[1] || end == name) return -1;
358     /* make sure all the rest is digits */
359     for (p = end + 1; *p; p++) if (!isdigit(*p)) return -1;
360     *end = 0;
361     return atoi( end + 1 );
362 }
363
364
365 /*******************************************************************
366  *         assemble_file
367  *
368  * Run a file through the assembler.
369  */
370 void assemble_file( const char *src_file, const char *obj_file )
371 {
372     const char *prog = get_as_command();
373     char *cmd;
374     int err;
375
376     cmd = xmalloc( strlen(prog) + strlen(obj_file) + strlen(src_file) + 6 );
377     sprintf( cmd, "%s -o %s %s", prog, obj_file, src_file );
378     if (verbose) fprintf( stderr, "%s\n", cmd );
379     err = system( cmd );
380     if (err) fatal_error( "%s failed with status %d\n", prog, err );
381     free( cmd );
382 }
383
384
385 /*******************************************************************
386  *         alloc_dll_spec
387  *
388  * Create a new dll spec file descriptor
389  */
390 DLLSPEC *alloc_dll_spec(void)
391 {
392     DLLSPEC *spec;
393
394     spec = xmalloc( sizeof(*spec) );
395     spec->file_name          = NULL;
396     spec->dll_name           = NULL;
397     spec->init_func          = NULL;
398     spec->type               = SPEC_WIN32;
399     spec->base               = MAX_ORDINALS;
400     spec->limit              = 0;
401     spec->stack_size         = 0;
402     spec->heap_size          = 0;
403     spec->nb_entry_points    = 0;
404     spec->alloc_entry_points = 0;
405     spec->nb_names           = 0;
406     spec->nb_resources       = 0;
407     spec->characteristics    = IMAGE_FILE_EXECUTABLE_IMAGE;
408     if (get_ptr_size() > 4)
409         spec->characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
410     else
411         spec->characteristics |= IMAGE_FILE_32BIT_MACHINE;
412     spec->dll_characteristics = IMAGE_DLLCHARACTERISTICS_NX_COMPAT;
413     spec->subsystem          = 0;
414     spec->subsystem_major    = 4;
415     spec->subsystem_minor    = 0;
416     spec->entry_points       = NULL;
417     spec->names              = NULL;
418     spec->ordinals           = NULL;
419     spec->resources          = NULL;
420     return spec;
421 }
422
423
424 /*******************************************************************
425  *         free_dll_spec
426  *
427  * Free dll spec file descriptor
428  */
429 void free_dll_spec( DLLSPEC *spec )
430 {
431     int i;
432
433     for (i = 0; i < spec->nb_entry_points; i++)
434     {
435         ORDDEF *odp = &spec->entry_points[i];
436         free( odp->name );
437         free( odp->export_name );
438         free( odp->link_name );
439     }
440     free( spec->file_name );
441     free( spec->dll_name );
442     free( spec->init_func );
443     free( spec->entry_points );
444     free( spec->names );
445     free( spec->ordinals );
446     free( spec->resources );
447     free( spec );
448 }
449
450
451 /*******************************************************************
452  *         make_c_identifier
453  *
454  * Map a string to a valid C identifier.
455  */
456 const char *make_c_identifier( const char *str )
457 {
458     static char buffer[256];
459     char *p;
460
461     for (p = buffer; *str && p < buffer+sizeof(buffer)-1; p++, str++)
462     {
463         if (isalnum(*str)) *p = *str;
464         else *p = '_';
465     }
466     *p = 0;
467     return buffer;
468 }
469
470
471 /*******************************************************************
472  *         get_stub_name
473  *
474  * Generate an internal name for a stub entry point.
475  */
476 const char *get_stub_name( const ORDDEF *odp, const DLLSPEC *spec )
477 {
478     static char buffer[256];
479     if (odp->name || odp->export_name)
480     {
481         char *p;
482         sprintf( buffer, "__wine_stub_%s", odp->name ? odp->name : odp->export_name );
483         /* make sure name is a legal C identifier */
484         for (p = buffer; *p; p++) if (!isalnum(*p) && *p != '_') break;
485         if (!*p) return buffer;
486     }
487     sprintf( buffer, "__wine_stub_%s_%d", make_c_identifier(spec->file_name), odp->ordinal );
488     return buffer;
489 }
490
491 /* parse a cpu name and return the corresponding value */
492 enum target_cpu get_cpu_from_name( const char *name )
493 {
494     unsigned int i;
495
496     for (i = 0; i < sizeof(cpu_names)/sizeof(cpu_names[0]); i++)
497         if (!strcmp( cpu_names[i].name, name )) return cpu_names[i].cpu;
498     return -1;
499 }
500
501 /*****************************************************************
502  *  Function:    get_alignment
503  *
504  *  Description:
505  *    According to the info page for gas, the .align directive behaves
506  * differently on different systems.  On some architectures, the
507  * argument of a .align directive is the number of bytes to pad to, so
508  * to align on an 8-byte boundary you'd say
509  *     .align 8
510  * On other systems, the argument is "the number of low-order zero bits
511  * that the location counter must have after advancement."  So to
512  * align on an 8-byte boundary you'd say
513  *     .align 3
514  *
515  * The reason gas is written this way is that it's trying to mimick
516  * native assemblers for the various architectures it runs on.  gas
517  * provides other directives that work consistently across
518  * architectures, but of course we want to work on all arches with or
519  * without gas.  Hence this function.
520  *
521  *
522  *  Parameters:
523  *    align  --  the number of bytes to align to. Must be a power of 2.
524  */
525 unsigned int get_alignment(unsigned int align)
526 {
527     unsigned int n;
528
529     assert( !(align & (align - 1)) );
530
531     switch(target_cpu)
532     {
533     case CPU_x86:
534     case CPU_x86_64:
535     case CPU_SPARC:
536         if (target_platform != PLATFORM_APPLE) return align;
537         /* fall through */
538     case CPU_POWERPC:
539     case CPU_ALPHA:
540         n = 0;
541         while ((1u << n) != align) n++;
542         return n;
543     }
544     /* unreached */
545     assert(0);
546     return 0;
547 }
548
549 /* return the page size for the target CPU */
550 unsigned int get_page_size(void)
551 {
552     switch(target_cpu)
553     {
554     case CPU_x86:     return 4096;
555     case CPU_x86_64:  return 4096;
556     case CPU_POWERPC: return 4096;
557     case CPU_SPARC:   return 8192;
558     case CPU_ALPHA:   return 8192;
559     }
560     /* unreached */
561     assert(0);
562     return 0;
563 }
564
565 /* return the size of a pointer on the target CPU */
566 unsigned int get_ptr_size(void)
567 {
568     switch(target_cpu)
569     {
570     case CPU_x86:
571     case CPU_POWERPC:
572     case CPU_SPARC:
573     case CPU_ALPHA:
574         return 4;
575     case CPU_x86_64:
576         return 8;
577     }
578     /* unreached */
579     assert(0);
580     return 0;
581 }
582
583 /* return the assembly name for a C symbol */
584 const char *asm_name( const char *sym )
585 {
586     static char buffer[256];
587
588     switch (target_platform)
589     {
590     case PLATFORM_APPLE:
591     case PLATFORM_WINDOWS:
592         buffer[0] = '_';
593         strcpy( buffer + 1, sym );
594         return buffer;
595     default:
596         return sym;
597     }
598 }
599
600 /* return an assembly function declaration for a C function name */
601 const char *func_declaration( const char *func )
602 {
603     static char buffer[256];
604
605     switch (target_platform)
606     {
607     case PLATFORM_APPLE:
608         return "";
609     case PLATFORM_WINDOWS:
610         sprintf( buffer, ".def _%s; .scl 2; .type 32; .endef", func );
611         break;
612     default:
613         sprintf( buffer, ".type %s,@function", func );
614         break;
615     }
616     return buffer;
617 }
618
619 /* output a size declaration for an assembly function */
620 void output_function_size( const char *name )
621 {
622     switch (target_platform)
623     {
624     case PLATFORM_APPLE:
625     case PLATFORM_WINDOWS:
626         break;
627     default:
628         output( "\t.size %s, .-%s\n", name, name );
629         break;
630     }
631 }
632
633 /* output the GNU note for non-exec stack */
634 void output_gnu_stack_note(void)
635 {
636     switch (target_platform)
637     {
638     case PLATFORM_WINDOWS:
639     case PLATFORM_APPLE:
640         break;
641     default:
642         output( "\t.section .note.GNU-stack,\"\",@progbits\n" );
643         break;
644     }
645 }
646
647 /* return a global symbol declaration for an assembly symbol */
648 const char *asm_globl( const char *func )
649 {
650     static char buffer[256];
651
652     switch (target_platform)
653     {
654     case PLATFORM_APPLE:
655         sprintf( buffer, "\t.globl _%s\n\t.private_extern _%s\n_%s:", func, func, func );
656         return buffer;
657     case PLATFORM_WINDOWS:
658         sprintf( buffer, "\t.globl _%s\n_%s:", func, func );
659         return buffer;
660     default:
661         sprintf( buffer, "\t.globl %s\n\t.hidden %s\n%s:", func, func, func );
662         return buffer;
663     }
664 }
665
666 const char *get_asm_ptr_keyword(void)
667 {
668     switch(get_ptr_size())
669     {
670     case 4: return ".long";
671     case 8: return ".quad";
672     }
673     assert(0);
674     return NULL;
675 }
676
677 const char *get_asm_string_keyword(void)
678 {
679     switch (target_platform)
680     {
681     case PLATFORM_APPLE:
682         return ".asciz";
683     default:
684         return ".string";
685     }
686 }
687
688 const char *get_asm_short_keyword(void)
689 {
690     switch (target_platform)
691     {
692     default:            return ".short";
693     }
694 }
695
696 const char *get_asm_rodata_section(void)
697 {
698     switch (target_platform)
699     {
700     case PLATFORM_APPLE: return ".const";
701     default:             return ".section .rodata";
702     }
703 }
704
705 const char *get_asm_string_section(void)
706 {
707     switch (target_platform)
708     {
709     case PLATFORM_APPLE: return ".cstring";
710     default:             return ".section .rodata";
711     }
712 }