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