user32/tests: Fix some window test failures on various Windows platforms.
[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 /* find a build tool in the path, trying the various names */
197 char *find_tool( const char * const *names )
198 {
199     static char **dirs;
200     static unsigned int count, maxlen;
201
202     char *p, *file;
203     unsigned int i, len;
204     struct stat st;
205
206     if (!dirs)
207     {
208         char *path;
209
210         /* split the path in directories */
211
212         if (!getenv( "PATH" )) return NULL;
213         path = xstrdup( getenv( "PATH" ));
214         for (p = path, count = 2; *p; p++) if (*p == ':') count++;
215         dirs = xmalloc( count * sizeof(*dirs) );
216         count = 0;
217         dirs[count++] = p = path;
218         while (*p)
219         {
220             while (*p && *p != ':') p++;
221             if (!*p) break;
222             *p++ = 0;
223             dirs[count++] = p;
224         }
225         for (i = 0; i < count; i++) maxlen = max( maxlen, strlen(dirs[i])+2 );
226     }
227
228     while (*names)
229     {
230         len = strlen(*names) + 1;
231         file = xmalloc( maxlen + len );
232
233         for (i = 0; i < count; i++)
234         {
235             strcpy( file, dirs[i] );
236             p = file + strlen(file);
237             if (p == file) *p++ = '.';
238             if (p[-1] != '/') *p++ = '/';
239             strcpy( p, *names );
240
241             if (!stat( file, &st ) && S_ISREG(st.st_mode) && (st.st_mode & 0111)) return file;
242         }
243         free( file );
244         names++;
245     }
246     return NULL;
247 }
248
249 const char *get_as_command(void)
250 {
251     if (!as_command)
252     {
253         if (target_alias)
254         {
255             as_command = xmalloc( strlen(target_alias) + sizeof("-as") );
256             strcpy( as_command, target_alias );
257             strcat( as_command, "-as" );
258         }
259         else
260         {
261             static const char * const commands[] = { "gas", "as", NULL };
262             if (!(as_command = find_tool( commands ))) as_command = xstrdup("as");
263         }
264
265         if (force_pointer_size)
266         {
267             const char *args = (force_pointer_size == 8) ? " --64" : " --32";
268             as_command = xrealloc( as_command, strlen(as_command) + strlen(args) + 1 );
269             strcat( as_command, args );
270         }
271     }
272     return as_command;
273 }
274
275 const char *get_ld_command(void)
276 {
277     if (!ld_command)
278     {
279         if (target_alias)
280         {
281             ld_command = xmalloc( strlen(target_alias) + sizeof("-ld") );
282             strcpy( ld_command, target_alias );
283             strcat( ld_command, "-ld" );
284         }
285         else
286         {
287             static const char * const commands[] = { "ld", "gld", NULL };
288             if (!(ld_command = find_tool( commands ))) ld_command = xstrdup("ld");
289         }
290
291         if (force_pointer_size)
292         {
293             const char *args = (force_pointer_size == 8) ? " -m elf_x86_64" : " -m elf_i386";
294             ld_command = xrealloc( ld_command, strlen(ld_command) + strlen(args) + 1 );
295             strcat( ld_command, args );
296         }
297     }
298     return ld_command;
299 }
300
301 const char *get_nm_command(void)
302 {
303     if (!nm_command)
304     {
305         if (target_alias)
306         {
307             nm_command = xmalloc( strlen(target_alias) + sizeof("-nm") );
308             strcpy( nm_command, target_alias );
309             strcat( nm_command, "-nm" );
310         }
311         else
312         {
313             static const char * const commands[] = { "nm", "gnm", NULL };
314             if (!(nm_command = find_tool( commands ))) nm_command = xstrdup("nm");
315         }
316     }
317     return nm_command;
318 }
319
320 /* get a name for a temp file, automatically cleaned up on exit */
321 char *get_temp_file_name( const char *prefix, const char *suffix )
322 {
323     char *name;
324     const char *ext;
325     int fd;
326
327     assert( nb_tmp_files < MAX_TMP_FILES );
328     if (!nb_tmp_files && !save_temps) atexit( cleanup_tmp_files );
329
330     if (!prefix || !prefix[0]) prefix = "winebuild";
331     if (!suffix) suffix = "";
332     if (!(ext = strchr( prefix, '.' ))) ext = prefix + strlen(prefix);
333     name = xmalloc( sizeof("/tmp/") + (ext - prefix) + sizeof(".XXXXXX") + strlen(suffix) );
334     strcpy( name, "/tmp/" );
335     memcpy( name + 5, prefix, ext - prefix );
336     strcpy( name + 5 + (ext - prefix), ".XXXXXX" );
337     strcat( name, suffix );
338
339     /* first try without the /tmp/ prefix */
340     if ((fd = mkstemps( name + 5, strlen(suffix) )) != -1)
341         name += 5;
342     else if ((fd = mkstemps( name, strlen(suffix) )) == -1)
343         fatal_error( "could not generate a temp file\n" );
344
345     close( fd );
346     tmp_files[nb_tmp_files++] = name;
347     return name;
348 }
349
350 /* output a standard header for generated files */
351 void output_standard_file_header(void)
352 {
353     if (spec_file_name)
354         output( "/* File generated automatically from %s; do not edit! */\n", spec_file_name );
355     else
356         output( "/* File generated automatically; do not edit! */\n" );
357     output( "/* This file can be copied, modified and distributed without restriction. */\n\n" );
358 }
359
360 /* dump a byte stream into the assembly code */
361 void dump_bytes( const void *buffer, unsigned int size )
362 {
363     unsigned int i;
364     const unsigned char *ptr = buffer;
365
366     if (!size) return;
367     output( "\t.byte " );
368     for (i = 0; i < size - 1; i++, ptr++)
369     {
370         if ((i % 16) == 15) output( "0x%02x\n\t.byte ", *ptr );
371         else output( "0x%02x,", *ptr );
372     }
373     output( "0x%02x\n", *ptr );
374 }
375
376
377 /*******************************************************************
378  *         open_input_file
379  *
380  * Open a file in the given srcdir and set the input_file_name global variable.
381  */
382 FILE *open_input_file( const char *srcdir, const char *name )
383 {
384     char *fullname;
385     FILE *file = fopen( name, "r" );
386
387     if (!file && srcdir)
388     {
389         fullname = xmalloc( strlen(srcdir) + strlen(name) + 2 );
390         strcpy( fullname, srcdir );
391         strcat( fullname, "/" );
392         strcat( fullname, name );
393         file = fopen( fullname, "r" );
394     }
395     else fullname = xstrdup( name );
396
397     if (!file) fatal_error( "Cannot open file '%s'\n", fullname );
398     input_file_name = fullname;
399     current_line = 1;
400     return file;
401 }
402
403
404 /*******************************************************************
405  *         close_input_file
406  *
407  * Close the current input file (must have been opened with open_input_file).
408  */
409 void close_input_file( FILE *file )
410 {
411     fclose( file );
412     free( input_file_name );
413     input_file_name = NULL;
414     current_line = 0;
415 }
416
417
418 /*******************************************************************
419  *         remove_stdcall_decoration
420  *
421  * Remove a possible @xx suffix from a function name.
422  * Return the numerical value of the suffix, or -1 if none.
423  */
424 int remove_stdcall_decoration( char *name )
425 {
426     char *p, *end = strrchr( name, '@' );
427     if (!end || !end[1] || end == name) return -1;
428     /* make sure all the rest is digits */
429     for (p = end + 1; *p; p++) if (!isdigit(*p)) return -1;
430     *end = 0;
431     return atoi( end + 1 );
432 }
433
434
435 /*******************************************************************
436  *         assemble_file
437  *
438  * Run a file through the assembler.
439  */
440 void assemble_file( const char *src_file, const char *obj_file )
441 {
442     const char *prog = get_as_command();
443     char *cmd;
444     int err;
445
446     cmd = xmalloc( strlen(prog) + strlen(obj_file) + strlen(src_file) + 6 );
447     sprintf( cmd, "%s -o %s %s", prog, obj_file, src_file );
448     if (verbose) fprintf( stderr, "%s\n", cmd );
449     err = system( cmd );
450     if (err) fatal_error( "%s failed with status %d\n", prog, err );
451     free( cmd );
452 }
453
454
455 /*******************************************************************
456  *         alloc_dll_spec
457  *
458  * Create a new dll spec file descriptor
459  */
460 DLLSPEC *alloc_dll_spec(void)
461 {
462     DLLSPEC *spec;
463
464     spec = xmalloc( sizeof(*spec) );
465     spec->file_name          = NULL;
466     spec->dll_name           = NULL;
467     spec->init_func          = NULL;
468     spec->type               = SPEC_WIN32;
469     spec->base               = MAX_ORDINALS;
470     spec->limit              = 0;
471     spec->stack_size         = 0;
472     spec->heap_size          = 0;
473     spec->nb_entry_points    = 0;
474     spec->alloc_entry_points = 0;
475     spec->nb_names           = 0;
476     spec->nb_resources       = 0;
477     spec->characteristics    = IMAGE_FILE_EXECUTABLE_IMAGE;
478     if (get_ptr_size() > 4)
479         spec->characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
480     else
481         spec->characteristics |= IMAGE_FILE_32BIT_MACHINE;
482     spec->dll_characteristics = IMAGE_DLLCHARACTERISTICS_NX_COMPAT;
483     spec->subsystem          = 0;
484     spec->subsystem_major    = 4;
485     spec->subsystem_minor    = 0;
486     spec->entry_points       = NULL;
487     spec->names              = NULL;
488     spec->ordinals           = NULL;
489     spec->resources          = NULL;
490     return spec;
491 }
492
493
494 /*******************************************************************
495  *         free_dll_spec
496  *
497  * Free dll spec file descriptor
498  */
499 void free_dll_spec( DLLSPEC *spec )
500 {
501     int i;
502
503     for (i = 0; i < spec->nb_entry_points; i++)
504     {
505         ORDDEF *odp = &spec->entry_points[i];
506         free( odp->name );
507         free( odp->export_name );
508         free( odp->link_name );
509     }
510     free( spec->file_name );
511     free( spec->dll_name );
512     free( spec->init_func );
513     free( spec->entry_points );
514     free( spec->names );
515     free( spec->ordinals );
516     free( spec->resources );
517     free( spec );
518 }
519
520
521 /*******************************************************************
522  *         make_c_identifier
523  *
524  * Map a string to a valid C identifier.
525  */
526 const char *make_c_identifier( const char *str )
527 {
528     static char buffer[256];
529     char *p;
530
531     for (p = buffer; *str && p < buffer+sizeof(buffer)-1; p++, str++)
532     {
533         if (isalnum(*str)) *p = *str;
534         else *p = '_';
535     }
536     *p = 0;
537     return buffer;
538 }
539
540
541 /*******************************************************************
542  *         get_stub_name
543  *
544  * Generate an internal name for a stub entry point.
545  */
546 const char *get_stub_name( const ORDDEF *odp, const DLLSPEC *spec )
547 {
548     static char buffer[256];
549     if (odp->name || odp->export_name)
550     {
551         char *p;
552         sprintf( buffer, "__wine_stub_%s", odp->name ? odp->name : odp->export_name );
553         /* make sure name is a legal C identifier */
554         for (p = buffer; *p; p++) if (!isalnum(*p) && *p != '_') break;
555         if (!*p) return buffer;
556     }
557     sprintf( buffer, "__wine_stub_%s_%d", make_c_identifier(spec->file_name), odp->ordinal );
558     return buffer;
559 }
560
561 /* parse a cpu name and return the corresponding value */
562 enum target_cpu get_cpu_from_name( const char *name )
563 {
564     unsigned int i;
565
566     for (i = 0; i < sizeof(cpu_names)/sizeof(cpu_names[0]); i++)
567         if (!strcmp( cpu_names[i].name, name )) return cpu_names[i].cpu;
568     return -1;
569 }
570
571 /*****************************************************************
572  *  Function:    get_alignment
573  *
574  *  Description:
575  *    According to the info page for gas, the .align directive behaves
576  * differently on different systems.  On some architectures, the
577  * argument of a .align directive is the number of bytes to pad to, so
578  * to align on an 8-byte boundary you'd say
579  *     .align 8
580  * On other systems, the argument is "the number of low-order zero bits
581  * that the location counter must have after advancement."  So to
582  * align on an 8-byte boundary you'd say
583  *     .align 3
584  *
585  * The reason gas is written this way is that it's trying to mimick
586  * native assemblers for the various architectures it runs on.  gas
587  * provides other directives that work consistently across
588  * architectures, but of course we want to work on all arches with or
589  * without gas.  Hence this function.
590  *
591  *
592  *  Parameters:
593  *    align  --  the number of bytes to align to. Must be a power of 2.
594  */
595 unsigned int get_alignment(unsigned int align)
596 {
597     unsigned int n;
598
599     assert( !(align & (align - 1)) );
600
601     switch(target_cpu)
602     {
603     case CPU_x86:
604     case CPU_x86_64:
605     case CPU_SPARC:
606         if (target_platform != PLATFORM_APPLE) return align;
607         /* fall through */
608     case CPU_POWERPC:
609     case CPU_ALPHA:
610         n = 0;
611         while ((1u << n) != align) n++;
612         return n;
613     }
614     /* unreached */
615     assert(0);
616     return 0;
617 }
618
619 /* return the page size for the target CPU */
620 unsigned int get_page_size(void)
621 {
622     switch(target_cpu)
623     {
624     case CPU_x86:     return 4096;
625     case CPU_x86_64:  return 4096;
626     case CPU_POWERPC: return 4096;
627     case CPU_SPARC:   return 8192;
628     case CPU_ALPHA:   return 8192;
629     }
630     /* unreached */
631     assert(0);
632     return 0;
633 }
634
635 /* return the size of a pointer on the target CPU */
636 unsigned int get_ptr_size(void)
637 {
638     switch(target_cpu)
639     {
640     case CPU_x86:
641     case CPU_POWERPC:
642     case CPU_SPARC:
643     case CPU_ALPHA:
644         return 4;
645     case CPU_x86_64:
646         return 8;
647     }
648     /* unreached */
649     assert(0);
650     return 0;
651 }
652
653 /* return the assembly name for a C symbol */
654 const char *asm_name( const char *sym )
655 {
656     static char buffer[256];
657
658     switch (target_platform)
659     {
660     case PLATFORM_APPLE:
661     case PLATFORM_WINDOWS:
662         buffer[0] = '_';
663         strcpy( buffer + 1, sym );
664         return buffer;
665     default:
666         return sym;
667     }
668 }
669
670 /* return an assembly function declaration for a C function name */
671 const char *func_declaration( const char *func )
672 {
673     static char buffer[256];
674
675     switch (target_platform)
676     {
677     case PLATFORM_APPLE:
678         return "";
679     case PLATFORM_WINDOWS:
680         sprintf( buffer, ".def _%s; .scl 2; .type 32; .endef", func );
681         break;
682     default:
683         sprintf( buffer, ".type %s,@function", func );
684         break;
685     }
686     return buffer;
687 }
688
689 /* output a size declaration for an assembly function */
690 void output_function_size( const char *name )
691 {
692     switch (target_platform)
693     {
694     case PLATFORM_APPLE:
695     case PLATFORM_WINDOWS:
696         break;
697     default:
698         output( "\t.size %s, .-%s\n", name, name );
699         break;
700     }
701 }
702
703 /* output the GNU note for non-exec stack */
704 void output_gnu_stack_note(void)
705 {
706     switch (target_platform)
707     {
708     case PLATFORM_WINDOWS:
709     case PLATFORM_APPLE:
710         break;
711     default:
712         output( "\t.section .note.GNU-stack,\"\",@progbits\n" );
713         break;
714     }
715 }
716
717 /* return a global symbol declaration for an assembly symbol */
718 const char *asm_globl( const char *func )
719 {
720     static char buffer[256];
721
722     switch (target_platform)
723     {
724     case PLATFORM_APPLE:
725         sprintf( buffer, "\t.globl _%s\n\t.private_extern _%s\n_%s:", func, func, func );
726         return buffer;
727     case PLATFORM_WINDOWS:
728         sprintf( buffer, "\t.globl _%s\n_%s:", func, func );
729         return buffer;
730     default:
731         sprintf( buffer, "\t.globl %s\n\t.hidden %s\n%s:", func, func, func );
732         return buffer;
733     }
734 }
735
736 const char *get_asm_ptr_keyword(void)
737 {
738     switch(get_ptr_size())
739     {
740     case 4: return ".long";
741     case 8: return ".quad";
742     }
743     assert(0);
744     return NULL;
745 }
746
747 const char *get_asm_string_keyword(void)
748 {
749     switch (target_platform)
750     {
751     case PLATFORM_APPLE:
752         return ".asciz";
753     default:
754         return ".string";
755     }
756 }
757
758 const char *get_asm_short_keyword(void)
759 {
760     switch (target_platform)
761     {
762     default:            return ".short";
763     }
764 }
765
766 const char *get_asm_rodata_section(void)
767 {
768     switch (target_platform)
769     {
770     case PLATFORM_APPLE: return ".const";
771     default:             return ".section .rodata";
772     }
773 }
774
775 const char *get_asm_string_section(void)
776 {
777     switch (target_platform)
778     {
779     case PLATFORM_APPLE: return ".cstring";
780     default:             return ".section .rodata";
781     }
782 }