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