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