Send regular messages to stdout so that they are separate from
[wine] / tools / build.c
1 /*
2  * Copyright 1993 Robert J. Amstadt
3  * Copyright 1995 Martin von Loewis
4  * Copyright 1995, 1996, 1997 Alexandre Julliard
5  * Copyright 1997 Eric Youngdale
6  * Copyright 1999 Ulrich Weigand
7  */
8
9 #include "config.h"
10
11 #include <assert.h>
12 #include <stdarg.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <ctype.h>
17 #include <unistd.h>
18
19 #include "winbase.h"
20 #include "winnt.h"
21 #include "module.h"
22 #include "neexe.h"
23 #include "stackframe.h"
24 #include "builtin16.h"
25 #include "thread.h"
26
27 #ifdef NEED_UNDERSCORE_PREFIX
28 # define PREFIX "_"
29 #else
30 # define PREFIX
31 #endif
32
33 #ifdef HAVE_ASM_STRING
34 # define STRING ".string"
35 #else
36 # define STRING ".ascii"
37 #endif
38
39 #if defined(__GNUC__) && !defined(__svr4__)
40 # define USE_STABS
41 #else
42 # undef USE_STABS
43 #endif
44
45 #ifdef __i386__
46 extern WORD __get_cs(void);
47 extern WORD __get_ds(void);
48 __ASM_GLOBAL_FUNC( __get_cs, "movw %cs,%ax\n\tret" );
49 __ASM_GLOBAL_FUNC( __get_ds, "movw %ds,%ax\n\tret" );
50 #else
51 static inline WORD __get_cs(void) { return 0; }
52 static inline WORD __get_ds(void) { return 0; }
53 #endif
54
55 typedef enum
56 {
57     TYPE_BYTE,         /* byte variable (Win16) */
58     TYPE_WORD,         /* word variable (Win16) */
59     TYPE_LONG,         /* long variable (Win16) */
60     TYPE_PASCAL_16,    /* pascal function with 16-bit return (Win16) */
61     TYPE_PASCAL,       /* pascal function with 32-bit return (Win16) */
62     TYPE_ABS,          /* absolute value (Win16) */
63     TYPE_REGISTER,     /* register function */
64     TYPE_INTERRUPT,    /* interrupt handler function (Win16) */
65     TYPE_STUB,         /* unimplemented stub */
66     TYPE_STDCALL,      /* stdcall function (Win32) */
67     TYPE_CDECL,        /* cdecl function (Win32) */
68     TYPE_VARARGS,      /* varargs function (Win32) */
69     TYPE_EXTERN,       /* external symbol (Win32) */
70     TYPE_FORWARD,      /* forwarded function (Win32) */
71     TYPE_NBTYPES
72 } ORD_TYPE;
73
74 static const char * const TypeNames[TYPE_NBTYPES] =
75 {
76     "byte",         /* TYPE_BYTE */
77     "word",         /* TYPE_WORD */
78     "long",         /* TYPE_LONG */
79     "pascal16",     /* TYPE_PASCAL_16 */
80     "pascal",       /* TYPE_PASCAL */
81     "equate",       /* TYPE_ABS */
82     "register",     /* TYPE_REGISTER */
83     "interrupt",    /* TYPE_INTERRUPT */
84     "stub",         /* TYPE_STUB */
85     "stdcall",      /* TYPE_STDCALL */
86     "cdecl",        /* TYPE_CDECL */
87     "varargs",      /* TYPE_VARARGS */
88     "extern",       /* TYPE_EXTERN */
89     "forward"       /* TYPE_FORWARD */
90 };
91
92 #define MAX_ORDINALS    2048
93 #define MAX_IMPORTS       16
94
95   /* Callback function used for stub functions */
96 #define STUB_CALLBACK \
97   ((SpecType == SPEC_WIN16) ? "RELAY_Unimplemented16": "RELAY_Unimplemented32")
98
99 typedef enum
100 {
101     SPEC_INVALID,
102     SPEC_WIN16,
103     SPEC_WIN32
104 } SPEC_TYPE;
105
106 typedef enum
107 {
108     SPEC_MODE_DLL,
109     SPEC_MODE_GUIEXE,
110     SPEC_MODE_CUIEXE
111 } SPEC_MODE;
112
113 typedef struct
114 {
115     int n_values;
116     int *values;
117 } ORD_VARIABLE;
118
119 typedef struct
120 {
121     int  n_args;
122     char arg_types[32];
123     char link_name[80];
124 } ORD_FUNCTION;
125
126 typedef struct
127 {
128     int value;
129 } ORD_ABS;
130
131 typedef struct
132 {
133     char link_name[80];
134 } ORD_EXTERN;
135
136 typedef struct
137 {
138     char link_name[80];
139 } ORD_FORWARD;
140
141 typedef struct
142 {
143     ORD_TYPE    type;
144     int         ordinal;
145     int         offset;
146     int         lineno;
147     char        name[80];
148     union
149     {
150         ORD_VARIABLE   var;
151         ORD_FUNCTION   func;
152         ORD_ABS        abs;
153         ORD_EXTERN     ext;
154         ORD_FORWARD    fwd;
155     } u;
156 } ORDDEF;
157
158 static ORDDEF EntryPoints[MAX_ORDINALS];
159 static ORDDEF *Ordinals[MAX_ORDINALS];
160 static ORDDEF *Names[MAX_ORDINALS];
161
162 static SPEC_TYPE SpecType = SPEC_INVALID;
163 static SPEC_MODE SpecMode = SPEC_MODE_DLL;
164 static char DLLName[80];
165 static char DLLFileName[80];
166 static int Limit = 0;
167 static int Base = MAX_ORDINALS;
168 static int DLLHeapSize = 0;
169 static FILE *SpecFp;
170 static WORD Code_Selector, Data_Selector;
171 static char DLLInitFunc[80];
172 static char *DLLImports[MAX_IMPORTS];
173 static char rsrc_name[80];
174 static int nb_imports;
175 static int nb_entry_points;
176 static int nb_names;
177 static const char *input_file_name;
178 static const char *output_file_name;
179
180 char *ParseBuffer = NULL;
181 char *ParseNext;
182 char ParseSaveChar;
183 int Line;
184
185 static int UsePIC = 0;
186
187 static int debugging = 1;
188
189   /* Offset of a structure field relative to the start of the struct */
190 #define STRUCTOFFSET(type,field) ((int)&((type *)0)->field)
191
192   /* Offset of register relative to the start of the CONTEXT struct */
193 #define CONTEXTOFFSET(reg)  STRUCTOFFSET(CONTEXT86,reg)
194
195   /* Offset of register relative to the start of the STACK16FRAME struct */
196 #define STACK16OFFSET(reg)  STRUCTOFFSET(STACK16FRAME,reg)
197
198   /* Offset of register relative to the start of the STACK32FRAME struct */
199 #define STACK32OFFSET(reg)  STRUCTOFFSET(STACK32FRAME,reg)
200
201   /* Offset of the stack pointer relative to %fs:(0) */
202 #define STACKOFFSET (STRUCTOFFSET(TEB,cur_stack))
203
204 static void BuildCallFrom16Func( FILE *outfile, char *profile, char *prefix, int local );
205
206 static void *xmalloc (size_t size)
207 {
208     void *res;
209
210     res = malloc (size ? size : 1);
211     if (res == NULL)
212     {
213         fprintf (stderr, "Virtual memory exhausted.\n");
214         if (output_file_name) unlink( output_file_name );
215         exit (1);
216     }
217     return res;
218 }
219
220
221 static void *xrealloc (void *ptr, size_t size)
222 {
223     void *res = realloc (ptr, size);
224     if (res == NULL)
225     {
226         fprintf (stderr, "Virtual memory exhausted.\n");
227         if (output_file_name) unlink( output_file_name );
228         exit (1);
229     }
230     return res;
231 }
232
233 static char *xstrdup( const char *str )
234 {
235     char *res = strdup( str );
236     if (!res)
237     {
238         fprintf (stderr, "Virtual memory exhausted.\n");
239         if (output_file_name) unlink( output_file_name );
240         exit (1);
241     }
242     return res;
243 }
244
245 static void fatal_error( const char *msg, ... )
246 {
247     va_list valist;
248     va_start( valist, msg );
249     fprintf( stderr, "%s:%d: ", input_file_name, Line );
250     vfprintf( stderr, msg, valist );
251     va_end( valist );
252     if (output_file_name) unlink( output_file_name );
253     exit(1);
254 }
255
256 static int IsNumberString(char *s)
257 {
258     while (*s != '\0')
259         if (!isdigit(*s++))
260             return 0;
261
262     return 1;
263 }
264
265 static char *strupper(char *s)
266 {
267     char *p;
268     
269     for(p = s; *p != '\0'; p++)
270         *p = toupper(*p);
271
272     return s;
273 }
274
275 static char * GetTokenInLine(void)
276 {
277     char *p;
278     char *token;
279
280     if (ParseNext != ParseBuffer)
281     {
282         if (ParseSaveChar == '\0')
283             return NULL;
284         *ParseNext = ParseSaveChar;
285     }
286     
287     /*
288      * Remove initial white space.
289      */
290     for (p = ParseNext; isspace(*p); p++)
291         ;
292     
293     if ((*p == '\0') || (*p == '#'))
294         return NULL;
295     
296     /*
297      * Find end of token.
298      */
299     token = p++;
300     if (*token != '(' && *token != ')')
301         while (*p != '\0' && *p != '(' && *p != ')' && !isspace(*p))
302             p++;
303     
304     ParseSaveChar = *p;
305     ParseNext = p;
306     *p = '\0';
307
308     return token;
309 }
310
311 static char * GetToken(void)
312 {
313     char *token;
314
315     if (ParseBuffer == NULL)
316     {
317         ParseBuffer = xmalloc(512);
318         ParseNext = ParseBuffer;
319         while (1)
320         {
321             Line++;
322             if (fgets(ParseBuffer, 511, SpecFp) == NULL)
323                 return NULL;
324             if (ParseBuffer[0] != '#')
325                 break;
326         }
327     }
328
329     while ((token = GetTokenInLine()) == NULL)
330     {
331         ParseNext = ParseBuffer;
332         while (1)
333         {
334             Line++;
335             if (fgets(ParseBuffer, 511, SpecFp) == NULL)
336                 return NULL;
337             if (ParseBuffer[0] != '#')
338                 break;
339         }
340     }
341
342     return token;
343 }
344
345
346 static int name_compare( const void *name1, const void *name2 )
347 {
348     ORDDEF *odp1 = *(ORDDEF **)name1;
349     ORDDEF *odp2 = *(ORDDEF **)name2;
350     return strcmp( odp1->name, odp2->name );
351 }
352
353 /*******************************************************************
354  *         AssignOrdinals
355  *
356  * Assign ordinals to all entry points.
357  */
358 static void AssignOrdinals(void)
359 {
360     int i, ordinal;
361
362     if ( !nb_names ) return;
363
364     /* sort the list of names */
365     qsort( Names, nb_names, sizeof(Names[0]), name_compare );
366
367     /* check for duplicate names */
368     for (i = 0; i < nb_names - 1; i++)
369     {
370         if (!strcmp( Names[i]->name, Names[i+1]->name ))
371         {
372             Line = max( Names[i]->lineno, Names[i+1]->lineno );
373             fatal_error( "'%s' redefined (previous definition at line %d)\n",
374                          Names[i]->name, min( Names[i]->lineno, Names[i+1]->lineno ) );
375         }
376     }
377
378     /* start assigning from Base, or from 1 if no ordinal defined yet */
379     if (Base == MAX_ORDINALS) Base = 1;
380     for (i = 0, ordinal = Base; i < nb_names; i++)
381     {
382         if (Names[i]->ordinal != -1) continue;  /* already has an ordinal */
383         while (Ordinals[ordinal]) ordinal++;
384         if (ordinal >= MAX_ORDINALS)
385         {
386             Line = Names[i]->lineno;
387             fatal_error( "Too many functions defined (max %d)\n", MAX_ORDINALS );
388         }
389         Names[i]->ordinal = ordinal;
390         Ordinals[ordinal] = Names[i];
391     }
392     if (ordinal > Limit) Limit = ordinal;
393 }
394
395
396 /*******************************************************************
397  *         ParseVariable
398  *
399  * Parse a variable definition.
400  */
401 static void ParseVariable( ORDDEF *odp )
402 {
403     char *endptr;
404     int *value_array;
405     int n_values;
406     int value_array_size;
407     
408     char *token = GetToken();
409     if (*token != '(') fatal_error( "Expected '(' got '%s'\n", token );
410
411     n_values = 0;
412     value_array_size = 25;
413     value_array = xmalloc(sizeof(*value_array) * value_array_size);
414     
415     while ((token = GetToken()) != NULL)
416     {
417         if (*token == ')')
418             break;
419
420         value_array[n_values++] = strtol(token, &endptr, 0);
421         if (n_values == value_array_size)
422         {
423             value_array_size += 25;
424             value_array = xrealloc(value_array, 
425                                    sizeof(*value_array) * value_array_size);
426         }
427         
428         if (endptr == NULL || *endptr != '\0')
429             fatal_error( "Expected number value, got '%s'\n", token );
430     }
431     
432     if (token == NULL)
433         fatal_error( "End of file in variable declaration\n" );
434
435     odp->u.var.n_values = n_values;
436     odp->u.var.values = xrealloc(value_array, sizeof(*value_array) * n_values);
437 }
438
439
440 /*******************************************************************
441  *         ParseExportFunction
442  *
443  * Parse a function definition.
444  */
445 static void ParseExportFunction( ORDDEF *odp )
446 {
447     char *token;
448     int i;
449
450     switch(SpecType)
451     {
452     case SPEC_WIN16:
453         if (odp->type == TYPE_STDCALL)
454             fatal_error( "'stdcall' not supported for Win16\n" );
455         if (odp->type == TYPE_VARARGS)
456             fatal_error( "'varargs' not supported for Win16\n" );
457         break;
458     case SPEC_WIN32:
459         if ((odp->type == TYPE_PASCAL) || (odp->type == TYPE_PASCAL_16))
460             fatal_error( "'pascal' not supported for Win32\n" );
461         break;
462     default:
463         break;
464     }
465
466     token = GetToken();
467     if (*token != '(') fatal_error( "Expected '(' got '%s'\n", token );
468
469     for (i = 0; i < sizeof(odp->u.func.arg_types)-1; i++)
470     {
471         token = GetToken();
472         if (*token == ')')
473             break;
474
475         if (!strcmp(token, "word"))
476             odp->u.func.arg_types[i] = 'w';
477         else if (!strcmp(token, "s_word"))
478             odp->u.func.arg_types[i] = 's';
479         else if (!strcmp(token, "long") || !strcmp(token, "segptr"))
480             odp->u.func.arg_types[i] = 'l';
481         else if (!strcmp(token, "ptr"))
482             odp->u.func.arg_types[i] = 'p';
483         else if (!strcmp(token, "str"))
484             odp->u.func.arg_types[i] = 't';
485         else if (!strcmp(token, "wstr"))
486             odp->u.func.arg_types[i] = 'W';
487         else if (!strcmp(token, "segstr"))
488             odp->u.func.arg_types[i] = 'T';
489         else if (!strcmp(token, "double"))
490         {
491             odp->u.func.arg_types[i++] = 'l';
492             odp->u.func.arg_types[i] = 'l';
493         }
494         else fatal_error( "Unknown variable type '%s'\n", token );
495
496         if (SpecType == SPEC_WIN32)
497         {
498             if (strcmp(token, "long") &&
499                 strcmp(token, "ptr") &&
500                 strcmp(token, "str") &&
501                 strcmp(token, "wstr") &&
502                 strcmp(token, "double"))
503             {
504                 fatal_error( "Type '%s' not supported for Win32\n", token );
505             }
506         }
507     }
508     if ((*token != ')') || (i >= sizeof(odp->u.func.arg_types)))
509         fatal_error( "Too many arguments\n" );
510
511     odp->u.func.arg_types[i] = '\0';
512     if ((odp->type == TYPE_STDCALL) && !i)
513         odp->type = TYPE_CDECL; /* stdcall is the same as cdecl for 0 args */
514     strcpy(odp->u.func.link_name, GetToken());
515 }
516
517
518 /*******************************************************************
519  *         ParseEquate
520  *
521  * Parse an 'equate' definition.
522  */
523 static void ParseEquate( ORDDEF *odp )
524 {
525     char *endptr;
526     
527     char *token = GetToken();
528     int value = strtol(token, &endptr, 0);
529     if (endptr == NULL || *endptr != '\0')
530         fatal_error( "Expected number value, got '%s'\n", token );
531     if (SpecType == SPEC_WIN32)
532         fatal_error( "'equate' not supported for Win32\n" );
533     odp->u.abs.value = value;
534 }
535
536
537 /*******************************************************************
538  *         ParseStub
539  *
540  * Parse a 'stub' definition.
541  */
542 static void ParseStub( ORDDEF *odp )
543 {
544     odp->u.func.arg_types[0] = '\0';
545     strcpy( odp->u.func.link_name, STUB_CALLBACK );
546 }
547
548
549 /*******************************************************************
550  *         ParseInterrupt
551  *
552  * Parse an 'interrupt' definition.
553  */
554 static void ParseInterrupt( ORDDEF *odp )
555 {
556     char *token;
557
558     if (SpecType == SPEC_WIN32)
559         fatal_error( "'interrupt' not supported for Win32\n" );
560
561     token = GetToken();
562     if (*token != '(') fatal_error( "Expected '(' got '%s'\n", token );
563
564     token = GetToken();
565     if (*token != ')') fatal_error( "Expected ')' got '%s'\n", token );
566
567     odp->u.func.arg_types[0] = '\0';
568     strcpy( odp->u.func.link_name, GetToken() );
569 }
570
571
572 /*******************************************************************
573  *         ParseExtern
574  *
575  * Parse an 'extern' definition.
576  */
577 static void ParseExtern( ORDDEF *odp )
578 {
579     if (SpecType == SPEC_WIN16) fatal_error( "'extern' not supported for Win16\n" );
580     strcpy( odp->u.ext.link_name, GetToken() );
581 }
582
583
584 /*******************************************************************
585  *         ParseForward
586  *
587  * Parse a 'forward' definition.
588  */
589 static void ParseForward( ORDDEF *odp )
590 {
591     if (SpecType == SPEC_WIN16) fatal_error( "'forward' not supported for Win16\n" );
592     strcpy( odp->u.fwd.link_name, GetToken() );
593 }
594
595
596 /*******************************************************************
597  *         ParseOrdinal
598  *
599  * Parse an ordinal definition.
600  */
601 static void ParseOrdinal(int ordinal)
602 {
603     char *token;
604
605     ORDDEF *odp = &EntryPoints[nb_entry_points++];
606
607     if (!(token = GetToken())) fatal_error( "Expected type after ordinal\n" );
608
609     for (odp->type = 0; odp->type < TYPE_NBTYPES; odp->type++)
610         if (TypeNames[odp->type] && !strcmp( token, TypeNames[odp->type] ))
611             break;
612
613     if (odp->type >= TYPE_NBTYPES)
614         fatal_error( "Expected type after ordinal, found '%s' instead\n", token );
615
616     if (!(token = GetToken())) fatal_error( "Expected name after type\n" );
617
618     strcpy( odp->name, token );
619     odp->lineno = Line;
620     odp->ordinal = ordinal;
621
622     switch(odp->type)
623     {
624     case TYPE_BYTE:
625     case TYPE_WORD:
626     case TYPE_LONG:
627         ParseVariable( odp );
628         break;
629     case TYPE_REGISTER:
630         ParseExportFunction( odp );
631 #ifndef __i386__
632         /* ignore Win32 'register' routines on non-Intel archs */
633         if (SpecType == SPEC_WIN32)
634         {
635             nb_entry_points--;
636             return;
637         }
638 #endif
639         break;
640     case TYPE_PASCAL_16:
641     case TYPE_PASCAL:
642     case TYPE_STDCALL:
643     case TYPE_VARARGS:
644     case TYPE_CDECL:
645         ParseExportFunction( odp );
646         break;
647     case TYPE_INTERRUPT:
648         ParseInterrupt( odp );
649         break;
650     case TYPE_ABS:
651         ParseEquate( odp );
652         break;
653     case TYPE_STUB:
654         ParseStub( odp );
655         break;
656     case TYPE_EXTERN:
657         ParseExtern( odp );
658         break;
659     case TYPE_FORWARD:
660         ParseForward( odp );
661         break;
662     default:
663         assert( 0 );
664     }
665
666     if (ordinal != -1)
667     {
668         if (ordinal >= MAX_ORDINALS) fatal_error( "Ordinal number %d too large\n", ordinal );
669         if (ordinal > Limit) Limit = ordinal;
670         if (ordinal < Base) Base = ordinal;
671         odp->ordinal = ordinal;
672         Ordinals[ordinal] = odp;
673     }
674
675     if (!strcmp( odp->name, "@" ))
676     {
677         if (ordinal == -1)
678             fatal_error( "Nameless function needs an explicit ordinal number\n" );
679         if (SpecType != SPEC_WIN32)
680             fatal_error( "Nameless functions not supported for Win16\n" );
681         odp->name[0] = 0;
682     }
683     else Names[nb_names++] = odp;
684 }
685
686
687 /*******************************************************************
688  *         ParseTopLevel
689  *
690  * Parse a spec file.
691  */
692 static void ParseTopLevel(void)
693 {
694     char *token;
695     
696     while ((token = GetToken()) != NULL)
697     {
698         if (strcmp(token, "name") == 0)
699         {
700             strcpy(DLLName, GetToken());
701         }
702         else if (strcmp(token, "file") == 0)
703         {
704             strcpy(DLLFileName, GetToken());
705             strupper(DLLFileName);
706         }
707         else if (strcmp(token, "type") == 0)
708         {
709             token = GetToken();
710             if (!strcmp(token, "win16" )) SpecType = SPEC_WIN16;
711             else if (!strcmp(token, "win32" )) SpecType = SPEC_WIN32;
712             else fatal_error( "Type must be 'win16' or 'win32'\n" );
713         }
714         else if (strcmp(token, "mode") == 0)
715         {
716             token = GetToken();
717             if (!strcmp(token, "dll" )) SpecMode = SPEC_MODE_DLL;
718             else if (!strcmp(token, "guiexe" )) SpecMode = SPEC_MODE_GUIEXE;
719             else if (!strcmp(token, "cuiexe" )) SpecMode = SPEC_MODE_CUIEXE;
720             else fatal_error( "Mode must be 'dll', 'guiexe' or 'cuiexe'\n" );
721         }
722         else if (strcmp(token, "heap") == 0)
723         {
724             token = GetToken();
725             if (!IsNumberString(token)) fatal_error( "Expected number after heap\n" );
726             DLLHeapSize = atoi(token);
727         }
728         else if (strcmp(token, "init") == 0)
729         {
730             strcpy(DLLInitFunc, GetToken());
731             if (SpecType == SPEC_WIN16)
732                 fatal_error( "init cannot be used for Win16 spec files\n" );
733             if (!DLLInitFunc[0])
734                 fatal_error( "Expected function name after init\n" );
735             if (!strcmp(DLLInitFunc, "main"))
736                 fatal_error( "The init function cannot be named 'main'\n" );
737         }
738         else if (strcmp(token, "import") == 0)
739         {
740             if (nb_imports >= MAX_IMPORTS)
741                 fatal_error( "Too many imports (limit %d)\n", MAX_IMPORTS );
742             if (SpecType != SPEC_WIN32)
743                 fatal_error( "Imports not supported for Win16\n" );
744             DLLImports[nb_imports++] = xstrdup(GetToken());
745         }
746         else if (strcmp(token, "rsrc") == 0)
747         {
748             strcpy( rsrc_name, GetToken() );
749             strcat( rsrc_name, "_ResourceDescriptor" );
750         }
751         else if (strcmp(token, "@") == 0)
752         {
753             if (SpecType != SPEC_WIN32)
754                 fatal_error( "'@' ordinals not supported for Win16\n" );
755             ParseOrdinal( -1 );
756         }
757         else if (IsNumberString(token))
758         {
759             ParseOrdinal( atoi(token) );
760         }
761         else
762             fatal_error( "Expected name, id, length or ordinal\n" );
763     }
764
765     if (!DLLFileName[0])
766     {
767         if (SpecMode == SPEC_MODE_DLL)
768             sprintf( DLLFileName, "%s.dll", DLLName );
769         else
770             sprintf( DLLFileName, "%s.exe", DLLName );
771     }
772 }
773
774
775 /*******************************************************************
776  *         StoreVariableCode
777  *
778  * Store a list of ints into a byte array.
779  */
780 static int StoreVariableCode( unsigned char *buffer, int size, ORDDEF *odp )
781 {
782     int i;
783
784     switch(size)
785     {
786     case 1:
787         for (i = 0; i < odp->u.var.n_values; i++)
788             buffer[i] = odp->u.var.values[i];
789         break;
790     case 2:
791         for (i = 0; i < odp->u.var.n_values; i++)
792             ((unsigned short *)buffer)[i] = odp->u.var.values[i];
793         break;
794     case 4:
795         for (i = 0; i < odp->u.var.n_values; i++)
796             ((unsigned int *)buffer)[i] = odp->u.var.values[i];
797         break;
798     }
799     return odp->u.var.n_values * size;
800 }
801
802
803 /*******************************************************************
804  *         DumpBytes
805  *
806  * Dump a byte stream into the assembly code.
807  */
808 static void DumpBytes( FILE *outfile, const unsigned char *data, int len,
809                        const char *label )
810 {
811     int i;
812
813     fprintf( outfile, "\nstatic BYTE %s[] = \n{", label );
814
815     for (i = 0; i < len; i++)
816     {
817         if (!(i & 0x0f)) fprintf( outfile, "\n    " );
818         fprintf( outfile, "%d", *data++ );
819         if (i < len - 1) fprintf( outfile, ", " );
820     }
821     fprintf( outfile, "\n};\n" );
822 }
823
824
825 /*******************************************************************
826  *         BuildModule16
827  *
828  * Build the in-memory representation of a 16-bit NE module, and dump it
829  * as a byte stream into the assembly code.
830  */
831 static int BuildModule16( FILE *outfile, int max_code_offset,
832                           int max_data_offset )
833 {
834     int i;
835     char *buffer;
836     NE_MODULE *pModule;
837     SEGTABLEENTRY *pSegment;
838     OFSTRUCT *pFileInfo;
839     BYTE *pstr;
840     WORD *pword;
841     ET_BUNDLE *bundle = 0;
842     ET_ENTRY *entry = 0;
843
844     /*   Module layout:
845      * NE_MODULE       Module
846      * OFSTRUCT        File information
847      * SEGTABLEENTRY   Segment 1 (code)
848      * SEGTABLEENTRY   Segment 2 (data)
849      * WORD[2]         Resource table (empty)
850      * BYTE[2]         Imported names (empty)
851      * BYTE[n]         Resident names table
852      * BYTE[n]         Entry table
853      */
854
855     buffer = xmalloc( 0x10000 );
856
857     pModule = (NE_MODULE *)buffer;
858     memset( pModule, 0, sizeof(*pModule) );
859     pModule->magic = IMAGE_OS2_SIGNATURE;
860     pModule->count = 1;
861     pModule->next = 0;
862     pModule->flags = NE_FFLAGS_SINGLEDATA | NE_FFLAGS_BUILTIN | NE_FFLAGS_LIBMODULE;
863     pModule->dgroup = 2;
864     pModule->heap_size = DLLHeapSize;
865     pModule->stack_size = 0;
866     pModule->ip = 0;
867     pModule->cs = 0;
868     pModule->sp = 0;
869     pModule->ss = 0;
870     pModule->seg_count = 2;
871     pModule->modref_count = 0;
872     pModule->nrname_size = 0;
873     pModule->modref_table = 0;
874     pModule->nrname_fpos = 0;
875     pModule->moveable_entries = 0;
876     pModule->alignment = 0;
877     pModule->truetype = 0;
878     pModule->os_flags = NE_OSFLAGS_WINDOWS;
879     pModule->misc_flags = 0;
880     pModule->dlls_to_init  = 0;
881     pModule->nrname_handle = 0;
882     pModule->min_swap_area = 0;
883     pModule->expected_version = 0;
884     pModule->module32 = 0;
885     pModule->self = 0;
886     pModule->self_loading_sel = 0;
887
888       /* File information */
889
890     pFileInfo = (OFSTRUCT *)(pModule + 1);
891     pModule->fileinfo = (int)pFileInfo - (int)pModule;
892     memset( pFileInfo, 0, sizeof(*pFileInfo) - sizeof(pFileInfo->szPathName) );
893     pFileInfo->cBytes = sizeof(*pFileInfo) - sizeof(pFileInfo->szPathName)
894                         + strlen(DLLFileName);
895     strcpy( pFileInfo->szPathName, DLLFileName );
896     pstr = (char *)pFileInfo + pFileInfo->cBytes + 1;
897         
898 #ifdef __i386__  /* FIXME: Alignment problems! */
899
900       /* Segment table */
901
902     pSegment = (SEGTABLEENTRY *)pstr;
903     pModule->seg_table = (int)pSegment - (int)pModule;
904     pSegment->filepos = 0;
905     pSegment->size = max_code_offset;
906     pSegment->flags = 0;
907     pSegment->minsize = max_code_offset;
908     pSegment->hSeg = 0;
909     pSegment++;
910
911     pModule->dgroup_entry = (int)pSegment - (int)pModule;
912     pSegment->filepos = 0;
913     pSegment->size = max_data_offset;
914     pSegment->flags = NE_SEGFLAGS_DATA;
915     pSegment->minsize = max_data_offset;
916     pSegment->hSeg = 0;
917     pSegment++;
918
919       /* Resource table */
920
921     pword = (WORD *)pSegment;
922     pModule->res_table = (int)pword - (int)pModule;
923     *pword++ = 0;
924     *pword++ = 0;
925
926       /* Imported names table */
927
928     pstr = (char *)pword;
929     pModule->import_table = (int)pstr - (int)pModule;
930     *pstr++ = 0;
931     *pstr++ = 0;
932
933       /* Resident names table */
934
935     pModule->name_table = (int)pstr - (int)pModule;
936     /* First entry is module name */
937     *pstr = strlen(DLLName );
938     strcpy( pstr + 1, DLLName );
939     pstr += *pstr + 1;
940     *(WORD *)pstr = 0;
941     pstr += sizeof(WORD);
942     /* Store all ordinals */
943     for (i = 1; i <= Limit; i++)
944     {
945         ORDDEF *odp = Ordinals[i];
946         if (!odp || !odp->name[0]) continue;
947         *pstr = strlen( odp->name );
948         strcpy( pstr + 1, odp->name );
949         strupper( pstr + 1 );
950         pstr += *pstr + 1;
951         *(WORD *)pstr = i;
952         pstr += sizeof(WORD);
953     }
954     *pstr++ = 0;
955
956       /* Entry table */
957
958     pModule->entry_table = (int)pstr - (int)pModule;
959     for (i = 1; i <= Limit; i++)
960     {
961         int selector = 0;
962         ORDDEF *odp = Ordinals[i];
963         if (!odp) continue;
964
965         switch (odp->type)
966         {
967         case TYPE_CDECL:
968         case TYPE_PASCAL:
969         case TYPE_PASCAL_16:
970         case TYPE_REGISTER:
971         case TYPE_INTERRUPT:
972         case TYPE_STUB:
973             selector = 1;  /* Code selector */
974             break;
975
976         case TYPE_BYTE:
977         case TYPE_WORD:
978         case TYPE_LONG:
979             selector = 2;  /* Data selector */
980             break;
981
982         case TYPE_ABS:
983             selector = 0xfe;  /* Constant selector */
984             break;
985
986         default:
987             selector = 0;  /* Invalid selector */
988             break;
989         }
990
991         if ( !selector )
992            continue;
993
994         if ( bundle && bundle->last+1 == i )
995             bundle->last++;
996         else
997         {
998             if ( bundle )
999                 bundle->next = (char *)pstr - (char *)pModule;
1000
1001             bundle = (ET_BUNDLE *)pstr;
1002             bundle->first = i-1;
1003             bundle->last = i;
1004             bundle->next = 0;
1005             pstr += sizeof(ET_BUNDLE);
1006         }
1007
1008         /* FIXME: is this really correct ?? */
1009         entry = (ET_ENTRY *)pstr;
1010         entry->type = 0xff;  /* movable */
1011         entry->flags = 3; /* exported & public data */
1012         entry->segnum = selector;
1013         entry->offs = odp->offset;
1014         pstr += sizeof(ET_ENTRY);
1015     }
1016     *pstr++ = 0;
1017 #endif
1018
1019       /* Dump the module content */
1020
1021     DumpBytes( outfile, (char *)pModule, (int)pstr - (int)pModule,
1022                "Module" );
1023     return (int)pstr - (int)pModule;
1024 }
1025
1026
1027 /*******************************************************************
1028  *         output_exports
1029  *
1030  * Output the export table for a Win32 module.
1031  */
1032 static void output_exports( FILE *outfile, int nr_exports, int nr_names, int fwd_size )
1033 {
1034     int i, fwd_pos = 0;
1035
1036     if (!nr_exports) return;
1037
1038     fprintf( outfile, "typedef void (*func_ptr)();\n" );
1039     fprintf( outfile, "static struct {\n" );
1040     fprintf( outfile, "  struct {\n" );
1041     fprintf( outfile, "    unsigned int    Characteristics;\n" );
1042     fprintf( outfile, "    unsigned int    TimeDateStamp;\n" );
1043     fprintf( outfile, "    unsigned short  MajorVersion;\n" );
1044     fprintf( outfile, "    unsigned short  MinorVersion;\n" );
1045     fprintf( outfile, "    const char     *Name;\n" );
1046     fprintf( outfile, "    unsigned int    Base;\n" );
1047     fprintf( outfile, "    unsigned int    NumberOfFunctions;\n" );
1048     fprintf( outfile, "    unsigned int    NumberOfNames;\n" );
1049     fprintf( outfile, "    func_ptr       *AddressOfFunctions;\n" );
1050     fprintf( outfile, "    const char    **AddressOfNames;\n" );
1051     fprintf( outfile, "    unsigned short *AddressOfNameOrdinals;\n" );
1052     fprintf( outfile, "    func_ptr        functions[%d];\n", nr_exports );
1053     if (nb_names)
1054     {
1055         fprintf( outfile, "    const char     *names[%d];\n", nb_names );
1056         fprintf( outfile, "    unsigned short  ordinals[%d];\n", nb_names );
1057         if (nb_names % 2) fprintf( outfile, "    unsigned short  pad1;\n" );
1058     }
1059     if (fwd_size)
1060     {
1061         fprintf( outfile, "    char            forwards[%d];\n", (fwd_size + 3) & ~3 );
1062     }
1063     fprintf( outfile, "  } exp;\n" );
1064
1065 #ifdef __i386__
1066     fprintf( outfile, "  struct {\n" );
1067     fprintf( outfile, "    unsigned char  jmp;\n" );
1068     fprintf( outfile, "    unsigned char  addr[4];\n" );
1069     fprintf( outfile, "    unsigned char  ret;\n" );
1070     fprintf( outfile, "    unsigned short args;\n" );
1071     fprintf( outfile, "    func_ptr       orig;\n" );
1072     fprintf( outfile, "    unsigned int   argtypes;\n" );
1073     fprintf( outfile, "  } relay[%d];\n", nr_exports );
1074 #endif  /* __i386__ */
1075
1076     fprintf( outfile, "} exports = {\n  {\n" );
1077     fprintf( outfile, "    0,\n" );                 /* Characteristics */
1078     fprintf( outfile, "    0,\n" );                 /* TimeDateStamp */
1079     fprintf( outfile, "    0,\n" );                 /* MajorVersion */
1080     fprintf( outfile, "    0,\n" );                 /* MinorVersion */
1081     fprintf( outfile, "    dllname,\n" );           /* Name */
1082     fprintf( outfile, "    %d,\n", Base );          /* Base */
1083     fprintf( outfile, "    %d,\n", nr_exports );    /* NumberOfFunctions */
1084     fprintf( outfile, "    %d,\n", nb_names );      /* NumberOfNames */
1085     fprintf( outfile, "    exports.exp.functions,\n" ); /* AddressOfFunctions */
1086     if (nb_names)
1087     {
1088         fprintf( outfile, "    exports.exp.names,\n" );     /* AddressOfNames */
1089         fprintf( outfile, "    exports.exp.ordinals,\n" );  /* AddressOfNameOrdinals */
1090     }
1091     else
1092     {
1093         fprintf( outfile, "    0,\n" );  /* AddressOfNames */
1094         fprintf( outfile, "    0,\n" );  /* AddressOfNameOrdinals */
1095     }
1096
1097     /* output the function addresses */
1098
1099     fprintf( outfile, "    {\n      " );
1100     for (i = Base; i <= Limit; i++)
1101     {
1102         ORDDEF *odp = Ordinals[i];
1103         if (!odp) fprintf( outfile, "0" );
1104         else switch(odp->type)
1105         {
1106         case TYPE_EXTERN:
1107             fprintf( outfile, "%s", odp->u.ext.link_name );
1108             break;
1109         case TYPE_STDCALL:
1110         case TYPE_VARARGS:
1111         case TYPE_CDECL:
1112             fprintf( outfile, "%s", odp->u.func.link_name);
1113             break;
1114         case TYPE_STUB:
1115             fprintf( outfile, "__stub_%d", i );
1116             break;
1117         case TYPE_REGISTER:
1118             fprintf( outfile, "__regs_%d", i );
1119             break;
1120         case TYPE_FORWARD:
1121             fprintf( outfile, "(func_ptr)&exports.exp.forwards[%d] /* %s */",
1122                      fwd_pos, odp->u.fwd.link_name );
1123             fwd_pos += strlen(odp->u.fwd.link_name) + 1;
1124             break;
1125         default:
1126             assert(0);
1127         }
1128         if (i < Limit) fprintf( outfile, ",\n      " );
1129         else fprintf( outfile, "\n    },\n" );
1130     }
1131
1132     if (nb_names)
1133     {
1134         /* output the function names */
1135
1136         fprintf( outfile, "    {\n" );
1137         for (i = 0; i < nb_names; i++)
1138         {
1139             if (i) fprintf( outfile, ",\n" );
1140             fprintf( outfile, "      \"%s\"", Names[i]->name );
1141         }
1142         fprintf( outfile, "\n    },\n" );
1143
1144         /* output the function ordinals */
1145
1146         fprintf( outfile, "    {\n     " );
1147         for (i = 0; i < nb_names; i++)
1148         {
1149             fprintf( outfile, "%4d", Names[i]->ordinal - Base );
1150             if (i < nb_names-1)
1151             {
1152                 fputc( ',', outfile );
1153                 if ((i % 8) == 7) fprintf( outfile, "\n     " );
1154             }
1155         }
1156         fprintf( outfile, "\n    },\n" );
1157         if (nb_names % 2) fprintf( outfile, "    0,\n" );
1158     }
1159
1160     /* output forwards */
1161
1162     if (fwd_size)
1163     {
1164         for (i = Base; i <= Limit; i++)
1165         {
1166             ORDDEF *odp = Ordinals[i];
1167             if (odp && odp->type == TYPE_FORWARD)
1168                 fprintf( outfile, "    \"%s\\0\"\n", odp->u.fwd.link_name );
1169         }
1170     }
1171
1172     /* output relays */
1173
1174 #ifdef __i386__
1175     fprintf( outfile, "  },\n  {\n" );
1176     for (i = Base; i <= Limit; i++)
1177     {
1178         ORDDEF *odp = Ordinals[i];
1179
1180         if (odp && ((odp->type == TYPE_STDCALL) ||
1181                     (odp->type == TYPE_CDECL) ||
1182                     (odp->type == TYPE_REGISTER)))
1183         {
1184             unsigned int j, mask = 0;
1185             for (j = 0; odp->u.func.arg_types[j]; j++)
1186             {
1187                 if (odp->u.func.arg_types[j] == 't') mask |= 1<< (j*2);
1188                 if (odp->u.func.arg_types[j] == 'W') mask |= 2<< (j*2);
1189             }
1190
1191             switch(odp->type)
1192             {
1193             case TYPE_STDCALL:
1194                 fprintf( outfile, "    { 0xe9, { 0,0,0,0 }, 0xc2, 0x%04x, %s, 0x%08x }",
1195                          strlen(odp->u.func.arg_types) * sizeof(int),
1196                          odp->u.func.link_name, mask );
1197                 break;
1198             case TYPE_CDECL:
1199                 fprintf( outfile, "    { 0xe9, { 0,0,0,0 }, 0xc3, 0x%04x, %s, 0x%08x }",
1200                          strlen(odp->u.func.arg_types) * sizeof(int),
1201                          odp->u.func.link_name, mask );
1202                 break;
1203             case TYPE_REGISTER:
1204                 fprintf( outfile, "    { 0xe9, { 0,0,0,0 }, 0xc3, 0x%04x, __regs_%d, 0x%08x }",
1205                          0x8000 | (strlen(odp->u.func.arg_types) * sizeof(int)), i, mask );
1206                 break;
1207             default:
1208                 assert(0);
1209             }
1210         }
1211         else fprintf( outfile, "    { 0, }" );
1212
1213         if (i < Limit) fprintf( outfile, ",\n" );
1214     }
1215 #endif  /* __i386__ */
1216
1217     fprintf( outfile, "  }\n};\n" );
1218 }
1219
1220
1221 /*******************************************************************
1222  *         BuildSpec32File
1223  *
1224  * Build a Win32 C file from a spec file.
1225  */
1226 static int BuildSpec32File( FILE *outfile )
1227 {
1228     ORDDEF *odp;
1229     int i, fwd_size = 0, have_regs = FALSE;
1230     int nr_exports;
1231     const char *init_func;
1232
1233     AssignOrdinals();
1234     nr_exports = Base <= Limit ? Limit - Base + 1 : 0;
1235
1236     fprintf( outfile, "/* File generated automatically from %s; do not edit! */\n\n",
1237              input_file_name );
1238     fprintf( outfile, "#include \"builtin32.h\"\n\n" );
1239
1240     /* Reserve some space for the PE header */
1241
1242     fprintf( outfile, "extern char pe_header[];\n" );
1243     fprintf( outfile, "asm(\".section .text\\n\\t\"\n" );
1244     fprintf( outfile, "    \".align 4096\\n\"\n" );
1245     fprintf( outfile, "    \"pe_header:\\t.fill 4096,1,0\\n\\t\");\n" );
1246
1247     fprintf( outfile, "static const char dllname[] = \"%s\";\n", DLLName );
1248
1249     /* Output the DLL functions prototypes */
1250
1251     for (i = 0, odp = EntryPoints; i < nb_entry_points; i++, odp++)
1252     {
1253         switch(odp->type)
1254         {
1255         case TYPE_EXTERN:
1256             fprintf( outfile, "extern void %s();\n", odp->u.ext.link_name );
1257             break;
1258         case TYPE_STDCALL:
1259         case TYPE_VARARGS:
1260         case TYPE_CDECL:
1261             fprintf( outfile, "extern void %s();\n", odp->u.func.link_name );
1262             break;
1263         case TYPE_FORWARD:
1264             fwd_size += strlen(odp->u.fwd.link_name) + 1;
1265             break;
1266         case TYPE_REGISTER:
1267             fprintf( outfile, "extern void __regs_%d();\n", odp->ordinal );
1268             have_regs = TRUE;
1269             break;
1270         case TYPE_STUB:
1271             if (odp->name[0])
1272                 fprintf( outfile,
1273                          "static void __stub_%d() { BUILTIN32_Unimplemented(dllname,\"%s\"); }\n",
1274                          odp->ordinal, odp->name );
1275             else
1276                 fprintf( outfile,
1277                          "static void __stub_%d() { BUILTIN32_Unimplemented(dllname,\"%d\"); }\n",
1278                          odp->ordinal, odp->ordinal );
1279             
1280             break;
1281         default:
1282             fprintf(stderr,"build: function type %d not available for Win32\n",
1283                     odp->type);
1284             return -1;
1285         }
1286     }
1287
1288     /* Output code for all register functions */
1289
1290     if ( have_regs )
1291     { 
1292         fprintf( outfile, "#ifndef __GNUC__\n" );
1293         fprintf( outfile, "static void __asm__dummy(void) {\n" );
1294         fprintf( outfile, "#endif /* !defined(__GNUC__) */\n" );
1295         for (i = 0, odp = EntryPoints; i < nb_entry_points; i++, odp++)
1296         {
1297             if (odp->type != TYPE_REGISTER) continue;
1298             fprintf( outfile,
1299                      "asm(\".align 4\\n\\t\"\n"
1300                      "    \".type " PREFIX "__regs_%d,@function\\n\\t\"\n"
1301                      "    \"" PREFIX "__regs_%d:\\n\\t\"\n"
1302                      "    \"call " PREFIX "CALL32_Regs\\n\\t\"\n"
1303                      "    \".long " PREFIX "%s\\n\\t\"\n"
1304                      "    \".byte %d,%d\");\n",
1305                      odp->ordinal, odp->ordinal, odp->u.func.link_name,
1306                      4 * strlen(odp->u.func.arg_types),
1307                      4 * strlen(odp->u.func.arg_types) );
1308         }
1309         fprintf( outfile, "#ifndef __GNUC__\n" );
1310         fprintf( outfile, "}\n" );
1311         fprintf( outfile, "#endif /* !defined(__GNUC__) */\n" );
1312     }
1313
1314     /* Output the exports and relay entry points */
1315
1316     output_exports( outfile, nr_exports, nb_names, fwd_size );
1317
1318     /* Output the DLL imports */
1319
1320     if (nb_imports)
1321     {
1322         fprintf( outfile, "static const char * const Imports[%d] =\n{\n", nb_imports );
1323         for (i = 0; i < nb_imports; i++)
1324         {
1325             fprintf( outfile, "    \"%s\"", DLLImports[i] );
1326             if (i < nb_imports-1) fprintf( outfile, ",\n" );
1327         }
1328         fprintf( outfile, "\n};\n\n" );
1329     }
1330
1331     /* Output LibMain function */
1332
1333     init_func = DLLInitFunc[0] ? DLLInitFunc : NULL;
1334     switch(SpecMode)
1335     {
1336     case SPEC_MODE_DLL:
1337         if (init_func) fprintf( outfile, "extern void %s();\n", init_func );
1338         break;
1339     case SPEC_MODE_GUIEXE:
1340         if (!init_func) init_func = "WinMain";
1341         fprintf( outfile,
1342                  "\n#include <winbase.h>\n"
1343                  "static void exe_main(void)\n"
1344                  "{\n"
1345                  "    extern int PASCAL %s(HINSTANCE,HINSTANCE,LPCSTR,INT);\n"
1346                  "    STARTUPINFOA info;\n"
1347                  "    const char *cmdline = GetCommandLineA();\n"
1348                  "    while (*cmdline && *cmdline != ' ') cmdline++;\n"
1349                  "    if (*cmdline) cmdline++;\n"
1350                  "    GetStartupInfoA( &info );\n"
1351                  "    if (!(info.dwFlags & STARTF_USESHOWWINDOW)) info.wShowWindow = 1;\n"
1352                  "    ExitProcess( %s( GetModuleHandleA(0), 0, cmdline, info.wShowWindow ) );\n"
1353                  "}\n\n", init_func, init_func );
1354         fprintf( outfile,
1355                  "int main( int argc, char *argv[] )\n"
1356                  "{\n"
1357                  "    extern void PROCESS_InitWinelib( int, char ** );\n"
1358                  "    PROCESS_InitWinelib( argc, argv );\n"
1359                  "    return 1;\n"
1360                  "}\n\n" );
1361         init_func = "exe_main";
1362         break;
1363     case SPEC_MODE_CUIEXE:
1364         if (!init_func) init_func = "wine_main";
1365         fprintf( outfile,
1366                  "\n#include <winbase.h>\n"
1367                  "static void exe_main(void)\n"
1368                  "{\n"
1369                  "    extern int %s( int argc, char *argv[] );\n"
1370                  "    extern int _ARGC;\n"
1371                  "    extern char **_ARGV;\n"
1372                  "    ExitProcess( %s( _ARGC, _ARGV ) );\n"
1373                  "}\n\n", init_func, init_func );
1374         fprintf( outfile,
1375                  "int main( int argc, char *argv[] )\n"
1376                  "{\n"
1377                  "    extern void PROCESS_InitWinelib( int, char ** );\n"
1378                  "    PROCESS_InitWinelib( argc, argv );\n"
1379                  "    return 1;\n"
1380                  "}\n\n" );
1381         init_func = "exe_main";
1382         break;
1383     }
1384
1385     /* Output the DLL descriptor */
1386
1387     if (rsrc_name[0]) fprintf( outfile, "extern char %s[];\n\n", rsrc_name );
1388
1389     fprintf( outfile, "static const BUILTIN32_DESCRIPTOR descriptor =\n{\n" );
1390     fprintf( outfile, "    \"%s\",\n", DLLFileName );
1391     fprintf( outfile, "    %d,\n", nb_imports );
1392     fprintf( outfile, "    pe_header,\n" );
1393     fprintf( outfile, "    %s,\n", nr_exports ? "&exports" : "0" );
1394     fprintf( outfile, "    %s,\n", nr_exports ? "sizeof(exports.exp)" : "0" );
1395     fprintf( outfile, "    %s,\n", nb_imports ? "Imports" : "0" );
1396     fprintf( outfile, "    %s,\n", init_func ? init_func : "0" );
1397     fprintf( outfile, "    %d,\n", SpecMode == SPEC_MODE_DLL ? IMAGE_FILE_DLL : 0 );
1398     fprintf( outfile, "    %s\n", rsrc_name[0] ? rsrc_name : "0" );
1399     fprintf( outfile, "};\n" );
1400
1401     /* Output the DLL constructor */
1402
1403     fprintf( outfile, "#ifdef __GNUC__\n" );
1404     fprintf( outfile, "static void %s_init(void) __attribute__((constructor));\n", DLLName );
1405     fprintf( outfile, "#else /* defined(__GNUC__) */\n" );
1406     fprintf( outfile, "static void __asm__dummy_dll_init(void) {\n" );
1407     fprintf( outfile, "asm(\"\\t.section\t.init ,\\\"ax\\\"\\n\"\n" );
1408     fprintf( outfile, "    \"\\tcall %s_init\\n\"\n", DLLName );
1409     fprintf( outfile, "    \"\\t.previous\\n\");\n" );
1410     fprintf( outfile, "}\n" );
1411     fprintf( outfile, "#endif /* defined(__GNUC__) */\n" );
1412     fprintf( outfile, "static void %s_init(void) { BUILTIN32_RegisterDLL( &descriptor ); }\n",
1413              DLLName );
1414
1415     return 0;
1416 }
1417
1418 /*******************************************************************
1419  *         Spec16TypeCompare
1420  */
1421 static int Spec16TypeCompare( const void *e1, const void *e2 )
1422 {
1423     const ORDDEF *odp1 = *(const ORDDEF **)e1;
1424     const ORDDEF *odp2 = *(const ORDDEF **)e2;
1425
1426     int type1 = (odp1->type == TYPE_CDECL) ? 0
1427               : (odp1->type == TYPE_REGISTER) ? 3
1428               : (odp1->type == TYPE_INTERRUPT) ? 4
1429               : (odp1->type == TYPE_PASCAL_16) ? 1 : 2;
1430
1431     int type2 = (odp2->type == TYPE_CDECL) ? 0
1432               : (odp2->type == TYPE_REGISTER) ? 3
1433               : (odp2->type == TYPE_INTERRUPT) ? 4
1434               : (odp2->type == TYPE_PASCAL_16) ? 1 : 2;
1435
1436     int retval = type1 - type2;
1437     if ( !retval )
1438         retval = strcmp( odp1->u.func.arg_types, odp2->u.func.arg_types );
1439
1440     return retval;
1441 }
1442
1443 /*******************************************************************
1444  *         BuildSpec16File
1445  *
1446  * Build a Win16 assembly file from a spec file.
1447  */
1448 static int BuildSpec16File( FILE *outfile )
1449 {
1450     ORDDEF **type, **typelist;
1451     int i, nFuncs, nTypes;
1452     int code_offset, data_offset, module_size;
1453     unsigned char *data;
1454
1455     /* File header */
1456
1457     fprintf( outfile, "/* File generated automatically from %s; do not edit! */\n\n",
1458              input_file_name );
1459     fprintf( outfile, "#define __FLATCS__ 0x%04x\n", Code_Selector );
1460     fprintf( outfile, "#include \"builtin16.h\"\n\n" );
1461
1462     data = (unsigned char *)xmalloc( 0x10000 );
1463     memset( data, 0, 16 );
1464     data_offset = 16;
1465     strupper( DLLName );
1466
1467     /* Build sorted list of all argument types, without duplicates */
1468
1469     typelist = (ORDDEF **)calloc( Limit+1, sizeof(ORDDEF *) );
1470
1471     for (i = nFuncs = 0; i <= Limit; i++)
1472     {
1473         ORDDEF *odp = Ordinals[i];
1474         if (!odp) continue;
1475         switch (odp->type)
1476         {
1477           case TYPE_REGISTER:
1478           case TYPE_INTERRUPT:
1479           case TYPE_CDECL:
1480           case TYPE_PASCAL:
1481           case TYPE_PASCAL_16:
1482           case TYPE_STUB:
1483             typelist[nFuncs++] = odp;
1484
1485           default:
1486             break;
1487         }
1488     }
1489
1490     qsort( typelist, nFuncs, sizeof(ORDDEF *), Spec16TypeCompare );
1491
1492     i = nTypes = 0;
1493     while ( i < nFuncs )
1494     {
1495         typelist[nTypes++] = typelist[i++];
1496         while ( i < nFuncs && Spec16TypeCompare( typelist + i, typelist + nTypes-1 ) == 0 )
1497             i++;
1498     }
1499
1500     /* Output CallFrom16 routines needed by this .spec file */
1501
1502     for ( i = 0; i < nTypes; i++ )
1503     {
1504         char profile[101];
1505
1506         sprintf( profile, "%s_%s_%s",
1507                  (typelist[i]->type == TYPE_CDECL) ? "c" : "p",
1508                  (typelist[i]->type == TYPE_REGISTER) ? "regs" :
1509                  (typelist[i]->type == TYPE_INTERRUPT) ? "intr" :
1510                  (typelist[i]->type == TYPE_PASCAL_16) ? "word" : "long",
1511                  typelist[i]->u.func.arg_types );
1512
1513         BuildCallFrom16Func( outfile, profile, DLLName, TRUE );
1514     }
1515
1516     /* Output the DLL functions prototypes */
1517
1518     for (i = 0; i <= Limit; i++)
1519     {
1520         ORDDEF *odp = Ordinals[i];
1521         if (!odp) continue;
1522         switch(odp->type)
1523         {
1524         case TYPE_REGISTER:
1525         case TYPE_INTERRUPT:
1526         case TYPE_CDECL:
1527         case TYPE_PASCAL:
1528         case TYPE_PASCAL_16:
1529             fprintf( outfile, "extern void %s();\n", odp->u.func.link_name );
1530             break;
1531         default:
1532             break;
1533         }
1534     }
1535
1536     /* Output code segment */
1537
1538     fprintf( outfile, "\nstatic struct\n{\n    CALLFROM16   call[%d];\n"
1539                       "    ENTRYPOINT16 entry[%d];\n} Code_Segment = \n{\n    {\n",
1540                       nTypes, nFuncs );
1541     code_offset = 0;
1542
1543     for ( i = 0; i < nTypes; i++ )
1544     {
1545         char profile[101], *arg;
1546         int argsize = 0;
1547
1548         sprintf( profile, "%s_%s_%s", 
1549                           (typelist[i]->type == TYPE_CDECL) ? "c" : "p",
1550                           (typelist[i]->type == TYPE_REGISTER) ? "regs" :
1551                           (typelist[i]->type == TYPE_INTERRUPT) ? "intr" :
1552                           (typelist[i]->type == TYPE_PASCAL_16) ? "word" : "long",
1553                           typelist[i]->u.func.arg_types );
1554
1555         if ( typelist[i]->type != TYPE_CDECL )
1556             for ( arg = typelist[i]->u.func.arg_types; *arg; arg++ )
1557                 switch ( *arg )
1558                 {
1559                 case 'w':  /* word */
1560                 case 's':  /* s_word */
1561                     argsize += 2;
1562                     break;
1563         
1564                 case 'l':  /* long or segmented pointer */
1565                 case 'T':  /* segmented pointer to null-terminated string */
1566                 case 'p':  /* linear pointer */
1567                 case 't':  /* linear pointer to null-terminated string */
1568                     argsize += 4;
1569                     break;
1570                 }
1571
1572         if ( typelist[i]->type == TYPE_INTERRUPT )
1573             argsize += 2;
1574
1575         fprintf( outfile, "        CF16_%s( %s_CallFrom16_%s, %d, \"%s\" ),\n",
1576                  (   typelist[i]->type == TYPE_REGISTER 
1577                   || typelist[i]->type == TYPE_INTERRUPT)? "REGS":
1578                  typelist[i]->type == TYPE_PASCAL_16? "WORD" : "LONG",
1579                  DLLName, profile, argsize, profile );
1580
1581         code_offset += sizeof(CALLFROM16);
1582     }
1583     fprintf( outfile, "    },\n    {\n" );
1584
1585     for (i = 0; i <= Limit; i++)
1586     {
1587         ORDDEF *odp = Ordinals[i];
1588         if (!odp) continue;
1589         switch (odp->type)
1590         {
1591           case TYPE_ABS:
1592             odp->offset = LOWORD(odp->u.abs.value);
1593             break;
1594
1595           case TYPE_BYTE:
1596             odp->offset = data_offset;
1597             data_offset += StoreVariableCode( data + data_offset, 1, odp);
1598             break;
1599
1600           case TYPE_WORD:
1601             odp->offset = data_offset;
1602             data_offset += StoreVariableCode( data + data_offset, 2, odp);
1603             break;
1604
1605           case TYPE_LONG:
1606             odp->offset = data_offset;
1607             data_offset += StoreVariableCode( data + data_offset, 4, odp);
1608             break;
1609
1610           case TYPE_REGISTER:
1611           case TYPE_INTERRUPT:
1612           case TYPE_CDECL:
1613           case TYPE_PASCAL:
1614           case TYPE_PASCAL_16:
1615           case TYPE_STUB:
1616             type = bsearch( &odp, typelist, nTypes, sizeof(ORDDEF *), Spec16TypeCompare );
1617             assert( type );
1618
1619             fprintf( outfile, "        /* %s.%d */ ", DLLName, i );
1620             fprintf( outfile, "EP( %s, %d /* %s_%s_%s */ ),\n",
1621                               odp->u.func.link_name,
1622                               (type-typelist)*sizeof(CALLFROM16) - 
1623                               (code_offset + sizeof(ENTRYPOINT16)),
1624                               (odp->type == TYPE_CDECL) ? "c" : "p",
1625                               (odp->type == TYPE_REGISTER) ? "regs" :
1626                               (odp->type == TYPE_INTERRUPT) ? "intr" :
1627                               (odp->type == TYPE_PASCAL_16) ? "word" : "long",
1628                               odp->u.func.arg_types );
1629                                  
1630             odp->offset = code_offset;
1631             code_offset += sizeof(ENTRYPOINT16);
1632             break;
1633                 
1634           default:
1635             fprintf(stderr,"build: function type %d not available for Win16\n",
1636                     odp->type);
1637             return -1;
1638         }
1639     }
1640
1641     fprintf( outfile, "    }\n};\n" );
1642
1643     /* Output data segment */
1644
1645     DumpBytes( outfile, data, data_offset, "Data_Segment" );
1646
1647     /* Build the module */
1648
1649     module_size = BuildModule16( outfile, code_offset, data_offset );
1650
1651     /* Output the DLL descriptor */
1652
1653     if (rsrc_name[0]) fprintf( outfile, "extern const char %s[];\n\n", rsrc_name );
1654
1655     fprintf( outfile, "\nstatic const BUILTIN16_DESCRIPTOR descriptor = \n{\n" );
1656     fprintf( outfile, "    \"%s\",\n", DLLName );
1657     fprintf( outfile, "    Module,\n" );
1658     fprintf( outfile, "    sizeof(Module),\n" );
1659     fprintf( outfile, "    (BYTE *)&Code_Segment,\n" );
1660     fprintf( outfile, "    (BYTE *)Data_Segment,\n" );
1661     fprintf( outfile, "    %s\n", rsrc_name[0] ? rsrc_name : "0" );
1662     fprintf( outfile, "};\n" );
1663     
1664     /* Output the DLL constructor */
1665
1666     fprintf( outfile, "#ifdef __GNUC__\n" );
1667     fprintf( outfile, "static void %s_init(void) __attribute__((constructor));\n", DLLName );
1668     fprintf( outfile, "#else /* defined(__GNUC__) */\n" );
1669     fprintf( outfile, "static void __asm__dummy_dll_init(void) {\n" );
1670     fprintf( outfile, "asm(\"\\t.section\t.init ,\\\"ax\\\"\\n\"\n" );
1671     fprintf( outfile, "    \"\\tcall %s_init\\n\"\n", DLLName );
1672     fprintf( outfile, "    \"\\t.previous\\n\");\n" );
1673     fprintf( outfile, "}\n" );
1674     fprintf( outfile, "#endif /* defined(__GNUC__) */\n" );
1675     fprintf( outfile, "static void %s_init(void) { BUILTIN_RegisterDLL( &descriptor ); }\n",
1676              DLLName );
1677
1678     return 0;
1679 }
1680
1681
1682 /*******************************************************************
1683  *         BuildSpecFile
1684  *
1685  * Build an assembly file from a spec file.
1686  */
1687 static void BuildSpecFile( FILE *outfile, FILE *infile )
1688 {
1689     SpecFp = infile;
1690     ParseTopLevel();
1691
1692     switch(SpecType)
1693     {
1694     case SPEC_WIN16:
1695         BuildSpec16File( outfile );
1696         break;
1697     case SPEC_WIN32:
1698         BuildSpec32File( outfile );
1699         break;
1700     default:
1701         fatal_error( "Missing 'type' declaration\n" );
1702     }
1703 }
1704
1705
1706 /*******************************************************************
1707  *         BuildCallFrom16Func
1708  *
1709  * Build a 16-bit-to-Wine callback glue function. 
1710  *
1711  * The generated routines are intended to be used as argument conversion 
1712  * routines to be called by the CallFrom16... core. Thus, the prototypes of
1713  * the generated routines are (see also CallFrom16):
1714  *
1715  *  extern WORD WINAPI PREFIX_CallFrom16_C_word_xxx( FARPROC func, LPBYTE args );
1716  *  extern LONG WINAPI PREFIX_CallFrom16_C_long_xxx( FARPROC func, LPBYTE args );
1717  *  extern void WINAPI PREFIX_CallFrom16_C_regs_xxx( FARPROC func, LPBYTE args, 
1718  *                                                   CONTEXT86 *context );
1719  *  extern void WINAPI PREFIX_CallFrom16_C_intr_xxx( FARPROC func, LPBYTE args, 
1720  *                                                   CONTEXT86 *context );
1721  *
1722  * where 'C' is the calling convention ('p' for pascal or 'c' for cdecl), 
1723  * and each 'x' is an argument  ('w'=word, 's'=signed word, 'l'=long, 
1724  * 'p'=linear pointer, 't'=linear pointer to null-terminated string,
1725  * 'T'=segmented pointer to null-terminated string).
1726  *
1727  * The generated routines fetch the arguments from the 16-bit stack (pointed
1728  * to by 'args'); the offsets of the single argument values are computed 
1729  * according to the calling convention and the argument types.  Then, the
1730  * 32-bit entry point is called with these arguments.
1731  * 
1732  * For register functions, the arguments (if present) are converted just
1733  * the same as for normal functions, but in addition the CONTEXT86 pointer 
1734  * filled with the current register values is passed to the 32-bit routine.
1735  * (An 'intr' interrupt handler routine is treated exactly like a register 
1736  * routine, except that upon return, the flags word pushed onto the stack 
1737  * by the interrupt is removed by the 16-bit call stub.)
1738  *
1739  */
1740 static void BuildCallFrom16Func( FILE *outfile, char *profile, char *prefix, int local )
1741 {
1742     int i, pos, argsize = 0;
1743     int short_ret = 0;
1744     int reg_func = 0;
1745     int usecdecl = 0;
1746     char *args = profile + 7;
1747     char *ret_type;
1748
1749     /* Parse function type */
1750
1751     if (!strncmp( "c_", profile, 2 )) usecdecl = 1;
1752     else if (strncmp( "p_", profile, 2 ))
1753     {
1754         fprintf( stderr, "Invalid function name '%s', ignored\n", profile );
1755         return;
1756     }
1757
1758     if (!strncmp( "word_", profile + 2, 5 )) short_ret = 1;
1759     else if (!strncmp( "regs_", profile + 2, 5 )) reg_func = 1;
1760     else if (!strncmp( "intr_", profile + 2, 5 )) reg_func = 2;
1761     else if (strncmp( "long_", profile + 2, 5 ))
1762     {
1763         fprintf( stderr, "Invalid function name '%s', ignored\n", profile );
1764         return;
1765     }
1766
1767     for ( i = 0; args[i]; i++ )
1768         switch ( args[i] )
1769         {
1770         case 'w':  /* word */
1771         case 's':  /* s_word */
1772             argsize += 2;
1773             break;
1774         
1775         case 'l':  /* long or segmented pointer */
1776         case 'T':  /* segmented pointer to null-terminated string */
1777         case 'p':  /* linear pointer */
1778         case 't':  /* linear pointer to null-terminated string */
1779             argsize += 4;
1780             break;
1781         }
1782
1783     ret_type = reg_func? "void" : short_ret? "WORD" : "LONG";
1784
1785     fprintf( outfile, "typedef %s WINAPI (*proc_%s_t)( ", 
1786                       ret_type, profile );
1787     args = profile + 7;
1788     for ( i = 0; args[i]; i++ )
1789     {
1790         if ( i ) fprintf( outfile, ", " );
1791         switch (args[i])
1792         {
1793         case 'w':           fprintf( outfile, "WORD" ); break;
1794         case 's':           fprintf( outfile, "INT16" ); break;
1795         case 'l': case 'T': fprintf( outfile, "LONG" ); break;
1796         case 'p': case 't': fprintf( outfile, "LPVOID" ); break;
1797         }
1798     }
1799     if ( reg_func )
1800         fprintf( outfile, "%sstruct _CONTEXT86 *", i? ", " : "" );
1801     else if ( !i )
1802         fprintf( outfile, "void" );
1803     fprintf( outfile, " );\n" );
1804     
1805     fprintf( outfile, "%s%s WINAPI %s_CallFrom16_%s( FARPROC proc, LPBYTE args%s )\n{\n",
1806              local? "static " : "", ret_type, prefix, profile,
1807              reg_func? ", struct _CONTEXT86 *context" : "" );
1808
1809     fprintf( outfile, "    %s((proc_%s_t) proc) (\n",
1810              reg_func? "" : "return ", profile );
1811     args = profile + 7;
1812     pos = !usecdecl? argsize : 0;
1813     for ( i = 0; args[i]; i++ )
1814     {
1815         if ( i ) fprintf( outfile, ",\n" );
1816         fprintf( outfile, "        " );
1817         switch (args[i])
1818         {
1819         case 'w':  /* word */
1820             if ( !usecdecl ) pos -= 2;
1821             fprintf( outfile, "*(WORD *)(args+%d)", pos );
1822             if (  usecdecl ) pos += 2;
1823             break;
1824
1825         case 's':  /* s_word */
1826             if ( !usecdecl ) pos -= 2;
1827             fprintf( outfile, "*(INT16 *)(args+%d)", pos );
1828             if (  usecdecl ) pos += 2;
1829             break;
1830
1831         case 'l':  /* long or segmented pointer */
1832         case 'T':  /* segmented pointer to null-terminated string */
1833             if ( !usecdecl ) pos -= 4;
1834             fprintf( outfile, "*(LONG *)(args+%d)", pos );
1835             if (  usecdecl ) pos += 4;
1836             break;
1837
1838         case 'p':  /* linear pointer */
1839         case 't':  /* linear pointer to null-terminated string */
1840             if ( !usecdecl ) pos -= 4;
1841             fprintf( outfile, "PTR_SEG_TO_LIN( *(SEGPTR *)(args+%d) )", pos );
1842             if (  usecdecl ) pos += 4;
1843             break;
1844
1845         default:
1846             fprintf( stderr, "Unknown arg type '%c'\n", args[i] );
1847         }
1848     }
1849     if ( reg_func )
1850         fprintf( outfile, "%s        context", i? ",\n" : "" );
1851     fprintf( outfile, " );\n}\n\n" );
1852 }
1853
1854 /*******************************************************************
1855  *         BuildCallTo16Func
1856  *
1857  * Build a Wine-to-16-bit callback glue function. 
1858  *
1859  * Prototypes for the CallTo16 functions:
1860  *   extern WORD CALLBACK PREFIX_CallTo16_word_xxx( FARPROC16 func, args... );
1861  *   extern LONG CALLBACK PREFIX_CallTo16_long_xxx( FARPROC16 func, args... );
1862  * 
1863  * These routines are provided solely for convenience; they simply
1864  * write the arguments onto the 16-bit stack, and call the appropriate
1865  * CallTo16... core routine.
1866  *
1867  * If you have more sophisticated argument conversion requirements than
1868  * are provided by these routines, you might as well call the core 
1869  * routines by yourself.
1870  *
1871  */
1872 static void BuildCallTo16Func( FILE *outfile, char *profile, char *prefix )
1873 {
1874     char *args = profile + 5;
1875     int i, argsize = 0, short_ret = 0;
1876
1877     if (!strncmp( "word_", profile, 5 )) short_ret = 1;
1878     else if (strncmp( "long_", profile, 5 ))
1879     {
1880         fprintf( stderr, "Invalid function name '%s'.\n", profile );
1881         exit(1);
1882     }
1883
1884     fprintf( outfile, "%s %s_CallTo16_%s( FARPROC16 proc",
1885              short_ret? "WORD" : "LONG", prefix, profile );
1886     args = profile + 5;
1887     for ( i = 0; args[i]; i++ )
1888     {
1889         fprintf( outfile, ", " );
1890         switch (args[i])
1891         {
1892         case 'w': fprintf( outfile, "WORD" ); argsize += 2; break;
1893         case 'l': fprintf( outfile, "LONG" ); argsize += 4; break;
1894         }
1895         fprintf( outfile, " arg%d", i+1 );
1896     }
1897     fprintf( outfile, " )\n{\n" );
1898
1899     if ( argsize > 0 )
1900         fprintf( outfile, "    LPBYTE args = (LPBYTE)CURRENT_STACK16;\n" );
1901
1902     args = profile + 5;
1903     for ( i = 0; args[i]; i++ )
1904     {
1905         switch (args[i])
1906         {
1907         case 'w': fprintf( outfile, "    args -= sizeof(WORD); *(WORD" ); break;
1908         case 'l': fprintf( outfile, "    args -= sizeof(LONG); *(LONG" ); break;
1909         default:  fprintf( stderr, "Unexpected case '%c' in BuildCallTo16Func\n",
1910                                    args[i] );
1911         }
1912         fprintf( outfile, " *)args = arg%d;\n", i+1 );
1913     }
1914
1915     fprintf( outfile, "    return CallTo16%s( proc, %d );\n}\n\n",
1916              short_ret? "Word" : "Long", argsize );
1917 }
1918
1919
1920
1921 /*******************************************************************
1922  *         BuildCallFrom16Core
1923  *
1924  * This routine builds the core routines used in 16->32 thunks:
1925  * CallFrom16Word, CallFrom16Long, CallFrom16Register, and CallFrom16Thunk.
1926  *
1927  * These routines are intended to be called via a far call (with 32-bit
1928  * operand size) from 16-bit code.  The 16-bit code stub must push %bp,
1929  * the 32-bit entry point to be called, and the argument conversion 
1930  * routine to be used (see stack layout below).  
1931  *
1932  * The core routine completes the STACK16FRAME on the 16-bit stack and
1933  * switches to the 32-bit stack.  Then, the argument conversion routine 
1934  * is called; it gets passed the 32-bit entry point and a pointer to the 
1935  * 16-bit arguments (on the 16-bit stack) as parameters. (You can either 
1936  * use conversion routines automatically generated by BuildCallFrom16, 
1937  * or write your own for special purposes.)
1938  * 
1939  * The conversion routine must call the 32-bit entry point, passing it
1940  * the converted arguments, and return its return value to the core.  
1941  * After the conversion routine has returned, the core switches back
1942  * to the 16-bit stack, converts the return value to the DX:AX format
1943  * (CallFrom16Long), and returns to the 16-bit call stub.  All parameters,
1944  * including %bp, are popped off the stack.
1945  *
1946  * The 16-bit call stub now returns to the caller, popping the 16-bit
1947  * arguments if necessary (pascal calling convention).
1948  *
1949  * In the case of a 'register' function, CallFrom16Register fills a
1950  * CONTEXT86 structure with the values all registers had at the point
1951  * the first instruction of the 16-bit call stub was about to be 
1952  * executed.  A pointer to this CONTEXT86 is passed as third parameter 
1953  * to the argument conversion routine, which typically passes it on
1954  * to the called 32-bit entry point.
1955  *
1956  * CallFrom16Thunk is a special variant used by the implementation of 
1957  * the Win95 16->32 thunk functions C16ThkSL and C16ThkSL01 and is 
1958  * implemented as follows:
1959  * On entry, the EBX register is set up to contain a flat pointer to the
1960  * 16-bit stack such that EBX+22 points to the first argument.
1961  * Then, the entry point is called, while EBP is set up to point
1962  * to the return address (on the 32-bit stack).
1963  * The called function returns with CX set to the number of bytes
1964  * to be popped of the caller's stack.
1965  *
1966  * Stack layout upon entry to the core routine (STACK16FRAME):
1967  *  ...           ...
1968  * (sp+24) word   first 16-bit arg
1969  * (sp+22) word   cs
1970  * (sp+20) word   ip
1971  * (sp+18) word   bp
1972  * (sp+14) long   32-bit entry point (reused for Win16 mutex recursion count)
1973  * (sp+12) word   ip of actual entry point (necessary for relay debugging)
1974  * (sp+8)  long   relay (argument conversion) function entry point
1975  * (sp+4)  long   cs of 16-bit entry point
1976  * (sp)    long   ip of 16-bit entry point
1977  *
1978  * Added on the stack:
1979  * (sp-2)  word   saved gs
1980  * (sp-4)  word   saved fs
1981  * (sp-6)  word   saved es
1982  * (sp-8)  word   saved ds
1983  * (sp-12) long   saved ebp
1984  * (sp-16) long   saved ecx
1985  * (sp-20) long   saved edx
1986  * (sp-24) long   saved previous stack
1987  */
1988 static void BuildCallFrom16Core( FILE *outfile, int reg_func, int thunk, int short_ret )
1989 {
1990     char *name = thunk? "Thunk" : reg_func? "Register" : short_ret? "Word" : "Long";
1991
1992     /* Function header */
1993     fprintf( outfile, "\n\t.align 4\n" );
1994 #ifdef USE_STABS
1995     fprintf( outfile, ".stabs \"CallFrom16%s:F1\",36,0,0," PREFIX "CallFrom16%s\n", 
1996              name, name);
1997 #endif
1998     fprintf( outfile, "\t.type " PREFIX "CallFrom16%s,@function\n", name );
1999     fprintf( outfile, "\t.globl " PREFIX "CallFrom16%s\n", name );
2000     fprintf( outfile, PREFIX "CallFrom16%s:\n", name );
2001
2002     /* Create STACK16FRAME (except STACK32FRAME link) */
2003     fprintf( outfile, "\tpushw %%gs\n" );
2004     fprintf( outfile, "\tpushw %%fs\n" );
2005     fprintf( outfile, "\tpushw %%es\n" );
2006     fprintf( outfile, "\tpushw %%ds\n" );
2007     fprintf( outfile, "\tpushl %%ebp\n" );
2008     fprintf( outfile, "\tpushl %%ecx\n" );
2009     fprintf( outfile, "\tpushl %%edx\n" );
2010
2011     /* Save original EFlags register */
2012     fprintf( outfile, "\tpushfl\n" );
2013
2014     if ( UsePIC )
2015     {
2016         /* Get Global Offset Table into %ecx */
2017         fprintf( outfile, "\tcall .LCallFrom16%s.getgot1\n", name );
2018         fprintf( outfile, ".LCallFrom16%s.getgot1:\n", name );
2019         fprintf( outfile, "\tpopl %%ecx\n" );
2020         fprintf( outfile, "\taddl $_GLOBAL_OFFSET_TABLE_+[.-.LCallFrom16%s.getgot1], %%ecx\n", name );
2021     }
2022
2023     /* Load 32-bit segment registers */
2024     fprintf( outfile, "\tmovw $0x%04x, %%dx\n", Data_Selector );
2025 #ifdef __svr4__
2026     fprintf( outfile, "\tdata16\n");
2027 #endif
2028     fprintf( outfile, "\tmovw %%dx, %%ds\n" );
2029 #ifdef __svr4__
2030     fprintf( outfile, "\tdata16\n");
2031 #endif
2032     fprintf( outfile, "\tmovw %%dx, %%es\n" );
2033
2034     if ( UsePIC )
2035     {
2036         fprintf( outfile, "\tmovl " PREFIX "SYSLEVEL_Win16CurrentTeb@GOT(%%ecx), %%edx\n" );
2037         fprintf( outfile, "\tmovw (%%edx), %%fs\n" );
2038     }
2039     else
2040         fprintf( outfile, "\tmovw " PREFIX "SYSLEVEL_Win16CurrentTeb, %%fs\n" );
2041
2042     /* Get address of ldt_copy array into %ecx */
2043     if ( UsePIC )
2044         fprintf( outfile, "\tmovl " PREFIX "ldt_copy@GOT(%%ecx), %%ecx\n" );
2045     else
2046         fprintf( outfile, "\tmovl $" PREFIX "ldt_copy, %%ecx\n" );
2047
2048     /* Translate STACK16FRAME base to flat offset in %edx */
2049     fprintf( outfile, "\tmovw %%ss, %%dx\n" );
2050     fprintf( outfile, "\tandl $0xfff8, %%edx\n" );
2051     fprintf( outfile, "\tmovl (%%ecx,%%edx), %%edx\n" );
2052     fprintf( outfile, "\tmovzwl %%sp, %%ebp\n" );
2053     fprintf( outfile, "\tleal (%%ebp,%%edx), %%edx\n" );  
2054
2055     /* Get saved flags into %ecx */
2056     fprintf( outfile, "\tpopl %%ecx\n" );
2057
2058     /* Get the 32-bit stack pointer from the TEB and complete STACK16FRAME */
2059     fprintf( outfile, "\t.byte 0x64\n\tmovl (%d), %%ebp\n", STACKOFFSET );
2060     fprintf( outfile, "\tpushl %%ebp\n" );
2061
2062     /* Switch stacks */
2063 #ifdef __svr4__
2064     fprintf( outfile,"\tdata16\n");
2065 #endif
2066     fprintf( outfile, "\t.byte 0x64\n\tmovw %%ss, (%d)\n", STACKOFFSET + 2 );
2067     fprintf( outfile, "\t.byte 0x64\n\tmovw %%sp, (%d)\n", STACKOFFSET );
2068     fprintf( outfile, "\tpushl %%ds\n" );
2069     fprintf( outfile, "\tpopl %%ss\n" );
2070     fprintf( outfile, "\tmovl %%ebp, %%esp\n" );
2071     fprintf( outfile, "\taddl $%d, %%ebp\n", STRUCTOFFSET(STACK32FRAME, ebp) );
2072
2073
2074     /* At this point:
2075        STACK16FRAME is completely set up
2076        DS, ES, SS: flat data segment
2077        FS: current TEB
2078        ESP: points to last STACK32FRAME
2079        EBP: points to ebp member of last STACK32FRAME
2080        EDX: points to current STACK16FRAME
2081        ECX: contains saved flags
2082        all other registers: unchanged */
2083
2084     /* Special case: C16ThkSL stub */
2085     if ( thunk )
2086     {
2087         /* Set up registers as expected and call thunk */
2088         fprintf( outfile, "\tleal %d(%%edx), %%ebx\n", sizeof(STACK16FRAME)-22 );
2089         fprintf( outfile, "\tleal -4(%%esp), %%ebp\n" );
2090
2091         fprintf( outfile, "\tcall *%d(%%edx)\n", STACK16OFFSET(entry_point) );
2092
2093         /* Switch stack back */
2094         /* fprintf( outfile, "\t.byte 0x64\n\tlssw (%d), %%sp\n", STACKOFFSET ); */
2095         fprintf( outfile, "\t.byte 0x64,0x66,0x0f,0xb2,0x25\n\t.long %d\n", STACKOFFSET );
2096         fprintf( outfile, "\t.byte 0x64\n\tpopl (%d)\n", STACKOFFSET );
2097
2098         /* Restore registers and return directly to caller */
2099         fprintf( outfile, "\taddl $8, %%esp\n" );
2100         fprintf( outfile, "\tpopl %%ebp\n" );
2101         fprintf( outfile, "\tpopw %%ds\n" );
2102         fprintf( outfile, "\tpopw %%es\n" );
2103         fprintf( outfile, "\tpopw %%fs\n" );
2104         fprintf( outfile, "\tpopw %%gs\n" );
2105         fprintf( outfile, "\taddl $20, %%esp\n" );
2106
2107         fprintf( outfile, "\txorb %%ch, %%ch\n" );
2108         fprintf( outfile, "\tpopl %%ebx\n" );
2109         fprintf( outfile, "\taddw %%cx, %%sp\n" );
2110         fprintf( outfile, "\tpush %%ebx\n" );
2111
2112         fprintf( outfile, "\t.byte 0x66\n" );
2113         fprintf( outfile, "\tlret\n" );
2114
2115         return;
2116     }
2117
2118
2119     /* Build register CONTEXT */
2120     if ( reg_func )
2121     {
2122         fprintf( outfile, "\tsubl $%d, %%esp\n", sizeof(CONTEXT86) );
2123
2124         fprintf( outfile, "\tmovl %%ecx, %d(%%esp)\n", CONTEXTOFFSET(EFlags) );  
2125
2126         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(Eax) );
2127         fprintf( outfile, "\tmovl %%ebx, %d(%%esp)\n", CONTEXTOFFSET(Ebx) );
2128         fprintf( outfile, "\tmovl %%esi, %d(%%esp)\n", CONTEXTOFFSET(Esi) );
2129         fprintf( outfile, "\tmovl %%edi, %d(%%esp)\n", CONTEXTOFFSET(Edi) );
2130
2131         fprintf( outfile, "\tmovl %d(%%edx), %%eax\n", STACK16OFFSET(ebp) );
2132         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(Ebp) );
2133         fprintf( outfile, "\tmovl %d(%%edx), %%eax\n", STACK16OFFSET(ecx) );
2134         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(Ecx) );
2135         fprintf( outfile, "\tmovl %d(%%edx), %%eax\n", STACK16OFFSET(edx) );
2136         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(Edx) );
2137
2138         fprintf( outfile, "\tmovzwl %d(%%edx), %%eax\n", STACK16OFFSET(ds) );
2139         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(SegDs) );
2140         fprintf( outfile, "\tmovzwl %d(%%edx), %%eax\n", STACK16OFFSET(es) );
2141         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(SegEs) );
2142         fprintf( outfile, "\tmovzwl %d(%%edx), %%eax\n", STACK16OFFSET(fs) );
2143         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(SegFs) );
2144         fprintf( outfile, "\tmovzwl %d(%%edx), %%eax\n", STACK16OFFSET(gs) );
2145         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(SegGs) );
2146
2147         fprintf( outfile, "\tmovzwl %d(%%edx), %%eax\n", STACK16OFFSET(cs) );
2148         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(SegCs) );
2149         fprintf( outfile, "\tmovzwl %d(%%edx), %%eax\n", STACK16OFFSET(ip) );
2150         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(Eip) );
2151
2152         fprintf( outfile, "\t.byte 0x64\n\tmovzwl (%d), %%eax\n", STACKOFFSET+2 );
2153         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(SegSs) );
2154         fprintf( outfile, "\t.byte 0x64\n\tmovzwl (%d), %%eax\n", STACKOFFSET );
2155         fprintf( outfile, "\taddl $%d, %%eax\n", STACK16OFFSET(ip) );
2156         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(Esp) );
2157 #if 0
2158         fprintf( outfile, "\tfsave %d(%%esp)\n", CONTEXTOFFSET(FloatSave) );
2159 #endif
2160
2161         /* Push address of CONTEXT86 structure -- popped by the relay routine */
2162         fprintf( outfile, "\tpushl %%esp\n" );
2163     }
2164
2165
2166     /* Print debug info before call */
2167     if ( debugging )
2168     {
2169         if ( UsePIC )
2170         {
2171             fprintf( outfile, "\tpushl %%ebx\n" );
2172
2173             /* Get Global Offset Table into %ebx (for PLT call) */
2174             fprintf( outfile, "\tcall .LCallFrom16%s.getgot2\n", name );
2175             fprintf( outfile, ".LCallFrom16%s.getgot2:\n", name );
2176             fprintf( outfile, "\tpopl %%ebx\n" );
2177             fprintf( outfile, "\taddl $_GLOBAL_OFFSET_TABLE_+[.-.LCallFrom16%s.getgot2], %%ebx\n", name );
2178         }
2179
2180         fprintf( outfile, "\tpushl %%edx\n" );
2181         if ( reg_func )
2182             fprintf( outfile, "\tleal -%d(%%ebp), %%eax\n\tpushl %%eax\n",
2183                               sizeof(CONTEXT) + STRUCTOFFSET(STACK32FRAME, ebp) );
2184         else
2185             fprintf( outfile, "\tpushl $0\n" );
2186
2187         if ( UsePIC )
2188             fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallFrom16@PLT\n ");
2189         else
2190             fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallFrom16\n ");
2191
2192         fprintf( outfile, "\tpopl %%edx\n" );
2193         fprintf( outfile, "\tpopl %%edx\n" );
2194
2195         if ( UsePIC )
2196             fprintf( outfile, "\tpopl %%ebx\n" );
2197     }
2198
2199     /* Call relay routine (which will call the API entry point) */
2200     fprintf( outfile, "\tleal %d(%%edx), %%eax\n", sizeof(STACK16FRAME) );
2201     fprintf( outfile, "\tpushl %%eax\n" );
2202     fprintf( outfile, "\tpushl %d(%%edx)\n", STACK16OFFSET(entry_point) );
2203     fprintf( outfile, "\tcall *%d(%%edx)\n", STACK16OFFSET(relay) );
2204
2205     /* Print debug info after call */
2206     if ( debugging )
2207     {
2208         if ( UsePIC )
2209         {
2210             fprintf( outfile, "\tpushl %%ebx\n" );
2211
2212             /* Get Global Offset Table into %ebx (for PLT call) */
2213             fprintf( outfile, "\tcall .LCallFrom16%s.getgot3\n", name );
2214             fprintf( outfile, ".LCallFrom16%s.getgot3:\n", name );
2215             fprintf( outfile, "\tpopl %%ebx\n" );
2216             fprintf( outfile, "\taddl $_GLOBAL_OFFSET_TABLE_+[.-.LCallFrom16%s.getgot3], %%ebx\n", name );
2217         }
2218
2219         fprintf( outfile, "\tpushl %%eax\n" );
2220         if ( reg_func )
2221             fprintf( outfile, "\tleal -%d(%%ebp), %%eax\n\tpushl %%eax\n",
2222                               sizeof(CONTEXT) + STRUCTOFFSET(STACK32FRAME, ebp) );
2223         else
2224             fprintf( outfile, "\tpushl $0\n" );
2225
2226         if ( UsePIC )
2227             fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallFrom16Ret@PLT\n ");
2228         else
2229             fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallFrom16Ret\n ");
2230
2231         fprintf( outfile, "\tpopl %%eax\n" );
2232         fprintf( outfile, "\tpopl %%eax\n" );
2233
2234         if ( UsePIC )
2235             fprintf( outfile, "\tpopl %%ebx\n" );
2236     }
2237
2238
2239     if ( reg_func )
2240     {
2241         fprintf( outfile, "\tmovl %%esp, %%ebx\n" );
2242
2243         /* Switch stack back */
2244         /* fprintf( outfile, "\t.byte 0x64\n\tlssw (%d), %%sp\n", STACKOFFSET ); */
2245         fprintf( outfile, "\t.byte 0x64,0x66,0x0f,0xb2,0x25\n\t.long %d\n", STACKOFFSET );
2246         fprintf( outfile, "\t.byte 0x64\n\tpopl (%d)\n", STACKOFFSET );
2247
2248         /* Get return address to CallFrom16 stub */
2249         fprintf( outfile, "\taddw $%d, %%sp\n", STACK16OFFSET(callfrom_ip)-4 );
2250         fprintf( outfile, "\tpopl %%eax\n" );
2251         fprintf( outfile, "\tpopl %%edx\n" );
2252
2253         /* Restore all registers from CONTEXT */
2254         fprintf( outfile, "\tmovw %d(%%ebx), %%ss\n", CONTEXTOFFSET(SegSs) );
2255         fprintf( outfile, "\tmovl %d(%%ebx), %%esp\n", CONTEXTOFFSET(Esp) );
2256         fprintf( outfile, "\taddl $4, %%esp\n" );  /* room for final return address */
2257
2258         fprintf( outfile, "\tpushw %d(%%ebx)\n", CONTEXTOFFSET(SegCs) );
2259         fprintf( outfile, "\tpushw %d(%%ebx)\n", CONTEXTOFFSET(Eip) );
2260         fprintf( outfile, "\tpushl %%edx\n" );
2261         fprintf( outfile, "\tpushl %%eax\n" );
2262         fprintf( outfile, "\tpushl %d(%%ebx)\n", CONTEXTOFFSET(EFlags) );
2263         fprintf( outfile, "\tpushl %d(%%ebx)\n", CONTEXTOFFSET(SegDs) );
2264
2265         fprintf( outfile, "\tmovw %d(%%ebx), %%es\n", CONTEXTOFFSET(SegEs) );
2266         fprintf( outfile, "\tmovw %d(%%ebx), %%fs\n", CONTEXTOFFSET(SegFs) );
2267         fprintf( outfile, "\tmovw %d(%%ebx), %%gs\n", CONTEXTOFFSET(SegGs) );
2268
2269         fprintf( outfile, "\tmovl %d(%%ebx), %%ebp\n", CONTEXTOFFSET(Ebp) );
2270         fprintf( outfile, "\tmovl %d(%%ebx), %%esi\n", CONTEXTOFFSET(Esi) );
2271         fprintf( outfile, "\tmovl %d(%%ebx), %%edi\n", CONTEXTOFFSET(Edi) );
2272         fprintf( outfile, "\tmovl %d(%%ebx), %%eax\n", CONTEXTOFFSET(Eax) );
2273         fprintf( outfile, "\tmovl %d(%%ebx), %%edx\n", CONTEXTOFFSET(Edx) );
2274         fprintf( outfile, "\tmovl %d(%%ebx), %%ecx\n", CONTEXTOFFSET(Ecx) );
2275         fprintf( outfile, "\tmovl %d(%%ebx), %%ebx\n", CONTEXTOFFSET(Ebx) );
2276   
2277         fprintf( outfile, "\tpopl %%ds\n" );
2278         fprintf( outfile, "\tpopfl\n" );
2279         fprintf( outfile, "\tlret\n" );
2280     }
2281     else
2282     {
2283         /* Switch stack back */
2284         /* fprintf( outfile, "\t.byte 0x64\n\tlssw (%d), %%sp\n", STACKOFFSET ); */
2285         fprintf( outfile, "\t.byte 0x64,0x66,0x0f,0xb2,0x25\n\t.long %d\n", STACKOFFSET );
2286         fprintf( outfile, "\t.byte 0x64\n\tpopl (%d)\n", STACKOFFSET );
2287
2288         /* Restore registers */
2289         fprintf( outfile, "\tpopl %%edx\n" );
2290         fprintf( outfile, "\tpopl %%ecx\n" );
2291         fprintf( outfile, "\tpopl %%ebp\n" );
2292         fprintf( outfile, "\tpopw %%ds\n" );
2293         fprintf( outfile, "\tpopw %%es\n" );
2294         fprintf( outfile, "\tpopw %%fs\n" );
2295         fprintf( outfile, "\tpopw %%gs\n" );
2296
2297         /* Prepare return value and set flags accordingly */
2298         if ( !short_ret )
2299             fprintf( outfile, "\tshldl $16, %%eax, %%edx\n" );
2300         fprintf( outfile, "\torl %%eax, %%eax\n" );
2301
2302         /* Return to return stub which will return to caller */
2303         fprintf( outfile, "\tlret $12\n" );
2304     }
2305 }
2306   
2307
2308 /*******************************************************************
2309  *         BuildCallTo16Core
2310  *
2311  * This routine builds the core routines used in 32->16 thunks:
2312  *
2313  *   extern void CALLBACK CallTo16Word( SEGPTR target, int nb_args );
2314  *   extern void CALLBACK CallTo16Long( SEGPTR target, int nb_args );
2315  *   extern void CALLBACK CallTo16RegisterShort( const CONTEXT86 *context, int nb_args );
2316  *   extern void CALLBACK CallTo16RegisterLong ( const CONTEXT86 *context, int nb_args );
2317  *
2318  * These routines can be called directly from 32-bit code. 
2319  *
2320  * All routines expect that the 16-bit stack contents (arguments) were 
2321  * already set up by the caller; nb_args must contain the number of bytes 
2322  * to be conserved.  The 16-bit SS:SP will be set accordinly.
2323  *
2324  * All other registers are either taken from the CONTEXT86 structure 
2325  * or else set to default values.  The target routine address is either
2326  * given directly or taken from the CONTEXT86.
2327  *
2328  * If you want to call a 16-bit routine taking only standard argument types 
2329  * (WORD and LONG), you can also have an appropriate argument conversion 
2330  * stub automatically generated (see BuildCallTo16); you'd then call this
2331  * stub, which in turn would prepare the 16-bit stack and call the appropiate
2332  * core routine.
2333  *
2334  */
2335
2336 static void BuildCallTo16Core( FILE *outfile, int short_ret, int reg_func )
2337 {
2338     char *name = reg_func == 2 ? "RegisterLong" : 
2339                  reg_func == 1 ? "RegisterShort" :
2340                  short_ret? "Word" : "Long";
2341
2342     /* Function header */
2343     fprintf( outfile, "\n\t.align 4\n" );
2344 #ifdef USE_STABS
2345     fprintf( outfile, ".stabs \"CallTo16%s:F1\",36,0,0," PREFIX "CallTo16%s\n", 
2346              name, name);
2347 #endif
2348     fprintf( outfile, "\t.type " PREFIX "CallTo16%s,@function\n", name );
2349     fprintf( outfile, "\t.globl " PREFIX "CallTo16%s\n", name );
2350     fprintf( outfile, PREFIX "CallTo16%s:\n", name );
2351
2352     /* Function entry sequence */
2353     fprintf( outfile, "\tpushl %%ebp\n" );
2354     fprintf( outfile, "\tmovl %%esp, %%ebp\n" );
2355
2356     /* Save the 32-bit registers */
2357     fprintf( outfile, "\tpushl %%ebx\n" );
2358     fprintf( outfile, "\tpushl %%ecx\n" );
2359     fprintf( outfile, "\tpushl %%edx\n" );
2360     fprintf( outfile, "\tpushl %%esi\n" );
2361     fprintf( outfile, "\tpushl %%edi\n" );
2362
2363     if ( UsePIC )
2364     {
2365         /* Get Global Offset Table into %ebx */
2366         fprintf( outfile, "\tcall .LCallTo16%s.getgot1\n", name );
2367         fprintf( outfile, ".LCallTo16%s.getgot1:\n", name );
2368         fprintf( outfile, "\tpopl %%ebx\n" );
2369         fprintf( outfile, "\taddl $_GLOBAL_OFFSET_TABLE_+[.-.LCallTo16%s.getgot1], %%ebx\n", name );
2370     }
2371
2372     /* Enter Win16 Mutex */
2373     if ( UsePIC )
2374         fprintf( outfile, "\tcall " PREFIX "SYSLEVEL_EnterWin16Lock@PLT\n" );
2375     else
2376         fprintf( outfile, "\tcall " PREFIX "SYSLEVEL_EnterWin16Lock\n" );
2377
2378     /* Print debugging info */
2379     if (debugging)
2380     {
2381         /* Push flags, number of arguments, and target */
2382         fprintf( outfile, "\tpushl $%d\n", reg_func );
2383         fprintf( outfile, "\tpushl 12(%%ebp)\n" );
2384         fprintf( outfile, "\tpushl  8(%%ebp)\n" );
2385
2386         if ( UsePIC )
2387             fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallTo16@PLT\n" );
2388         else
2389             fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallTo16\n" );
2390
2391         fprintf( outfile, "\taddl $12, %%esp\n" );
2392     }
2393
2394     /* Get return address */
2395     if ( UsePIC )
2396     {
2397         fprintf( outfile, "\tmovl " PREFIX "CallTo16_RetAddr@GOT(%%ebx), %%ecx\n" );
2398         fprintf( outfile, "\tmovl " PREFIX "(%%ecx), %%ecx\n" );
2399     }
2400     else
2401         fprintf( outfile, "\tmovl " PREFIX "CallTo16_RetAddr, %%ecx\n" );
2402
2403     /* Call the actual CallTo16 routine (simulate a lcall) */
2404     fprintf( outfile, "\tpushl %%cs\n" );
2405     fprintf( outfile, "\tcall .LCallTo16%s\n", name );
2406
2407     /* Convert and push return value */
2408     if ( short_ret )
2409     {
2410         fprintf( outfile, "\tmovzwl %%ax, %%eax\n" );
2411         fprintf( outfile, "\tpushl %%eax\n" );
2412     }
2413     else if ( reg_func != 2 )
2414     {
2415         fprintf( outfile, "\tshll $16,%%edx\n" );
2416         fprintf( outfile, "\tmovw %%ax,%%dx\n" );
2417         fprintf( outfile, "\tpushl %%edx\n" );
2418     }
2419     else
2420         fprintf( outfile, "\tpushl %%eax\n" );
2421
2422     if ( UsePIC )
2423     {
2424         /* Get Global Offset Table into %ebx (might have been overwritten) */
2425         fprintf( outfile, "\tcall .LCallTo16%s.getgot2\n", name );
2426         fprintf( outfile, ".LCallTo16%s.getgot2:\n", name );
2427         fprintf( outfile, "\tpopl %%ebx\n" );
2428         fprintf( outfile, "\taddl $_GLOBAL_OFFSET_TABLE_+[.-.LCallTo16%s.getgot2], %%ebx\n", name );
2429     }
2430
2431     /* Print debugging info */
2432     if (debugging)
2433     {
2434         if ( UsePIC )
2435             fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallTo16Ret@PLT\n" );
2436         else
2437             fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallTo16Ret\n" );
2438     }
2439
2440     /* Leave Win16 Mutex */
2441     if ( UsePIC )
2442         fprintf( outfile, "\tcall " PREFIX "SYSLEVEL_LeaveWin16Lock@PLT\n" );
2443     else
2444         fprintf( outfile, "\tcall " PREFIX "SYSLEVEL_LeaveWin16Lock\n" );
2445
2446     /* Get return value */
2447     fprintf( outfile, "\tpopl %%eax\n" );
2448
2449     /* Restore the 32-bit registers */
2450     fprintf( outfile, "\tpopl %%edi\n" );
2451     fprintf( outfile, "\tpopl %%esi\n" );
2452     fprintf( outfile, "\tpopl %%edx\n" );
2453     fprintf( outfile, "\tpopl %%ecx\n" );
2454     fprintf( outfile, "\tpopl %%ebx\n" );
2455
2456     /* Function exit sequence */
2457     fprintf( outfile, "\tpopl %%ebp\n" );
2458     fprintf( outfile, "\tret $8\n" );
2459
2460
2461     /* Start of the actual CallTo16 routine */
2462
2463     fprintf( outfile, ".LCallTo16%s:\n", name );
2464
2465     /* Complete STACK32FRAME */
2466     fprintf( outfile, "\t.byte 0x64\n\tpushl (%d)\n", STACKOFFSET );
2467     fprintf( outfile, "\tmovl %%esp,%%edx\n" );
2468
2469     /* Switch to the 16-bit stack */
2470 #ifdef __svr4__
2471     fprintf( outfile,"\tdata16\n");
2472 #endif
2473     fprintf( outfile, "\t.byte 0x64\n\tmovw (%d),%%ss\n", STACKOFFSET + 2);
2474     fprintf( outfile, "\t.byte 0x64\n\tmovw (%d),%%sp\n", STACKOFFSET );
2475     fprintf( outfile, "\t.byte 0x64\n\tmovl %%edx,(%d)\n", STACKOFFSET );
2476
2477     /* Make %bp point to the previous stackframe (built by CallFrom16) */
2478     fprintf( outfile, "\tmovzwl %%sp,%%ebp\n" );
2479     fprintf( outfile, "\tleal %d(%%ebp),%%ebp\n", STACK16OFFSET(bp) );
2480
2481     /* Add the specified offset to the new sp */
2482     fprintf( outfile, "\tsubw %d(%%edx), %%sp\n", STACK32OFFSET(nb_args) );
2483
2484     /* Push the return address 
2485      * With sreg suffix, we push 16:16 address (normal lret)
2486      * With lreg suffix, we push 16:32 address (0x66 lret, for KERNEL32_45)
2487      */
2488     if (reg_func != 2)
2489         fprintf( outfile, "\tpushl %%ecx\n" );
2490     else 
2491     {
2492         fprintf( outfile, "\tshldl $16, %%ecx, %%eax\n" );
2493         fprintf( outfile, "\tpushw $0\n" );
2494         fprintf( outfile, "\tpushw %%ax\n" );
2495         fprintf( outfile, "\tpushw $0\n" );
2496         fprintf( outfile, "\tpushw %%cx\n" );
2497     }
2498
2499     if (reg_func)
2500     {
2501         /* Push the called routine address */
2502         fprintf( outfile, "\tmovl %d(%%edx),%%edx\n", STACK32OFFSET(target) );
2503         fprintf( outfile, "\tpushw %d(%%edx)\n", CONTEXTOFFSET(SegCs) );
2504         fprintf( outfile, "\tpushw %d(%%edx)\n", CONTEXTOFFSET(Eip) );
2505
2506         /* Get the registers */
2507         fprintf( outfile, "\tpushw %d(%%edx)\n", CONTEXTOFFSET(SegDs) );
2508         fprintf( outfile, "\tmovl %d(%%edx),%%eax\n", CONTEXTOFFSET(SegEs) );
2509         fprintf( outfile, "\tmovw %%ax,%%es\n" );
2510         fprintf( outfile, "\tmovl %d(%%edx),%%eax\n", CONTEXTOFFSET(SegFs) );
2511         fprintf( outfile, "\tmovw %%ax,%%fs\n" );
2512         fprintf( outfile, "\tmovl %d(%%edx),%%ebp\n", CONTEXTOFFSET(Ebp) );
2513         fprintf( outfile, "\tmovl %d(%%edx),%%esi\n", CONTEXTOFFSET(Esi) );
2514         fprintf( outfile, "\tmovl %d(%%edx),%%edi\n", CONTEXTOFFSET(Edi) );
2515         fprintf( outfile, "\tmovl %d(%%edx),%%eax\n", CONTEXTOFFSET(Eax) );
2516         fprintf( outfile, "\tmovl %d(%%edx),%%ebx\n", CONTEXTOFFSET(Ebx) );
2517         fprintf( outfile, "\tmovl %d(%%edx),%%ecx\n", CONTEXTOFFSET(Ecx) );
2518         fprintf( outfile, "\tmovl %d(%%edx),%%edx\n", CONTEXTOFFSET(Edx) );
2519
2520         /* Get the 16-bit ds */
2521         fprintf( outfile, "\tpopw %%ds\n" );
2522     }
2523     else  /* not a register function */
2524     {
2525         /* Push the called routine address */
2526         fprintf( outfile, "\tpushl %d(%%edx)\n", STACK32OFFSET(target) );
2527
2528         /* Set %fs to the value saved by the last CallFrom16 */
2529         fprintf( outfile, "\tmovw %d(%%ebp),%%ax\n", STACK16OFFSET(fs)-STACK16OFFSET(bp) );
2530         fprintf( outfile, "\tmovw %%ax,%%fs\n" );
2531
2532         /* Set %ds and %es (and %ax just in case) equal to %ss */
2533         fprintf( outfile, "\tmovw %%ss,%%ax\n" );
2534         fprintf( outfile, "\tmovw %%ax,%%ds\n" );
2535         fprintf( outfile, "\tmovw %%ax,%%es\n" );
2536     }
2537
2538     /* Jump to the called routine */
2539     fprintf( outfile, "\t.byte 0x66\n" );
2540     fprintf( outfile, "\tlret\n" );
2541 }
2542
2543 /*******************************************************************
2544  *         BuildRet16Func
2545  *
2546  * Build the return code for 16-bit callbacks
2547  */
2548 static void BuildRet16Func( FILE *outfile )
2549 {
2550     /* 
2551      *  Note: This must reside in the .data section to allow
2552      *        run-time relocation of the SYSLEVEL_Win16CurrentTeb symbol
2553      */
2554
2555     fprintf( outfile, "\n\t.type " PREFIX "CallTo16_Ret,@function\n" );
2556     fprintf( outfile, "\t.globl " PREFIX "CallTo16_Ret\n" );
2557     fprintf( outfile, PREFIX "CallTo16_Ret:\n" );
2558
2559     /* Restore 32-bit segment registers */
2560
2561     fprintf( outfile, "\tmovw $0x%04x,%%bx\n", Data_Selector );
2562 #ifdef __svr4__
2563     fprintf( outfile, "\tdata16\n");
2564 #endif
2565     fprintf( outfile, "\tmovw %%bx,%%ds\n" );
2566 #ifdef __svr4__
2567     fprintf( outfile, "\tdata16\n");
2568 #endif
2569     fprintf( outfile, "\tmovw %%bx,%%es\n" );
2570
2571     fprintf( outfile, "\tmovw " PREFIX "SYSLEVEL_Win16CurrentTeb,%%fs\n" );
2572
2573     /* Restore the 32-bit stack */
2574
2575 #ifdef __svr4__
2576     fprintf( outfile, "\tdata16\n");
2577 #endif
2578     fprintf( outfile, "\tmovw %%bx,%%ss\n" );
2579     fprintf( outfile, "\t.byte 0x64\n\tmovl (%d),%%esp\n", STACKOFFSET );
2580     fprintf( outfile, "\t.byte 0x64\n\tpopl (%d)\n", STACKOFFSET );
2581
2582     /* Return to caller */
2583
2584     fprintf( outfile, "\tlret\n" );
2585
2586     /* Declare the return address variable */
2587
2588     fprintf( outfile, "\n\t.globl " PREFIX "CallTo16_RetAddr\n" );
2589     fprintf( outfile, PREFIX "CallTo16_RetAddr:\t.long 0\n" );
2590 }
2591
2592 /*******************************************************************
2593  *         BuildCallTo32CBClient
2594  *
2595  * Call a CBClient relay stub from 32-bit code (KERNEL.620).
2596  *
2597  * Since the relay stub is itself 32-bit, this should not be a problem;
2598  * unfortunately, the relay stubs are expected to switch back to a 
2599  * 16-bit stack (and 16-bit code) after completion :-(
2600  *
2601  * This would conflict with our 16- vs. 32-bit stack handling, so
2602  * we simply switch *back* to our 32-bit stack before returning to
2603  * the caller ...
2604  *
2605  * The CBClient relay stub expects to be called with the following
2606  * 16-bit stack layout, and with ebp and ebx pointing into the 16-bit
2607  * stack at the designated places:
2608  *
2609  *    ...
2610  *  (ebp+14) original arguments to the callback routine
2611  *  (ebp+10) far return address to original caller
2612  *  (ebp+6)  Thunklet target address
2613  *  (ebp+2)  Thunklet relay ID code
2614  *  (ebp)    BP (saved by CBClientGlueSL)
2615  *  (ebp-2)  SI (saved by CBClientGlueSL)
2616  *  (ebp-4)  DI (saved by CBClientGlueSL)
2617  *  (ebp-6)  DS (saved by CBClientGlueSL)
2618  *
2619  *   ...     buffer space used by the 16-bit side glue for temp copies
2620  *
2621  *  (ebx+4)  far return address to 16-bit side glue code
2622  *  (ebx)    saved 16-bit ss:sp (pointing to ebx+4)
2623  *
2624  * The 32-bit side glue code accesses both the original arguments (via ebp)
2625  * and the temporary copies prepared by the 16-bit side glue (via ebx).
2626  * After completion, the stub will load ss:sp from the buffer at ebx
2627  * and perform a far return to 16-bit code.  
2628  *
2629  * To trick the relay stub into returning to us, we replace the 16-bit
2630  * return address to the glue code by a cs:ip pair pointing to our
2631  * return entry point (the original return address is saved first).
2632  * Our return stub thus called will then reload the 32-bit ss:esp and
2633  * return to 32-bit code (by using and ss:esp value that we have also
2634  * pushed onto the 16-bit stack before and a cs:eip values found at
2635  * that position on the 32-bit stack).  The ss:esp to be restored is
2636  * found relative to the 16-bit stack pointer at:
2637  *
2638  *  (ebx-4)   ss  (flat)
2639  *  (ebx-8)   sp  (32-bit stack pointer)
2640  *
2641  * The second variant of this routine, CALL32_CBClientEx, which is used
2642  * to implement KERNEL.621, has to cope with yet another problem: Here,
2643  * the 32-bit side directly returns to the caller of the CBClient thunklet,
2644  * restoring registers saved by CBClientGlueSL and cleaning up the stack.
2645  * As we have to return to our 32-bit code first, we have to adapt the
2646  * layout of our temporary area so as to include values for the registers
2647  * that are to be restored, and later (in the implementation of KERNEL.621)
2648  * we *really* restore them. The return stub restores DS, DI, SI, and BP
2649  * from the stack, skips the next 8 bytes (CBClient relay code / target),
2650  * and then performs a lret NN, where NN is the number of arguments to be
2651  * removed. Thus, we prepare our temporary area as follows:
2652  *
2653  *     (ebx+22) 16-bit cs  (this segment)
2654  *     (ebx+20) 16-bit ip  ('16-bit' return entry point)
2655  *     (ebx+16) 32-bit ss  (flat)
2656  *     (ebx+12) 32-bit sp  (32-bit stack pointer)
2657  *     (ebx+10) 16-bit bp  (points to ebx+24)
2658  *     (ebx+8)  16-bit si  (ignored)
2659  *     (ebx+6)  16-bit di  (ignored)
2660  *     (ebx+4)  16-bit ds  (we actually use the flat DS here)
2661  *     (ebx+2)  16-bit ss  (16-bit stack segment)
2662  *     (ebx+0)  16-bit sp  (points to ebx+4)
2663  *
2664  * Note that we ensure that DS is not changed and remains the flat segment,
2665  * and the 32-bit stack pointer our own return stub needs fits just 
2666  * perfectly into the 8 bytes that are skipped by the Windows stub.
2667  * One problem is that we have to determine the number of removed arguments,
2668  * as these have to be really removed in KERNEL.621. Thus, the BP value 
2669  * that we place in the temporary area to be restored, contains the value 
2670  * that SP would have if no arguments were removed. By comparing the actual
2671  * value of SP with this value in our return stub we can compute the number
2672  * of removed arguments. This is then returned to KERNEL.621.
2673  *
2674  * The stack layout of this function:
2675  * (ebp+20)  nArgs     pointer to variable receiving nr. of args (Ex only)
2676  * (ebp+16)  esi       pointer to caller's esi value
2677  * (ebp+12)  arg       ebp value to be set for relay stub
2678  * (ebp+8)   func      CBClient relay stub address
2679  * (ebp+4)   ret addr
2680  * (ebp)     ebp
2681  */
2682 static void BuildCallTo32CBClient( FILE *outfile, BOOL isEx )
2683 {
2684     char *name = isEx? "CBClientEx" : "CBClient";
2685     int size = isEx? 24 : 12;
2686
2687     /* Function header */
2688
2689     fprintf( outfile, "\n\t.align 4\n" );
2690 #ifdef USE_STABS
2691     fprintf( outfile, ".stabs \"CALL32_%s:F1\",36,0,0," PREFIX "CALL32_%s\n",
2692                       name, name );
2693 #endif
2694     fprintf( outfile, "\t.globl " PREFIX "CALL32_%s\n", name );
2695     fprintf( outfile, PREFIX "CALL32_%s:\n", name );
2696
2697     /* Entry code */
2698
2699     fprintf( outfile, "\tpushl %%ebp\n" );
2700     fprintf( outfile, "\tmovl %%esp,%%ebp\n" );
2701     fprintf( outfile, "\tpushl %%edi\n" );
2702     fprintf( outfile, "\tpushl %%esi\n" );
2703     fprintf( outfile, "\tpushl %%ebx\n" );
2704
2705     /* Get the 16-bit stack */
2706
2707     fprintf( outfile, "\t.byte 0x64\n\tmovl (%d),%%ebx\n", STACKOFFSET);
2708     
2709     /* Convert it to a flat address */
2710
2711     fprintf( outfile, "\tshldl $16,%%ebx,%%eax\n" );
2712     fprintf( outfile, "\tandl $0xfff8,%%eax\n" );
2713     fprintf( outfile, "\tmovl " PREFIX "ldt_copy(%%eax),%%esi\n" );
2714     fprintf( outfile, "\tmovw %%bx,%%ax\n" );
2715     fprintf( outfile, "\taddl %%eax,%%esi\n" );
2716
2717     /* Allocate temporary area (simulate STACK16_PUSH) */
2718
2719     fprintf( outfile, "\tpushf\n" );
2720     fprintf( outfile, "\tcld\n" );
2721     fprintf( outfile, "\tleal -%d(%%esi), %%edi\n", size );
2722     fprintf( outfile, "\tmovl $%d, %%ecx\n", sizeof(STACK16FRAME) );
2723     fprintf( outfile, "\trep\n\tmovsb\n" );
2724     fprintf( outfile, "\tpopf\n" );
2725
2726     fprintf( outfile, "\t.byte 0x64\n\tsubw $%d,(%d)\n", size, STACKOFFSET );
2727
2728     fprintf( outfile, "\tpushl %%edi\n" );  /* remember address */
2729
2730     /* Set up temporary area */
2731
2732     if ( !isEx )
2733     {
2734         fprintf( outfile, "\tleal 4(%%edi), %%edi\n" );
2735
2736         fprintf( outfile, "\tleal -8(%%esp), %%eax\n" );
2737         fprintf( outfile, "\tmovl %%eax, -8(%%edi)\n" );    /* 32-bit sp */
2738
2739         fprintf( outfile, "\tmovw %%ss, %%ax\n" );
2740         fprintf( outfile, "\tandl $0x0000ffff, %%eax\n" );
2741         fprintf( outfile, "\tmovl %%eax, -4(%%edi)\n" );    /* 32-bit ss */
2742
2743         fprintf( outfile, "\taddl $%d, %%ebx\n", sizeof(STACK16FRAME)-size+4 + 4 );
2744         fprintf( outfile, "\tmovl %%ebx, 0(%%edi)\n" );    /* 16-bit ss:sp */
2745
2746         fprintf( outfile, "\tmovl " PREFIX "CALL32_%s_RetAddr, %%eax\n", name );
2747         fprintf( outfile, "\tmovl %%eax, 4(%%edi)\n" );   /* overwrite return address */
2748     }
2749     else
2750     {
2751         fprintf( outfile, "\taddl $%d, %%ebx\n", sizeof(STACK16FRAME)-size+4 );
2752         fprintf( outfile, "\tmovl %%ebx, 0(%%edi)\n" );
2753
2754         fprintf( outfile, "\tmovw %%ds, %%ax\n" );
2755         fprintf( outfile, "\tmovw %%ax, 4(%%edi)\n" );
2756
2757         fprintf( outfile, "\taddl $20, %%ebx\n" );
2758         fprintf( outfile, "\tmovw %%bx, 10(%%edi)\n" );
2759
2760         fprintf( outfile, "\tleal -8(%%esp), %%eax\n" );
2761         fprintf( outfile, "\tmovl %%eax, 12(%%edi)\n" );
2762
2763         fprintf( outfile, "\tmovw %%ss, %%ax\n" );
2764         fprintf( outfile, "\tandl $0x0000ffff, %%eax\n" );
2765         fprintf( outfile, "\tmovl %%eax, 16(%%edi)\n" );
2766
2767         fprintf( outfile, "\tmovl " PREFIX "CALL32_%s_RetAddr, %%eax\n", name );
2768         fprintf( outfile, "\tmovl %%eax, 20(%%edi)\n" );
2769     }
2770
2771     /* Set up registers and call CBClient relay stub (simulating a far call) */
2772
2773     fprintf( outfile, "\tmovl 16(%%ebp), %%esi\n" );
2774     fprintf( outfile, "\tmovl (%%esi), %%esi\n" );
2775
2776     fprintf( outfile, "\tmovl %%edi, %%ebx\n" );
2777     fprintf( outfile, "\tmovl 8(%%ebp), %%eax\n" );
2778     fprintf( outfile, "\tmovl 12(%%ebp), %%ebp\n" );
2779
2780     fprintf( outfile, "\tpushl %%cs\n" );
2781     fprintf( outfile, "\tcall *%%eax\n" );
2782
2783     /* Return new esi value to caller */
2784
2785     fprintf( outfile, "\tmovl 32(%%esp), %%edi\n" );
2786     fprintf( outfile, "\tmovl %%esi, (%%edi)\n" );
2787
2788     /* Cleanup temporary area (simulate STACK16_POP) */
2789
2790     fprintf( outfile, "\tpop %%esi\n" );
2791
2792     fprintf( outfile, "\tpushf\n" );
2793     fprintf( outfile, "\tstd\n" );
2794     fprintf( outfile, "\tdec %%esi\n" );
2795     fprintf( outfile, "\tleal %d(%%esi), %%edi\n", size );
2796     fprintf( outfile, "\tmovl $%d, %%ecx\n", sizeof(STACK16FRAME) );
2797     fprintf( outfile, "\trep\n\tmovsb\n" );
2798     fprintf( outfile, "\tpopf\n" );
2799
2800     fprintf( outfile, "\t.byte 0x64\n\taddw $%d,(%d)\n", size, STACKOFFSET );
2801
2802     /* Return argument size to caller */
2803     if ( isEx )
2804     {
2805         fprintf( outfile, "\tmovl 32(%%esp), %%ebx\n" );
2806         fprintf( outfile, "\tmovl %%ebp, (%%ebx)\n" );
2807     }
2808
2809     /* Restore registers and return */
2810
2811     fprintf( outfile, "\tpopl %%ebx\n" );
2812     fprintf( outfile, "\tpopl %%esi\n" );
2813     fprintf( outfile, "\tpopl %%edi\n" );
2814     fprintf( outfile, "\tpopl %%ebp\n" );
2815     fprintf( outfile, "\tret\n" );
2816 }
2817
2818 static void BuildCallTo32CBClientRet( FILE *outfile, BOOL isEx )
2819 {
2820     char *name = isEx? "CBClientEx" : "CBClient";
2821
2822     /* '16-bit' return stub */
2823
2824     fprintf( outfile, "\n\t.globl " PREFIX "CALL32_%s_Ret\n", name );
2825     fprintf( outfile, PREFIX "CALL32_%s_Ret:\n", name );
2826
2827     if ( !isEx )
2828     {
2829         fprintf( outfile, "\tmovzwl %%sp, %%ebx\n" );
2830         fprintf( outfile, "\tlssl %%ss:-16(%%ebx), %%esp\n" );
2831     }
2832     else
2833     {
2834         fprintf( outfile, "\tmovzwl %%bp, %%ebx\n" );
2835         fprintf( outfile, "\tsubw %%bp, %%sp\n" );
2836         fprintf( outfile, "\tmovzwl %%sp, %%ebp\n" );
2837         fprintf( outfile, "\tlssl %%ss:-12(%%ebx), %%esp\n" );
2838     }
2839     fprintf( outfile, "\tlret\n" );
2840
2841     /* Declare the return address variable */
2842
2843     fprintf( outfile, "\n\t.globl " PREFIX "CALL32_%s_RetAddr\n", name );
2844     fprintf( outfile, PREFIX "CALL32_%s_RetAddr:\t.long 0\n", name );
2845 }
2846
2847
2848 /*******************************************************************
2849  *         BuildCallTo32LargeStack
2850  *
2851  * Build the function used to switch to the original 32-bit stack
2852  * before calling a 32-bit function from 32-bit code. This is used for
2853  * functions that need a large stack, like X bitmaps functions.
2854  *
2855  * The generated function has the following prototype:
2856  *   int xxx( int (*func)(), void *arg );
2857  *
2858  * The pointer to the function can be retrieved by calling CALL32_Init,
2859  * which also takes care of saving the current 32-bit stack pointer.
2860  * Furthermore, CALL32_Init switches to a new stack and jumps to the
2861  * specified target address.
2862  *
2863  * NOTE: The CALL32_LargeStack routine may be recursively entered by the 
2864  *       same thread, but not concurrently entered by several threads.
2865  *
2866  * Stack layout of CALL32_Init:
2867  *
2868  * (esp+12)  new stack address
2869  * (esp+8)   target address
2870  * (esp+4)   pointer to variable to receive CALL32_LargeStack address
2871  * (esp)     ret addr
2872  *
2873  * Stack layout of CALL32_LargeStack:
2874  *   ...     ...
2875  * (ebp+12)  arg
2876  * (ebp+8)   func
2877  * (ebp+4)   ret addr
2878  * (ebp)     ebp
2879  */
2880 static void BuildCallTo32LargeStack( FILE *outfile )
2881 {
2882     /* Initialization function */
2883
2884     fprintf( outfile, "\n\t.align 4\n" );
2885 #ifdef USE_STABS
2886     fprintf( outfile, ".stabs \"CALL32_Init:F1\",36,0,0," PREFIX "CALL32_Init\n");
2887 #endif
2888     fprintf( outfile, "\t.globl " PREFIX "CALL32_Init\n" );
2889     fprintf( outfile, "\t.type " PREFIX "CALL32_Init,@function\n" );
2890     fprintf( outfile, PREFIX "CALL32_Init:\n" );
2891     fprintf( outfile, "\tmovl %%esp,CALL32_Original32_esp\n" );
2892     fprintf( outfile, "\tpopl %%eax\n" );
2893     fprintf( outfile, "\tpopl %%eax\n" );
2894     fprintf( outfile, "\tmovl $CALL32_LargeStack,(%%eax)\n" );
2895     fprintf( outfile, "\tpopl %%eax\n" );
2896     fprintf( outfile, "\tpopl %%esp\n" );
2897     fprintf( outfile, "\tpushl %%eax\n" );
2898     fprintf( outfile, "\tret\n" );
2899
2900     /* Function header */
2901
2902     fprintf( outfile, "\n\t.align 4\n" );
2903 #ifdef USE_STABS
2904     fprintf( outfile, ".stabs \"CALL32_LargeStack:F1\",36,0,0,CALL32_LargeStack\n");
2905 #endif
2906     fprintf( outfile, "CALL32_LargeStack:\n" );
2907     
2908     /* Entry code */
2909
2910     fprintf( outfile, "\tpushl %%ebp\n" );
2911     fprintf( outfile, "\tmovl %%esp,%%ebp\n" );
2912
2913     /* Switch to the original 32-bit stack pointer */
2914
2915     fprintf( outfile, "\tcmpl $0, CALL32_RecursionCount\n" );
2916     fprintf( outfile, "\tjne  CALL32_skip\n" );
2917     fprintf( outfile, "\tmovl CALL32_Original32_esp, %%esp\n" );
2918     fprintf( outfile, "CALL32_skip:\n" );
2919
2920     fprintf( outfile, "\tincl CALL32_RecursionCount\n" );
2921
2922     /* Transfer the argument and call the function */
2923
2924     fprintf( outfile, "\tpushl 12(%%ebp)\n" );
2925     fprintf( outfile, "\tcall *8(%%ebp)\n" );
2926
2927     /* Restore registers and return */
2928
2929     fprintf( outfile, "\tdecl CALL32_RecursionCount\n" );
2930
2931     fprintf( outfile, "\tmovl %%ebp,%%esp\n" );
2932     fprintf( outfile, "\tpopl %%ebp\n" );
2933     fprintf( outfile, "\tret\n" );
2934
2935     /* Data */
2936
2937     fprintf( outfile, "\t.data\n" );
2938     fprintf( outfile, "CALL32_Original32_esp:\t.long 0\n" );
2939     fprintf( outfile, "CALL32_RecursionCount:\t.long 0\n" );
2940     fprintf( outfile, "\t.text\n" );
2941 }
2942
2943
2944 /*******************************************************************
2945  *         BuildCallFrom32Regs
2946  *
2947  * Build a 32-bit-to-Wine call-back function for a 'register' function.
2948  * 'args' is the number of dword arguments.
2949  *
2950  * Stack layout:
2951  *   ...
2952  * (ebp+12)  first arg
2953  * (ebp+8)   ret addr to user code
2954  * (ebp+4)   ret addr to relay code
2955  * (ebp+0)   saved ebp
2956  * (ebp-128) buffer area to allow stack frame manipulation
2957  * (ebp-332) CONTEXT86 struct
2958  * (ebp-336) CONTEXT86 *argument
2959  *  ....     other arguments copied from (ebp+12)
2960  *
2961  * The entry point routine is called with a CONTEXT* extra argument,
2962  * following the normal args. In this context structure, EIP_reg
2963  * contains the return address to user code, and ESP_reg the stack
2964  * pointer on return (with the return address and arguments already
2965  * removed).
2966  */
2967 static void BuildCallFrom32Regs( FILE *outfile )
2968 {
2969     static const int STACK_SPACE = 128 + sizeof(CONTEXT86);
2970
2971     /* Function header */
2972
2973     fprintf( outfile, "\n\t.align 4\n" );
2974 #ifdef USE_STABS
2975     fprintf( outfile, ".stabs \"CALL32_Regs:F1\",36,0,0," PREFIX "CALL32_Regs\n" );
2976 #endif
2977     fprintf( outfile, "\t.globl " PREFIX "CALL32_Regs\n" );
2978     fprintf( outfile, PREFIX "CALL32_Regs:\n" );
2979
2980     /* Allocate some buffer space on the stack */
2981
2982     fprintf( outfile, "\tpushl %%ebp\n" );
2983     fprintf( outfile, "\tmovl %%esp,%%ebp\n ");
2984     fprintf( outfile, "\tleal -%d(%%esp), %%esp\n", STACK_SPACE );
2985     
2986     /* Build the context structure */
2987
2988     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(Eax) - STACK_SPACE );
2989     fprintf( outfile, "\tpushfl\n" );
2990     fprintf( outfile, "\tpopl %%eax\n" );
2991     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(EFlags) - STACK_SPACE );
2992     fprintf( outfile, "\tmovl 0(%%ebp),%%eax\n" );
2993     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(Ebp) - STACK_SPACE );
2994     fprintf( outfile, "\tmovl %%ebx,%d(%%ebp)\n", CONTEXTOFFSET(Ebx) - STACK_SPACE );
2995     fprintf( outfile, "\tmovl %%ecx,%d(%%ebp)\n", CONTEXTOFFSET(Ecx) - STACK_SPACE );
2996     fprintf( outfile, "\tmovl %%edx,%d(%%ebp)\n", CONTEXTOFFSET(Edx) - STACK_SPACE );
2997     fprintf( outfile, "\tmovl %%esi,%d(%%ebp)\n", CONTEXTOFFSET(Esi) - STACK_SPACE );
2998     fprintf( outfile, "\tmovl %%edi,%d(%%ebp)\n", CONTEXTOFFSET(Edi) - STACK_SPACE );
2999
3000     fprintf( outfile, "\txorl %%eax,%%eax\n" );
3001     fprintf( outfile, "\tmovw %%cs,%%ax\n" );
3002     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(SegCs) - STACK_SPACE );
3003     fprintf( outfile, "\tmovw %%es,%%ax\n" );
3004     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(SegEs) - STACK_SPACE );
3005     fprintf( outfile, "\tmovw %%fs,%%ax\n" );
3006     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(SegFs) - STACK_SPACE );
3007     fprintf( outfile, "\tmovw %%gs,%%ax\n" );
3008     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(SegGs) - STACK_SPACE );
3009     fprintf( outfile, "\tmovw %%ss,%%ax\n" );
3010     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(SegSs) - STACK_SPACE );
3011     fprintf( outfile, "\tmovw %%ds,%%ax\n" );
3012     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(SegDs) - STACK_SPACE );
3013     fprintf( outfile, "\tmovw %%ax,%%es\n" );  /* set %es equal to %ds just in case */
3014
3015     fprintf( outfile, "\tmovl $0x%x,%%eax\n", CONTEXT86_FULL );
3016     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(ContextFlags) - STACK_SPACE );
3017
3018     fprintf( outfile, "\tmovl 8(%%ebp),%%eax\n" ); /* Get %eip at time of call */
3019     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(Eip) - STACK_SPACE );
3020
3021     /* Transfer the arguments */
3022
3023     fprintf( outfile, "\tmovl 4(%%ebp),%%ebx\n" );   /* get relay code addr */
3024     fprintf( outfile, "\tpushl %%esp\n" );           /* push ptr to context struct */
3025     fprintf( outfile, "\tmovzbl 4(%%ebx),%%ecx\n" ); /* fetch number of args to copy */
3026     fprintf( outfile, "\tjecxz 1f\n" );
3027     fprintf( outfile, "\tsubl %%ecx,%%esp\n" );
3028     fprintf( outfile, "\tleal 12(%%ebp),%%esi\n" );  /* get %esp at time of call */
3029     fprintf( outfile, "\tmovl %%esp,%%edi\n" );
3030     fprintf( outfile, "\tshrl $2,%%ecx\n" );
3031     fprintf( outfile, "\tcld\n" );
3032     fprintf( outfile, "\trep\n\tmovsl\n" );  /* copy args */
3033
3034     fprintf( outfile, "1:\tmovzbl 5(%%ebx),%%eax\n" ); /* fetch number of args to remove */
3035     fprintf( outfile, "\tleal 12(%%ebp,%%eax),%%eax\n" );
3036     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(Esp) - STACK_SPACE );
3037
3038     /* Call the entry point */
3039
3040     fprintf( outfile, "\tcall *0(%%ebx)\n" );
3041
3042     /* Store %eip and %ebp onto the new stack */
3043
3044     fprintf( outfile, "\tmovl %d(%%ebp),%%edx\n", CONTEXTOFFSET(Esp) - STACK_SPACE );
3045     fprintf( outfile, "\tmovl %d(%%ebp),%%eax\n", CONTEXTOFFSET(Eip) - STACK_SPACE );
3046     fprintf( outfile, "\tmovl %%eax,-4(%%edx)\n" );
3047     fprintf( outfile, "\tmovl %d(%%ebp),%%eax\n", CONTEXTOFFSET(Ebp) - STACK_SPACE );
3048     fprintf( outfile, "\tmovl %%eax,-8(%%edx)\n" );
3049
3050     /* Restore the context structure */
3051
3052     /* Note: we don't bother to restore %cs, %ds and %ss
3053      *       changing them in 32-bit code is a recipe for disaster anyway
3054      */
3055     fprintf( outfile, "\tmovl %d(%%ebp),%%eax\n", CONTEXTOFFSET(SegEs) - STACK_SPACE );
3056     fprintf( outfile, "\tmovw %%ax,%%es\n" );
3057     fprintf( outfile, "\tmovl %d(%%ebp),%%eax\n", CONTEXTOFFSET(SegFs) - STACK_SPACE );
3058     fprintf( outfile, "\tmovw %%ax,%%fs\n" );
3059     fprintf( outfile, "\tmovl %d(%%ebp),%%eax\n", CONTEXTOFFSET(SegGs) - STACK_SPACE );
3060     fprintf( outfile, "\tmovw %%ax,%%gs\n" );
3061
3062     fprintf( outfile, "\tmovl %d(%%ebp),%%edi\n", CONTEXTOFFSET(Edi) - STACK_SPACE );
3063     fprintf( outfile, "\tmovl %d(%%ebp),%%esi\n", CONTEXTOFFSET(Esi) - STACK_SPACE );
3064     fprintf( outfile, "\tmovl %d(%%ebp),%%edx\n", CONTEXTOFFSET(Edx) - STACK_SPACE );
3065     fprintf( outfile, "\tmovl %d(%%ebp),%%ecx\n", CONTEXTOFFSET(Ecx) - STACK_SPACE );
3066     fprintf( outfile, "\tmovl %d(%%ebp),%%ebx\n", CONTEXTOFFSET(Ebx) - STACK_SPACE );
3067
3068     fprintf( outfile, "\tmovl %d(%%ebp),%%eax\n", CONTEXTOFFSET(EFlags) - STACK_SPACE );
3069     fprintf( outfile, "\tpushl %%eax\n" );
3070     fprintf( outfile, "\tpopfl\n" );
3071     fprintf( outfile, "\tmovl %d(%%ebp),%%eax\n", CONTEXTOFFSET(Eax) - STACK_SPACE );
3072
3073     fprintf( outfile, "\tmovl %d(%%ebp),%%ebp\n", CONTEXTOFFSET(Esp) - STACK_SPACE );
3074     fprintf( outfile, "\tleal -8(%%ebp),%%esp\n" );
3075     fprintf( outfile, "\tpopl %%ebp\n" );
3076     fprintf( outfile, "\tret\n" );
3077 }
3078
3079
3080 /*******************************************************************
3081  *         BuildGlue
3082  *
3083  * Build the 16-bit-to-Wine/Wine-to-16-bit callback glue code
3084  */
3085 static void BuildGlue( FILE *outfile, FILE *infile )
3086 {
3087     char buffer[1024];
3088
3089     /* File header */
3090
3091     fprintf( outfile, "/* File generated automatically from %s; do not edit! */\n\n",
3092              input_file_name );
3093     fprintf( outfile, "#include \"builtin16.h\"\n" );
3094     fprintf( outfile, "#include \"stackframe.h\"\n\n" );
3095
3096     /* Build the callback glue functions */
3097
3098     while (fgets( buffer, sizeof(buffer), infile ))
3099     {
3100         if (strstr( buffer, "### start build ###" )) break;
3101     }
3102     while (fgets( buffer, sizeof(buffer), infile ))
3103     {
3104         char *p; 
3105         if ( (p = strstr( buffer, "CallFrom16_" )) != NULL )
3106         {
3107             char *q, *profile = p + strlen( "CallFrom16_" );
3108             for (q = profile; (*q == '_') || isalpha(*q); q++ )
3109                 ;
3110             *q = '\0';
3111             for (q = p-1; q > buffer && ((*q == '_') || isalnum(*q)); q-- )
3112                 ;
3113             if ( ++q < p ) p[-1] = '\0'; else q = "";
3114             BuildCallFrom16Func( outfile, profile, q, FALSE );
3115         }
3116         if ( (p = strstr( buffer, "CallTo16_" )) != NULL )
3117         {
3118             char *q, *profile = p + strlen( "CallTo16_" );
3119             for (q = profile; (*q == '_') || isalpha(*q); q++ )
3120                 ;
3121             *q = '\0';
3122             for (q = p-1; q > buffer && ((*q == '_') || isalnum(*q)); q-- )
3123                 ;
3124             if ( ++q < p ) p[-1] = '\0'; else q = "";
3125             BuildCallTo16Func( outfile, profile, q );
3126         }
3127         if (strstr( buffer, "### stop build ###" )) break;
3128     }
3129
3130     fclose( infile );
3131 }
3132
3133 /*******************************************************************
3134  *         BuildCall16
3135  *
3136  * Build the 16-bit callbacks
3137  */
3138 static void BuildCall16( FILE *outfile )
3139 {
3140     /* File header */
3141
3142     fprintf( outfile, "/* File generated automatically. Do not edit! */\n\n" );
3143     fprintf( outfile, "\t.text\n" );
3144
3145 #ifdef __i386__
3146
3147 #ifdef USE_STABS
3148     if (output_file_name)
3149     {
3150         char buffer[1024];
3151         getcwd(buffer, sizeof(buffer));
3152         fprintf( outfile, "\t.file\t\"%s\"\n", output_file_name );
3153
3154         /*
3155          * The stabs help the internal debugger as they are an indication that it
3156          * is sensible to step into a thunk/trampoline.
3157          */
3158         fprintf( outfile, ".stabs \"%s/\",100,0,0,Code_Start\n", buffer);
3159         fprintf( outfile, ".stabs \"%s\",100,0,0,Code_Start\n", output_file_name );
3160         fprintf( outfile, "Code_Start:\n\n" );
3161     }
3162 #endif
3163     fprintf( outfile, PREFIX"Call16_Start:\n" );
3164     fprintf( outfile, "\t.globl "PREFIX"Call16_Start\n" );
3165     fprintf( outfile, "\t.byte 0\n\n" );
3166
3167
3168     /* Standard CallFrom16 routine (WORD return) */
3169     BuildCallFrom16Core( outfile, FALSE, FALSE, TRUE );
3170
3171     /* Standard CallFrom16 routine (DWORD return) */
3172     BuildCallFrom16Core( outfile, FALSE, FALSE, FALSE );
3173
3174     /* Register CallFrom16 routine */
3175     BuildCallFrom16Core( outfile, TRUE, FALSE, FALSE );
3176
3177     /* C16ThkSL CallFrom16 routine */
3178     BuildCallFrom16Core( outfile, FALSE, TRUE, FALSE );
3179
3180     /* Standard CallTo16 routine (WORD return) */
3181     BuildCallTo16Core( outfile, TRUE, FALSE );
3182
3183     /* Standard CallTo16 routine (DWORD return) */
3184     BuildCallTo16Core( outfile, FALSE, FALSE );
3185
3186     /* Register CallTo16 routine (16:16 retf) */
3187     BuildCallTo16Core( outfile, FALSE, 1 );
3188
3189     /* Register CallTo16 routine (16:32 retf) */
3190     BuildCallTo16Core( outfile, FALSE, 2 );
3191
3192     /* CBClientThunkSL routine */
3193     BuildCallTo32CBClient( outfile, FALSE );
3194
3195     /* CBClientThunkSLEx routine */
3196     BuildCallTo32CBClient( outfile, TRUE  );
3197
3198     fprintf( outfile, PREFIX"Call16_End:\n" );
3199     fprintf( outfile, "\t.globl "PREFIX"Call16_End\n" );
3200
3201 #ifdef USE_STABS
3202     fprintf( outfile, "\t.stabs \"\",100,0,0,.Letext\n");
3203     fprintf( outfile, ".Letext:\n");
3204 #endif
3205
3206     /* The whole Call16_Ret segment must lie within the .data section */
3207     fprintf( outfile, "\n\t.data\n" );
3208     fprintf( outfile, "\t.globl " PREFIX "Call16_Ret_Start\n" );
3209     fprintf( outfile, PREFIX "Call16_Ret_Start:\n" );
3210
3211     /* Standard CallTo16 return stub */
3212     BuildRet16Func( outfile );
3213
3214     /* CBClientThunkSL return stub */
3215     BuildCallTo32CBClientRet( outfile, FALSE );
3216
3217     /* CBClientThunkSLEx return stub */
3218     BuildCallTo32CBClientRet( outfile, TRUE  );
3219
3220     /* End of Call16_Ret segment */
3221     fprintf( outfile, "\n\t.globl " PREFIX "Call16_Ret_End\n" );
3222     fprintf( outfile, PREFIX "Call16_Ret_End:\n" );
3223
3224 #else  /* __i386__ */
3225
3226     fprintf( outfile, PREFIX"Call16_Start:\n" );
3227     fprintf( outfile, "\t.globl "PREFIX"Call16_Start\n" );
3228     fprintf( outfile, "\t.byte 0\n\n" );
3229     fprintf( outfile, PREFIX"Call16_End:\n" );
3230     fprintf( outfile, "\t.globl "PREFIX"Call16_End\n" );
3231
3232     fprintf( outfile, "\t.globl " PREFIX "Call16_Ret_Start\n" );
3233     fprintf( outfile, PREFIX "Call16_Ret_Start:\n" );
3234     fprintf( outfile, "\t.byte 0\n\n" );
3235     fprintf( outfile, "\n\t.globl " PREFIX "Call16_Ret_End\n" );
3236     fprintf( outfile, PREFIX "Call16_Ret_End:\n" );
3237
3238 #endif  /* __i386__ */
3239 }
3240
3241 /*******************************************************************
3242  *         BuildCall32
3243  *
3244  * Build the 32-bit callbacks
3245  */
3246 static void BuildCall32( FILE *outfile )
3247 {
3248     /* File header */
3249
3250     fprintf( outfile, "/* File generated automatically. Do not edit! */\n\n" );
3251     fprintf( outfile, "\t.text\n" );
3252
3253 #ifdef __i386__
3254
3255 #ifdef USE_STABS
3256     if (output_file_name)
3257     {
3258         char buffer[1024];
3259         getcwd(buffer, sizeof(buffer));
3260         fprintf( outfile, "\t.file\t\"%s\"\n", output_file_name );
3261
3262         /*
3263          * The stabs help the internal debugger as they are an indication that it
3264          * is sensible to step into a thunk/trampoline.
3265          */
3266         fprintf( outfile, ".stabs \"%s/\",100,0,0,Code_Start\n", buffer);
3267         fprintf( outfile, ".stabs \"%s\",100,0,0,Code_Start\n", output_file_name );
3268         fprintf( outfile, "Code_Start:\n" );
3269     }
3270 #endif
3271
3272     /* Build the 32-bit large stack callback */
3273
3274     BuildCallTo32LargeStack( outfile );
3275
3276     /* Build the register callback function */
3277
3278     BuildCallFrom32Regs( outfile );
3279
3280 #ifdef USE_STABS
3281     fprintf( outfile, "\t.text\n");
3282     fprintf( outfile, "\t.stabs \"\",100,0,0,.Letext\n");
3283     fprintf( outfile, ".Letext:\n");
3284 #endif
3285
3286 #else  /* __i386__ */
3287
3288     /* Just to avoid an empty file */
3289     fprintf( outfile, "\t.long 0\n" );
3290
3291 #endif  /* __i386__ */
3292 }
3293
3294
3295 /*******************************************************************
3296  *         usage
3297  */
3298 static void usage(void)
3299 {
3300     fprintf( stderr,
3301              "usage: build [-pic] [-o outfile] -spec SPEC_FILE\n"
3302              "       build [-pic] [-o outfile] -glue SOURCE_FILE\n"
3303              "       build [-pic] [-o outfile] -call16\n"
3304              "       build [-pic] [-o outfile] -call32\n" );
3305     if (output_file_name) unlink( output_file_name );
3306     exit(1);
3307 }
3308
3309
3310 /*******************************************************************
3311  *         open_input
3312  */
3313 static FILE *open_input( const char *name )
3314 {
3315     FILE *f;
3316
3317     if (!name)
3318     {
3319         input_file_name = "<stdin>";
3320         return stdin;
3321     }
3322     input_file_name = name;
3323     if (!(f = fopen( name, "r" )))
3324     {
3325         fprintf( stderr, "Cannot open input file '%s'\n", name );
3326         if (output_file_name) unlink( output_file_name );
3327         exit(1);
3328     }
3329     return f;
3330 }
3331
3332 /*******************************************************************
3333  *         main
3334  */
3335 int main(int argc, char **argv)
3336 {
3337     FILE *outfile = stdout;
3338
3339     if (argc < 2) usage();
3340
3341     if (!strcmp( argv[1], "-pic" ))
3342     {
3343         UsePIC = 1;
3344         argv += 1;
3345         argc -= 1;
3346         if (argc < 2) usage();
3347     }
3348
3349     if (!strcmp( argv[1], "-o" ))
3350     {
3351         output_file_name = argv[2];
3352         argv += 2;
3353         argc -= 2;
3354         if (argc < 2) usage();
3355         if (!(outfile = fopen( output_file_name, "w" )))
3356         {
3357             fprintf( stderr, "Unable to create output file '%s'\n", output_file_name );
3358             exit(1);
3359         }
3360     }
3361
3362     /* Retrieve the selector values; this assumes that we are building
3363      * the asm files on the platform that will also run them. Probably
3364      * a safe assumption to make.
3365      */
3366     Code_Selector = __get_cs();
3367     Data_Selector = __get_ds();
3368
3369     if (!strcmp( argv[1], "-spec" )) BuildSpecFile( outfile, open_input( argv[2] ) );
3370     else if (!strcmp( argv[1], "-glue" )) BuildGlue( outfile, open_input( argv[2] ) );
3371     else if (!strcmp( argv[1], "-call16" )) BuildCall16( outfile );
3372     else if (!strcmp( argv[1], "-call32" )) BuildCall32( outfile );
3373     else
3374     {
3375         fclose( outfile );
3376         usage();
3377     }
3378
3379     fclose( outfile );
3380     return 0;
3381 }