Framework for the doppler effect.
[wine] / tools / winebuild / spec16.c
1 /*
2  * 16-bit spec files
3  *
4  * Copyright 1993 Robert J. Amstadt
5  * Copyright 1995 Martin von Loewis
6  * Copyright 1995, 1996, 1997 Alexandre Julliard
7  * Copyright 1997 Eric Youngdale
8  * Copyright 1999 Ulrich Weigand
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include <assert.h>
29 #include <ctype.h>
30
31 #include "wine/exception.h"
32 #include "builtin16.h"
33 #include "module.h"
34 #include "stackframe.h"
35
36 #include "build.h"
37
38
39 /*******************************************************************
40  *         get_cs
41  */
42 #ifdef __i386__
43 static inline unsigned short get_cs(void)
44 {
45     unsigned short res;
46 #ifdef __GNUC__
47     __asm__("movw %%cs,%w0" : "=r"(res));
48 #elif defined(_MSC_VER)
49     __asm { mov res, cs }
50 #else
51     res = 0;
52 #endif
53     return res;
54 }
55 #endif /* __i386__ */
56
57
58 /*******************************************************************
59  *         output_file_header
60  *
61  * Output a file header with the common declarations we need.
62  */
63 static void output_file_header( FILE *outfile )
64 {
65     output_standard_file_header( outfile );
66     fprintf( outfile, "extern struct\n{\n" );
67     fprintf( outfile, "  void *base[8192];\n" );
68     fprintf( outfile, "  unsigned long limit[8192];\n" );
69     fprintf( outfile, "  unsigned char flags[8192];\n" );
70     fprintf( outfile, "} wine_ldt_copy;\n\n" );
71 #ifdef __i386__
72     fprintf( outfile, "#define __stdcall __attribute__((__stdcall__))\n\n" );
73 #else
74     fprintf( outfile, "#define __stdcall\n\n" );
75 #endif
76 }
77
78
79 /*******************************************************************
80  *         StoreVariableCode
81  *
82  * Store a list of ints into a byte array.
83  */
84 static int StoreVariableCode( unsigned char *buffer, int size, ORDDEF *odp )
85 {
86     int i;
87
88     switch(size)
89     {
90     case 1:
91         for (i = 0; i < odp->u.var.n_values; i++)
92             buffer[i] = odp->u.var.values[i];
93         break;
94     case 2:
95         for (i = 0; i < odp->u.var.n_values; i++)
96             ((unsigned short *)buffer)[i] = odp->u.var.values[i];
97         break;
98     case 4:
99         for (i = 0; i < odp->u.var.n_values; i++)
100             ((unsigned int *)buffer)[i] = odp->u.var.values[i];
101         break;
102     }
103     return odp->u.var.n_values * size;
104 }
105
106
107 /*******************************************************************
108  *         BuildModule16
109  *
110  * Build the in-memory representation of a 16-bit NE module, and dump it
111  * as a byte stream into the assembly code.
112  */
113 static int BuildModule16( FILE *outfile, int max_code_offset,
114                           int max_data_offset )
115 {
116     int i;
117     char *buffer;
118     NE_MODULE *pModule;
119     SEGTABLEENTRY *pSegment;
120     OFSTRUCT *pFileInfo;
121     BYTE *pstr;
122     ET_BUNDLE *bundle = 0;
123     ET_ENTRY entry;
124
125     /*   Module layout:
126      * NE_MODULE       Module
127      * OFSTRUCT        File information
128      * SEGTABLEENTRY   Segment 1 (code)
129      * SEGTABLEENTRY   Segment 2 (data)
130      * WORD[2]         Resource table (empty)
131      * BYTE[2]         Imported names (empty)
132      * BYTE[n]         Resident names table
133      * BYTE[n]         Entry table
134      */
135
136     buffer = xmalloc( 0x10000 );
137     memset( buffer, 0, 0x10000 );
138
139     pModule = (NE_MODULE *)buffer;
140     pModule->magic = IMAGE_OS2_SIGNATURE;
141     pModule->count = 1;
142     pModule->next = 0;
143     pModule->flags = NE_FFLAGS_SINGLEDATA | NE_FFLAGS_BUILTIN | NE_FFLAGS_LIBMODULE;
144     pModule->dgroup = 2;
145     pModule->heap_size = DLLHeapSize;
146     pModule->stack_size = 0;
147     pModule->ip = 0;
148     pModule->cs = 0;
149     pModule->sp = 0;
150     pModule->ss = 0;
151     pModule->seg_count = 2;
152     pModule->modref_count = 0;
153     pModule->nrname_size = 0;
154     pModule->modref_table = 0;
155     pModule->nrname_fpos = 0;
156     pModule->moveable_entries = 0;
157     pModule->alignment = 0;
158     pModule->truetype = 0;
159     pModule->os_flags = NE_OSFLAGS_WINDOWS;
160     pModule->misc_flags = 0;
161     pModule->dlls_to_init  = 0;
162     pModule->nrname_handle = 0;
163     pModule->min_swap_area = 0;
164     pModule->expected_version = 0;
165     pModule->module32 = 0;
166     pModule->self = 0;
167     pModule->self_loading_sel = 0;
168
169       /* File information */
170
171     pFileInfo = (OFSTRUCT *)(pModule + 1);
172     pModule->fileinfo = (int)pFileInfo - (int)pModule;
173     memset( pFileInfo, 0, sizeof(*pFileInfo) - sizeof(pFileInfo->szPathName) );
174     pFileInfo->cBytes = sizeof(*pFileInfo) - sizeof(pFileInfo->szPathName)
175                         + strlen(dll_file_name);
176     strcpy( pFileInfo->szPathName, dll_file_name );
177     pstr = (char *)pFileInfo + pFileInfo->cBytes + 1;
178
179       /* Segment table */
180
181     pstr = (char *)(((long)pstr + 3) & ~3);
182     pSegment = (SEGTABLEENTRY *)pstr;
183     pModule->seg_table = (int)pSegment - (int)pModule;
184     pSegment->filepos = 0;
185     pSegment->size = max_code_offset;
186     pSegment->flags = 0;
187     pSegment->minsize = max_code_offset;
188     pSegment->hSeg = 0;
189     pSegment++;
190
191     pModule->dgroup_entry = (int)pSegment - (int)pModule;
192     pSegment->filepos = 0;
193     pSegment->size = max_data_offset;
194     pSegment->flags = NE_SEGFLAGS_DATA;
195     pSegment->minsize = max_data_offset;
196     pSegment->hSeg = 0;
197     pSegment++;
198
199       /* Resource table */
200
201     pstr = (char *)pSegment;
202     pstr = (char *)(((long)pstr + 3) & ~3);
203     pModule->res_table = (int)pstr - (int)pModule;
204     pstr += output_res16_directory( pstr );
205
206       /* Imported names table */
207
208     pstr = (char *)(((long)pstr + 3) & ~3);
209     pModule->import_table = (int)pstr - (int)pModule;
210     *pstr++ = 0;
211     *pstr++ = 0;
212
213       /* Resident names table */
214
215     pstr = (char *)(((long)pstr + 3) & ~3);
216     pModule->name_table = (int)pstr - (int)pModule;
217     /* First entry is module name */
218     *pstr = strlen( dll_name );
219     strcpy( pstr + 1, dll_name );
220     strupper( pstr + 1 );
221     pstr += *pstr + 1;
222     *pstr++ = 0;
223     *pstr++ = 0;
224     /* Store all ordinals */
225     for (i = 1; i <= Limit; i++)
226     {
227         ORDDEF *odp = Ordinals[i];
228         WORD ord = i;
229         if (!odp || !odp->name[0]) continue;
230         *pstr = strlen( odp->name );
231         strcpy( pstr + 1, odp->name );
232         strupper( pstr + 1 );
233         pstr += *pstr + 1;
234         memcpy( pstr, &ord, sizeof(WORD) );
235         pstr += sizeof(WORD);
236     }
237     *pstr++ = 0;
238
239       /* Entry table */
240
241     pstr = (char *)(((long)pstr + 3) & ~3);
242     pModule->entry_table = (int)pstr - (int)pModule;
243     for (i = 1; i <= Limit; i++)
244     {
245         int selector = 0;
246         ORDDEF *odp = Ordinals[i];
247         if (!odp) continue;
248
249         switch (odp->type)
250         {
251         case TYPE_CDECL:
252         case TYPE_PASCAL:
253         case TYPE_PASCAL_16:
254         case TYPE_STUB:
255             selector = 1;  /* Code selector */
256             break;
257
258         case TYPE_VARIABLE:
259             selector = 2;  /* Data selector */
260             break;
261
262         case TYPE_ABS:
263             selector = 0xfe;  /* Constant selector */
264             break;
265
266         default:
267             selector = 0;  /* Invalid selector */
268             break;
269         }
270
271         if ( !selector )
272            continue;
273
274         if ( bundle && bundle->last+1 == i )
275             bundle->last++;
276         else
277         {
278             pstr = (char *)(((long)pstr + 1) & ~1);
279             if ( bundle )
280                 bundle->next = (char *)pstr - (char *)pModule;
281
282             bundle = (ET_BUNDLE *)pstr;
283             bundle->first = i-1;
284             bundle->last = i;
285             bundle->next = 0;
286             pstr += sizeof(ET_BUNDLE);
287         }
288
289         /* FIXME: is this really correct ?? */
290         entry.type = 0xff;  /* movable */
291         entry.flags = 3; /* exported & public data */
292         entry.segnum = selector;
293         entry.offs = odp->offset;
294         memcpy( pstr, &entry, sizeof(ET_ENTRY) );
295         pstr += sizeof(ET_ENTRY);
296     }
297     *pstr++ = 0;
298
299       /* Dump the module content */
300
301     pstr = (char *)(((long)pstr + 3) & ~3);
302     dump_bytes( outfile, (char *)pModule, (int)pstr - (int)pModule, "Module", 0 );
303     return (int)pstr - (int)pModule;
304 }
305
306
307 /*******************************************************************
308  *         BuildCallFrom16Func
309  *
310  * Build a 16-bit-to-Wine callback glue function.
311  *
312  * The generated routines are intended to be used as argument conversion
313  * routines to be called by the CallFrom16... core. Thus, the prototypes of
314  * the generated routines are (see also CallFrom16):
315  *
316  *  extern WORD WINAPI PREFIX_CallFrom16_C_word_xxx( FARPROC func, LPBYTE args );
317  *  extern LONG WINAPI PREFIX_CallFrom16_C_long_xxx( FARPROC func, LPBYTE args );
318  *  extern void WINAPI PREFIX_CallFrom16_C_regs_xxx( FARPROC func, LPBYTE args,
319  *                                                   CONTEXT86 *context );
320  *  extern void WINAPI PREFIX_CallFrom16_C_intr_xxx( FARPROC func, LPBYTE args,
321  *                                                   CONTEXT86 *context );
322  *
323  * where 'C' is the calling convention ('p' for pascal or 'c' for cdecl),
324  * and each 'x' is an argument  ('w'=word, 's'=signed word, 'l'=long,
325  * 'p'=linear pointer, 't'=linear pointer to null-terminated string,
326  * 'T'=segmented pointer to null-terminated string).
327  *
328  * The generated routines fetch the arguments from the 16-bit stack (pointed
329  * to by 'args'); the offsets of the single argument values are computed
330  * according to the calling convention and the argument types.  Then, the
331  * 32-bit entry point is called with these arguments.
332  *
333  * For register functions, the arguments (if present) are converted just
334  * the same as for normal functions, but in addition the CONTEXT86 pointer
335  * filled with the current register values is passed to the 32-bit routine.
336  * (An 'intr' interrupt handler routine is treated exactly like a register
337  * routine, except that upon return, the flags word pushed onto the stack
338  * by the interrupt is removed by the 16-bit call stub.)
339  *
340  */
341 static void BuildCallFrom16Func( FILE *outfile, const char *profile, const char *prefix )
342 {
343     int i, pos, argsize = 0;
344     int short_ret = 0;
345     int reg_func = 0;
346     int usecdecl = 0;
347     const char *args = profile + 7;
348     char *ret_type;
349
350     /* Parse function type */
351
352     if (!strncmp( "c_", profile, 2 )) usecdecl = 1;
353     else if (strncmp( "p_", profile, 2 ))
354     {
355         fprintf( stderr, "Invalid function name '%s', ignored\n", profile );
356         return;
357     }
358
359     if (!strncmp( "word_", profile + 2, 5 )) short_ret = 1;
360     else if (!strncmp( "regs_", profile + 2, 5 )) reg_func = 1;
361     else if (!strncmp( "intr_", profile + 2, 5 )) reg_func = 2;
362     else if (strncmp( "long_", profile + 2, 5 ))
363     {
364         fprintf( stderr, "Invalid function name '%s', ignored\n", profile );
365         return;
366     }
367
368     for ( i = 0; args[i]; i++ )
369         switch ( args[i] )
370         {
371         case 'w':  /* word */
372         case 's':  /* s_word */
373             argsize += 2;
374             break;
375         case 'l':  /* long or segmented pointer */
376         case 'T':  /* segmented pointer to null-terminated string */
377         case 'p':  /* linear pointer */
378         case 't':  /* linear pointer to null-terminated string */
379             argsize += 4;
380             break;
381         }
382
383     ret_type = reg_func? "void" : short_ret ? "unsigned short" : "unsigned int";
384
385     fprintf( outfile, "typedef %s (__stdcall *proc_%s_t)( ", ret_type, profile );
386     args = profile + 7;
387     for ( i = 0; args[i]; i++ )
388     {
389         if ( i ) fprintf( outfile, ", " );
390         switch (args[i])
391         {
392         case 'w':           fprintf( outfile, "unsigned short" ); break;
393         case 's':           fprintf( outfile, "short" ); break;
394         case 'l': case 'T': fprintf( outfile, "unsigned int" ); break;
395         case 'p': case 't': fprintf( outfile, "void *" ); break;
396         }
397     }
398     if ( reg_func )
399         fprintf( outfile, "%svoid *", i? ", " : "" );
400     else if ( !i )
401         fprintf( outfile, "void" );
402     fprintf( outfile, " );\n" );
403
404     fprintf( outfile, "static %s __stdcall __wine_%s_CallFrom16_%s( proc_%s_t proc, unsigned char *args%s )\n",
405              ret_type, make_c_identifier(prefix), profile, profile,
406              reg_func? ", void *context" : "" );
407
408     fprintf( outfile, "{\n    %sproc(\n", reg_func ? "" : "return " );
409     args = profile + 7;
410     pos = !usecdecl? argsize : 0;
411     for ( i = 0; args[i]; i++ )
412     {
413         if ( i ) fprintf( outfile, ",\n" );
414         fprintf( outfile, "        " );
415         switch (args[i])
416         {
417         case 'w':  /* word */
418             if ( !usecdecl ) pos -= 2;
419             fprintf( outfile, "*(unsigned short *)(args+%d)", pos );
420             if (  usecdecl ) pos += 2;
421             break;
422
423         case 's':  /* s_word */
424             if ( !usecdecl ) pos -= 2;
425             fprintf( outfile, "*(short *)(args+%d)", pos );
426             if (  usecdecl ) pos += 2;
427             break;
428
429         case 'l':  /* long or segmented pointer */
430         case 'T':  /* segmented pointer to null-terminated string */
431             if ( !usecdecl ) pos -= 4;
432             fprintf( outfile, "*(unsigned int *)(args+%d)", pos );
433             if (  usecdecl ) pos += 4;
434             break;
435
436         case 'p':  /* linear pointer */
437         case 't':  /* linear pointer to null-terminated string */
438             if ( !usecdecl ) pos -= 4;
439             fprintf( outfile, "((char*)wine_ldt_copy.base[*(unsigned short*)(args+%d) >> 3] + *(unsigned short*)(args+%d))",
440                      pos + 2, pos );
441             if (  usecdecl ) pos += 4;
442             break;
443
444         default:
445             fprintf( stderr, "Unknown arg type '%c'\n", args[i] );
446         }
447     }
448     if ( reg_func )
449         fprintf( outfile, "%s        context", i? ",\n" : "" );
450     fprintf( outfile, " );\n}\n\n" );
451 }
452
453
454 /*******************************************************************
455  *         BuildCallTo16Func
456  *
457  * Build a Wine-to-16-bit callback glue function.
458  *
459  * Prototypes for the CallTo16 functions:
460  *   extern WORD CALLBACK PREFIX_CallTo16_word_xxx( FARPROC16 func, args... );
461  *   extern LONG CALLBACK PREFIX_CallTo16_long_xxx( FARPROC16 func, args... );
462  *
463  * These routines are provided solely for convenience; they simply
464  * write the arguments onto the 16-bit stack, and call the appropriate
465  * wine_call_to_16... core routine.
466  *
467  * If you have more sophisticated argument conversion requirements than
468  * are provided by these routines, you might as well call the core
469  * routines by yourself.
470  *
471  */
472 static int BuildCallTo16Func( FILE *outfile, const char *profile, const char *prefix )
473 {
474     const char *args = profile + 5;
475     int i, argsize = 0, short_ret = 0;
476
477     if (!strncmp( "word_", profile, 5 )) short_ret = 1;
478     else if (strncmp( "long_", profile, 5 ))
479     {
480         error( "Invalid function name '%s'\n", profile );
481         return 0;
482     }
483
484     fprintf( outfile, "unsigned %s __stdcall %s_CallTo16_%s( void (*proc)()",
485              short_ret? "short" : "int", prefix, profile );
486     args = profile + 5;
487     for ( i = 0; args[i]; i++ )
488     {
489         fprintf( outfile, ", " );
490         switch (args[i])
491         {
492         case 'w': fprintf( outfile, "unsigned short" ); argsize += 2; break;
493         case 'l': fprintf( outfile, "unsigned int" ); argsize += 4; break;
494         default:
495             error( "Invalid letter '%c' in function name '%s'\n", args[i], profile );
496             return 0;
497         }
498         fprintf( outfile, " arg%d", i+1 );
499     }
500     fprintf( outfile, " )\n{\n" );
501
502 #ifdef __i386__
503     if ( argsize > 0 )
504     {
505         fprintf( outfile, "    char *args;\n" );
506         fprintf( outfile, "    unsigned int cur_stack;\n\n" );
507         fprintf( outfile, "#ifdef __GNUC__\n" );
508         fprintf( outfile, "    __asm__(\".byte 0x64\\n\\tmovl (0x%x),%%0\" : \"=r\" (cur_stack));\n",
509                  STACKOFFSET );
510         fprintf( outfile, "#else\n" );
511         fprintf( outfile, "    extern char *NtCurrentTeb(void);\n" );
512         fprintf( outfile, "    cur_stack = *(unsigned int *)(NtCurrentTeb() + 0x%x);\n",
513                  STACKOFFSET );
514         fprintf( outfile, "#endif\n" );
515         fprintf( outfile, "    args = (char *)wine_ldt_copy.base[cur_stack >> 19] + (cur_stack & 0xffff);\n" );
516     }
517
518     args = profile + 5;
519     for ( i = 0; args[i]; i++ )
520     {
521         switch (args[i])
522         {
523         case 'w': fprintf( outfile, "    args -= sizeof(unsigned short); *(unsigned short" ); break;
524         case 'l': fprintf( outfile, "    args -= sizeof(unsigned int); *(unsigned int" ); break;
525         default:  fprintf( stderr, "Unexpected case '%c' in BuildCallTo16Func\n",
526                                    args[i] );
527         }
528         fprintf( outfile, " *)args = arg%d;\n", i+1 );
529     }
530
531     fprintf( outfile, "    return wine_call_to_16( proc, %d );\n}\n\n", argsize );
532 #else  /* __i386__ */
533     fprintf( outfile, "    assert(0);\n}\n\n" );
534 #endif  /* __i386__ */
535     return 1;
536 }
537
538
539 /*******************************************************************
540  *         get_function_name
541  */
542 static const char *get_function_name( const ORDDEF *odp )
543 {
544     static char buffer[80];
545
546     sprintf( buffer, "%s_%s_%s",
547              (odp->type == TYPE_CDECL) ? "c" : "p",
548              (odp->flags & FLAG_REGISTER) ? "regs" :
549              (odp->flags & FLAG_INTERRUPT) ? "intr" :
550              (odp->type == TYPE_PASCAL_16) ? "word" : "long",
551              odp->u.func.arg_types );
552     return buffer;
553 }
554
555
556 /*******************************************************************
557  *         Spec16TypeCompare
558  */
559 static int Spec16TypeCompare( const void *e1, const void *e2 )
560 {
561     const ORDDEF *odp1 = *(const ORDDEF **)e1;
562     const ORDDEF *odp2 = *(const ORDDEF **)e2;
563     int retval;
564
565     int type1 = (odp1->type == TYPE_CDECL) ? 0
566               : (odp1->type == TYPE_PASCAL_16) ? 1 : 2;
567
568     int type2 = (odp2->type == TYPE_CDECL) ? 0
569               : (odp2->type == TYPE_PASCAL_16) ? 1 : 2;
570
571     if (odp1->flags & FLAG_REGISTER) type1 += 4;
572     if (odp1->flags & FLAG_INTERRUPT) type1 += 8;
573     if (odp2->flags & FLAG_REGISTER) type2 += 4;
574     if (odp2->flags & FLAG_INTERRUPT) type2 += 8;
575
576     retval = type1 - type2;
577     if ( !retval )
578         retval = strcmp( odp1->u.func.arg_types, odp2->u.func.arg_types );
579
580     return retval;
581 }
582
583
584 /*******************************************************************
585  *         output_stub_funcs
586  *
587  * Output the functions for stub entry points
588 */
589 static void output_stub_funcs( FILE *outfile )
590 {
591     int i;
592     char *p;
593
594     for (i = 0; i <= Limit; i++)
595     {
596         ORDDEF *odp = Ordinals[i];
597         if (!odp || odp->type != TYPE_STUB) continue;
598         fprintf( outfile, "#ifdef __GNUC__\n" );
599         fprintf( outfile, "static void __wine_unimplemented( const char *func ) __attribute__((noreturn));\n" );
600         fprintf( outfile, "#endif\n" );
601         fprintf( outfile, "static void __wine_unimplemented( const char *func )\n{\n" );
602         fprintf( outfile, "  struct exc_record {\n" );
603         fprintf( outfile, "    unsigned int code, flags;\n" );
604         fprintf( outfile, "    void *rec, *addr;\n" );
605         fprintf( outfile, "    unsigned int params;\n" );
606         fprintf( outfile, "    const void *info[15];\n" );
607         fprintf( outfile, "  } rec;\n\n" );
608         fprintf( outfile, "  extern void __stdcall RtlRaiseException( struct exc_record * );\n\n" );
609         fprintf( outfile, "  rec.code    = 0x%08x;\n", EXCEPTION_WINE_STUB );
610         fprintf( outfile, "  rec.flags   = %d;\n", EH_NONCONTINUABLE );
611         fprintf( outfile, "  rec.rec     = 0;\n" );
612         fprintf( outfile, "  rec.params  = 2;\n" );
613         fprintf( outfile, "  rec.info[0] = \"%s\";\n", dll_file_name );
614         fprintf( outfile, "  rec.info[1] = func;\n" );
615         fprintf( outfile, "#ifdef __GNUC__\n" );
616         fprintf( outfile, "  rec.addr = __builtin_return_address(1);\n" );
617         fprintf( outfile, "#else\n" );
618         fprintf( outfile, "  rec.addr = 0;\n" );
619         fprintf( outfile, "#endif\n" );
620         fprintf( outfile, "  for (;;) RtlRaiseException( &rec );\n}\n\n" );
621         break;
622     }
623     for (i = 0; i <= Limit; i++)
624     {
625         ORDDEF *odp = Ordinals[i];
626         if (!odp || odp->type != TYPE_STUB) continue;
627         odp->link_name = xrealloc( odp->link_name, strlen(odp->name) + 13 );
628         strcpy( odp->link_name, "__wine_stub_" );
629         strcat( odp->link_name, odp->name );
630         for (p = odp->link_name; *p; p++) if (!isalnum(*p)) *p = '_';
631         fprintf( outfile, "static void %s(void) { __wine_unimplemented(\"%s\"); }\n",
632                  odp->link_name, odp->name );
633     }
634 }
635
636
637 /*******************************************************************
638  *         BuildSpec16File
639  *
640  * Build a Win16 assembly file from a spec file.
641  */
642 void BuildSpec16File( FILE *outfile )
643 {
644     ORDDEF **type, **typelist;
645     int i, nFuncs, nTypes;
646     int code_offset, data_offset, module_size, res_size;
647     unsigned char *data;
648     char constructor[100], destructor[100];
649 #ifdef __i386__
650     unsigned short code_selector = get_cs();
651 #endif
652
653     /* File header */
654
655     output_file_header( outfile );
656     fprintf( outfile, "extern unsigned short __wine_call_from_16_word();\n" );
657     fprintf( outfile, "extern unsigned int __wine_call_from_16_long();\n" );
658     fprintf( outfile, "extern void __wine_call_from_16_regs();\n" );
659     fprintf( outfile, "extern void __wine_call_from_16_thunk();\n" );
660
661     data = (unsigned char *)xmalloc( 0x10000 );
662     memset( data, 0, 16 );
663     data_offset = 16;
664
665     if (!dll_name)  /* set default name from file name */
666     {
667         char *p;
668         dll_name = xstrdup( dll_file_name );
669         if ((p = strrchr( dll_name, '.' ))) *p = 0;
670     }
671
672     output_stub_funcs( outfile );
673
674     /* Build sorted list of all argument types, without duplicates */
675
676     typelist = (ORDDEF **)calloc( Limit+1, sizeof(ORDDEF *) );
677
678     for (i = nFuncs = 0; i <= Limit; i++)
679     {
680         ORDDEF *odp = Ordinals[i];
681         if (!odp) continue;
682         switch (odp->type)
683         {
684           case TYPE_CDECL:
685           case TYPE_PASCAL:
686           case TYPE_PASCAL_16:
687           case TYPE_STUB:
688             typelist[nFuncs++] = odp;
689
690           default:
691             break;
692         }
693     }
694
695     qsort( typelist, nFuncs, sizeof(ORDDEF *), Spec16TypeCompare );
696
697     i = nTypes = 0;
698     while ( i < nFuncs )
699     {
700         typelist[nTypes++] = typelist[i++];
701         while ( i < nFuncs && Spec16TypeCompare( typelist + i, typelist + nTypes-1 ) == 0 )
702             i++;
703     }
704
705     /* Output CallFrom16 routines needed by this .spec file */
706 #ifdef __i386__
707     for ( i = 0; i < nTypes; i++ )
708     {
709         char profile[101];
710
711         strcpy( profile, get_function_name( typelist[i] ));
712         BuildCallFrom16Func( outfile, profile, dll_file_name );
713     }
714 #endif
715
716     /* Output the DLL functions prototypes */
717
718     for (i = 0; i <= Limit; i++)
719     {
720         ORDDEF *odp = Ordinals[i];
721         if (!odp) continue;
722         switch(odp->type)
723         {
724         case TYPE_CDECL:
725         case TYPE_PASCAL:
726         case TYPE_PASCAL_16:
727             fprintf( outfile, "extern void %s();\n", odp->link_name );
728             break;
729         default:
730             break;
731         }
732     }
733
734     /* Output code segment */
735
736     fprintf( outfile, "\n#include \"pshpack1.h\"\n" );
737     fprintf( outfile, "\nstatic struct code_segment\n{\n" );
738     fprintf( outfile, "  struct {\n" );
739 #ifdef __i386__
740     fprintf( outfile, "    unsigned char pushl;\n" );      /* pushl $relay */
741     fprintf( outfile, "    void *relay;\n" );
742     fprintf( outfile, "    unsigned char lcall;\n" );      /* lcall __FLATCS__:glue */
743     fprintf( outfile, "    void *glue;\n" );
744     fprintf( outfile, "    unsigned short flatcs;\n" );
745 #endif
746     fprintf( outfile, "    unsigned short lret;\n" );      /* lret $args */
747     fprintf( outfile, "    unsigned short args;\n" );
748     fprintf( outfile, "    unsigned int arg_types[2];\n" );
749     fprintf( outfile, "  } call[%d];\n", nTypes );
750     fprintf( outfile, "  struct {\n" );
751 #ifdef __i386__
752     fprintf( outfile, "    unsigned short pushw_bp;\n" );  /* pushw %bp */
753     fprintf( outfile, "    unsigned char pushl;\n" );      /* pushl $target */
754 #endif
755     fprintf( outfile, "    void (*target)();\n" );
756     fprintf( outfile, "    unsigned short call;\n" );      /* call CALLFROM16 */
757     fprintf( outfile, "    short callfrom16;\n" );
758     fprintf( outfile, "  } entry[%d];\n", nFuncs );
759     fprintf( outfile, "} code_segment =\n{\n  {\n" );
760
761     code_offset = 0;
762
763     for ( i = 0; i < nTypes; i++ )
764     {
765         char profile[101], *arg;
766         unsigned int arg_types[2];
767         int j, argsize = 0;
768
769         strcpy( profile, get_function_name( typelist[i] ));
770         if ( typelist[i]->type != TYPE_CDECL )
771             for ( arg = typelist[i]->u.func.arg_types; *arg; arg++ )
772                 switch ( *arg )
773                 {
774                 case 'w':  /* word */
775                 case 's':  /* s_word */
776                     argsize += 2;
777                     break;
778                 case 'l':  /* long or segmented pointer */
779                 case 'T':  /* segmented pointer to null-terminated string */
780                 case 'p':  /* linear pointer */
781                 case 't':  /* linear pointer to null-terminated string */
782                     argsize += 4;
783                     break;
784                 }
785
786         if (typelist[i]->flags & FLAG_INTERRUPT) argsize += 2;
787
788         /* build the arg types bit fields */
789         arg_types[0] = arg_types[1] = 0;
790         for (j = 0; typelist[i]->u.func.arg_types[j]; j++)
791         {
792             int type = 0;
793             switch(typelist[i]->u.func.arg_types[j])
794             {
795             case 'w': type = ARG_WORD; break;
796             case 's': type = ARG_SWORD; break;
797             case 'l': type = ARG_LONG; break;
798             case 'p': type = ARG_PTR; break;
799             case 't': type = ARG_STR; break;
800             case 'T': type = ARG_SEGSTR; break;
801             }
802             arg_types[j / 10] |= type << (3 * (j % 10));
803         }
804         if (typelist[i]->flags & (FLAG_REGISTER|FLAG_INTERRUPT)) arg_types[0] |= ARG_REGISTER;
805         if (typelist[i]->type == TYPE_PASCAL_16) arg_types[0] |= ARG_RET16;
806
807 #ifdef __i386__
808         fprintf( outfile, "    { 0x68, __wine_%s_CallFrom16_%s, 0x9a, __wine_call_from_16_%s,\n",
809                  make_c_identifier(dll_file_name), profile,
810                  (typelist[i]->flags & (FLAG_REGISTER|FLAG_INTERRUPT)) ? "regs":
811                  typelist[i]->type == TYPE_PASCAL_16? "word" : "long" );
812         if (argsize)
813             fprintf( outfile, "      0x%04x, 0xca66, %d, { 0x%08x, 0x%08x } },\n",
814                      code_selector, argsize, arg_types[0], arg_types[1] );
815         else
816             fprintf( outfile, "      0x%04x, 0xcb66, 0x9090, { 0x%08x, 0x%08x } },\n",
817                      code_selector, arg_types[0], arg_types[1] );
818 #else
819         if (argsize)
820             fprintf( outfile, "    { 0xca66, %d, { 0x%08x, 0x%08x } },\n",
821                      argsize, arg_types[0], arg_types[1] );
822         else
823             fprintf( outfile, "     { 0xcb66, 0x9090, { 0x%08x, 0x%08x } },\n",
824                      arg_types[0], arg_types[1] );
825 #endif
826         code_offset += sizeof(CALLFROM16);
827     }
828     fprintf( outfile, "  },\n  {\n" );
829
830     for (i = 0; i <= Limit; i++)
831     {
832         ORDDEF *odp = Ordinals[i];
833         if (!odp) continue;
834         switch (odp->type)
835         {
836           case TYPE_ABS:
837             odp->offset = LOWORD(odp->u.abs.value);
838             break;
839
840           case TYPE_VARIABLE:
841             odp->offset = data_offset;
842             data_offset += StoreVariableCode( data + data_offset, 4, odp);
843             break;
844
845           case TYPE_CDECL:
846           case TYPE_PASCAL:
847           case TYPE_PASCAL_16:
848           case TYPE_STUB:
849             type = bsearch( &odp, typelist, nTypes, sizeof(ORDDEF *), Spec16TypeCompare );
850             assert( type );
851
852             fprintf( outfile, "    /* %s.%d */ ", dll_name, i );
853 #ifdef __i386__
854             fprintf( outfile, "{ 0x5566, 0x68, %s, 0xe866, %d  /* %s */ },\n",
855 #else
856             fprintf( outfile, "{ %s, 0xe866, %d, /* %s */ },\n",
857 #endif
858                      odp->link_name,
859                      (type-typelist)*sizeof(CALLFROM16) -
860                      (code_offset + sizeof(ENTRYPOINT16)),
861                      get_function_name( odp ) );
862
863             odp->offset = code_offset;
864             code_offset += sizeof(ENTRYPOINT16);
865             break;
866
867           default:
868             fprintf(stderr,"build: function type %d not available for Win16\n",
869                     odp->type);
870             exit(1);
871         }
872     }
873
874     fprintf( outfile, "    }\n};\n" );
875
876     /* Output data segment */
877
878     dump_bytes( outfile, data, data_offset, "Data_Segment", 0 );
879
880     /* Build the module */
881
882     module_size = BuildModule16( outfile, code_offset, data_offset );
883     res_size = output_res16_data( outfile );
884
885     /* Output the DLL descriptor */
886
887     fprintf( outfile, "#include \"poppack.h\"\n\n" );
888
889     fprintf( outfile, "static const struct dll_descriptor\n{\n" );
890     fprintf( outfile, "    unsigned char *module_start;\n" );
891     fprintf( outfile, "    int module_size;\n" );
892     fprintf( outfile, "    struct code_segment *code_start;\n" );
893     fprintf( outfile, "    unsigned char *data_start;\n" );
894     fprintf( outfile, "    const char *owner;\n" );
895     fprintf( outfile, "    const unsigned char *rsrc;\n" );
896     fprintf( outfile, "} descriptor =\n{\n" );
897     fprintf( outfile, "    Module,\n" );
898     fprintf( outfile, "    sizeof(Module),\n" );
899     fprintf( outfile, "    &code_segment,\n" );
900     fprintf( outfile, "    Data_Segment,\n" );
901     fprintf( outfile, "    \"%s\",\n", owner_name );
902     fprintf( outfile, "    %s\n", res_size ? "resource_data" : "0" );
903     fprintf( outfile, "};\n" );
904
905     /* Output the DLL constructor */
906
907     sprintf( constructor, "__wine_spec_%s_init", make_c_identifier(dll_file_name) );
908     sprintf( destructor, "__wine_spec_%s_fini", make_c_identifier(dll_file_name) );
909     output_dll_init( outfile, constructor, destructor );
910
911     fprintf( outfile,
912              "void %s(void)\n"
913              "{\n"
914              "    extern void __wine_register_dll_16( const struct dll_descriptor *descr );\n"
915              "    __wine_register_dll_16( &descriptor );\n"
916              "}\n", constructor );
917     fprintf( outfile,
918              "void %s(void)\n"
919              "{\n"
920              "    extern void __wine_unregister_dll_16( const struct dll_descriptor *descr );\n"
921              "    __wine_unregister_dll_16( &descriptor );\n"
922              "}\n", destructor );
923 }
924
925
926 /*******************************************************************
927  *         BuildGlue
928  *
929  * Build the 16-bit-to-Wine/Wine-to-16-bit callback glue code
930  */
931 void BuildGlue( FILE *outfile, const char *srcdir, char **argv )
932 {
933     char buffer[1024];
934
935     /* File header */
936
937     output_file_header( outfile );
938
939 #ifdef __i386__
940     fprintf( outfile, "extern unsigned int __stdcall wine_call_to_16( void (*target)(), int args );\n\n" );
941 #else
942     fprintf( outfile, "#include <assert.h>\n\n" );
943 #endif
944
945     /* Build the callback glue functions */
946
947     while (*argv)
948     {
949         FILE *infile = open_input_file( srcdir, *argv );
950
951         while (fgets( buffer, sizeof(buffer), infile ))
952         {
953             current_line++;
954             if (strstr( buffer, "### start build ###" )) break;
955         }
956         while (fgets( buffer, sizeof(buffer), infile ))
957         {
958             char *p;
959             if ( (p = strstr( buffer, "CallTo16_" )) != NULL )
960             {
961                 char *q, *profile = p + strlen( "CallTo16_" );
962                 for (q = profile; (*q == '_') || isalpha(*q); q++ )
963                     ;
964                 *q = '\0';
965                 for (q = p-1; q > buffer && ((*q == '_') || isalnum(*q)); q-- )
966                     ;
967                 if ( ++q < p ) p[-1] = '\0'; else q = "";
968                 BuildCallTo16Func( outfile, profile, q );
969             }
970             current_line++;
971             if (strstr( buffer, "### stop build ###" )) break;
972         }
973         close_input_file( infile );
974         argv++;
975     }
976 }