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