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