- Updated API files.
[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             strupper(DLLName);
702         }
703         else if (strcmp(token, "file") == 0)
704         {
705             strcpy(DLLFileName, GetToken());
706             strupper(DLLFileName);
707         }
708         else if (strcmp(token, "type") == 0)
709         {
710             token = GetToken();
711             if (!strcmp(token, "win16" )) SpecType = SPEC_WIN16;
712             else if (!strcmp(token, "win32" )) SpecType = SPEC_WIN32;
713             else fatal_error( "Type must be 'win16' or 'win32'\n" );
714         }
715         else if (strcmp(token, "mode") == 0)
716         {
717             token = GetToken();
718             if (!strcmp(token, "dll" )) SpecMode = SPEC_MODE_DLL;
719             else if (!strcmp(token, "guiexe" )) SpecMode = SPEC_MODE_GUIEXE;
720             else if (!strcmp(token, "cuiexe" )) SpecMode = SPEC_MODE_CUIEXE;
721             else fatal_error( "Mode must be 'dll', 'guiexe' or 'cuiexe'\n" );
722         }
723         else if (strcmp(token, "heap") == 0)
724         {
725             token = GetToken();
726             if (!IsNumberString(token)) fatal_error( "Expected number after heap\n" );
727             DLLHeapSize = atoi(token);
728         }
729         else if (strcmp(token, "init") == 0)
730         {
731             strcpy(DLLInitFunc, GetToken());
732             if (SpecType == SPEC_WIN16)
733                 fatal_error( "init cannot be used for Win16 spec files\n" );
734             if (!DLLInitFunc[0])
735                 fatal_error( "Expected function name after init\n" );
736             if (!strcmp(DLLInitFunc, "main"))
737                 fatal_error( "The init function cannot be named 'main'\n" );
738         }
739         else if (strcmp(token, "import") == 0)
740         {
741             if (nb_imports >= MAX_IMPORTS)
742                 fatal_error( "Too many imports (limit %d)\n", MAX_IMPORTS );
743             if (SpecType != SPEC_WIN32)
744                 fatal_error( "Imports not supported for Win16\n" );
745             DLLImports[nb_imports++] = xstrdup(GetToken());
746         }
747         else if (strcmp(token, "rsrc") == 0)
748         {
749             strcpy( rsrc_name, GetToken() );
750             strcat( rsrc_name, "_ResourceDescriptor" );
751         }
752         else if (strcmp(token, "@") == 0)
753         {
754             if (SpecType != SPEC_WIN32)
755                 fatal_error( "'@' ordinals not supported for Win16\n" );
756             ParseOrdinal( -1 );
757         }
758         else if (IsNumberString(token))
759         {
760             ParseOrdinal( atoi(token) );
761         }
762         else
763             fatal_error( "Expected name, id, length or ordinal\n" );
764     }
765
766     if (!DLLFileName[0])
767     {
768         if (SpecMode == SPEC_MODE_DLL)
769             sprintf( DLLFileName, "%s.DLL", DLLName );
770         else
771             sprintf( DLLFileName, "%s.EXE", DLLName );
772     }
773 }
774
775
776 /*******************************************************************
777  *         StoreVariableCode
778  *
779  * Store a list of ints into a byte array.
780  */
781 static int StoreVariableCode( unsigned char *buffer, int size, ORDDEF *odp )
782 {
783     int i;
784
785     switch(size)
786     {
787     case 1:
788         for (i = 0; i < odp->u.var.n_values; i++)
789             buffer[i] = odp->u.var.values[i];
790         break;
791     case 2:
792         for (i = 0; i < odp->u.var.n_values; i++)
793             ((unsigned short *)buffer)[i] = odp->u.var.values[i];
794         break;
795     case 4:
796         for (i = 0; i < odp->u.var.n_values; i++)
797             ((unsigned int *)buffer)[i] = odp->u.var.values[i];
798         break;
799     }
800     return odp->u.var.n_values * size;
801 }
802
803
804 /*******************************************************************
805  *         DumpBytes
806  *
807  * Dump a byte stream into the assembly code.
808  */
809 static void DumpBytes( FILE *outfile, const unsigned char *data, int len,
810                        const char *label )
811 {
812     int i;
813
814     fprintf( outfile, "\nstatic BYTE %s[] = \n{", label );
815
816     for (i = 0; i < len; i++)
817     {
818         if (!(i & 0x0f)) fprintf( outfile, "\n    " );
819         fprintf( outfile, "%d", *data++ );
820         if (i < len - 1) fprintf( outfile, ", " );
821     }
822     fprintf( outfile, "\n};\n" );
823 }
824
825
826 /*******************************************************************
827  *         BuildModule16
828  *
829  * Build the in-memory representation of a 16-bit NE module, and dump it
830  * as a byte stream into the assembly code.
831  */
832 static int BuildModule16( FILE *outfile, int max_code_offset,
833                           int max_data_offset )
834 {
835     int i;
836     char *buffer;
837     NE_MODULE *pModule;
838     SEGTABLEENTRY *pSegment;
839     OFSTRUCT *pFileInfo;
840     BYTE *pstr;
841     WORD *pword;
842     ET_BUNDLE *bundle = 0;
843     ET_ENTRY *entry = 0;
844
845     /*   Module layout:
846      * NE_MODULE       Module
847      * OFSTRUCT        File information
848      * SEGTABLEENTRY   Segment 1 (code)
849      * SEGTABLEENTRY   Segment 2 (data)
850      * WORD[2]         Resource table (empty)
851      * BYTE[2]         Imported names (empty)
852      * BYTE[n]         Resident names table
853      * BYTE[n]         Entry table
854      */
855
856     buffer = xmalloc( 0x10000 );
857
858     pModule = (NE_MODULE *)buffer;
859     memset( pModule, 0, sizeof(*pModule) );
860     pModule->magic = IMAGE_OS2_SIGNATURE;
861     pModule->count = 1;
862     pModule->next = 0;
863     pModule->flags = NE_FFLAGS_SINGLEDATA | NE_FFLAGS_BUILTIN | NE_FFLAGS_LIBMODULE;
864     pModule->dgroup = 2;
865     pModule->heap_size = DLLHeapSize;
866     pModule->stack_size = 0;
867     pModule->ip = 0;
868     pModule->cs = 0;
869     pModule->sp = 0;
870     pModule->ss = 0;
871     pModule->seg_count = 2;
872     pModule->modref_count = 0;
873     pModule->nrname_size = 0;
874     pModule->modref_table = 0;
875     pModule->nrname_fpos = 0;
876     pModule->moveable_entries = 0;
877     pModule->alignment = 0;
878     pModule->truetype = 0;
879     pModule->os_flags = NE_OSFLAGS_WINDOWS;
880     pModule->misc_flags = 0;
881     pModule->dlls_to_init  = 0;
882     pModule->nrname_handle = 0;
883     pModule->min_swap_area = 0;
884     pModule->expected_version = 0;
885     pModule->module32 = 0;
886     pModule->self = 0;
887     pModule->self_loading_sel = 0;
888
889       /* File information */
890
891     pFileInfo = (OFSTRUCT *)(pModule + 1);
892     pModule->fileinfo = (int)pFileInfo - (int)pModule;
893     memset( pFileInfo, 0, sizeof(*pFileInfo) - sizeof(pFileInfo->szPathName) );
894     pFileInfo->cBytes = sizeof(*pFileInfo) - sizeof(pFileInfo->szPathName)
895                         + strlen(DLLFileName);
896     strcpy( pFileInfo->szPathName, DLLFileName );
897     pstr = (char *)pFileInfo + pFileInfo->cBytes + 1;
898         
899 #ifdef __i386__  /* FIXME: Alignment problems! */
900
901       /* Segment table */
902
903     pSegment = (SEGTABLEENTRY *)pstr;
904     pModule->seg_table = (int)pSegment - (int)pModule;
905     pSegment->filepos = 0;
906     pSegment->size = max_code_offset;
907     pSegment->flags = 0;
908     pSegment->minsize = max_code_offset;
909     pSegment->hSeg = 0;
910     pSegment++;
911
912     pModule->dgroup_entry = (int)pSegment - (int)pModule;
913     pSegment->filepos = 0;
914     pSegment->size = max_data_offset;
915     pSegment->flags = NE_SEGFLAGS_DATA;
916     pSegment->minsize = max_data_offset;
917     pSegment->hSeg = 0;
918     pSegment++;
919
920       /* Resource table */
921
922     pword = (WORD *)pSegment;
923     pModule->res_table = (int)pword - (int)pModule;
924     *pword++ = 0;
925     *pword++ = 0;
926
927       /* Imported names table */
928
929     pstr = (char *)pword;
930     pModule->import_table = (int)pstr - (int)pModule;
931     *pstr++ = 0;
932     *pstr++ = 0;
933
934       /* Resident names table */
935
936     pModule->name_table = (int)pstr - (int)pModule;
937     /* First entry is module name */
938     *pstr = strlen(DLLName );
939     strcpy( pstr + 1, DLLName );
940     pstr += *pstr + 1;
941     *(WORD *)pstr = 0;
942     pstr += sizeof(WORD);
943     /* Store all ordinals */
944     for (i = 1; i <= Limit; i++)
945     {
946         ORDDEF *odp = Ordinals[i];
947         if (!odp || !odp->name[0]) continue;
948         *pstr = strlen( odp->name );
949         strcpy( pstr + 1, odp->name );
950         strupper( pstr + 1 );
951         pstr += *pstr + 1;
952         *(WORD *)pstr = i;
953         pstr += sizeof(WORD);
954     }
955     *pstr++ = 0;
956
957       /* Entry table */
958
959     pModule->entry_table = (int)pstr - (int)pModule;
960     for (i = 1; i <= Limit; i++)
961     {
962         int selector = 0;
963         ORDDEF *odp = Ordinals[i];
964         if (!odp) continue;
965
966         switch (odp->type)
967         {
968         case TYPE_CDECL:
969         case TYPE_PASCAL:
970         case TYPE_PASCAL_16:
971         case TYPE_REGISTER:
972         case TYPE_INTERRUPT:
973         case TYPE_STUB:
974             selector = 1;  /* Code selector */
975             break;
976
977         case TYPE_BYTE:
978         case TYPE_WORD:
979         case TYPE_LONG:
980             selector = 2;  /* Data selector */
981             break;
982
983         case TYPE_ABS:
984             selector = 0xfe;  /* Constant selector */
985             break;
986
987         default:
988             selector = 0;  /* Invalid selector */
989             break;
990         }
991
992         if ( !selector )
993            continue;
994
995         if ( bundle && bundle->last+1 == i )
996             bundle->last++;
997         else
998         {
999             if ( bundle )
1000                 bundle->next = (char *)pstr - (char *)pModule;
1001
1002             bundle = (ET_BUNDLE *)pstr;
1003             bundle->first = i-1;
1004             bundle->last = i;
1005             bundle->next = 0;
1006             pstr += sizeof(ET_BUNDLE);
1007         }
1008
1009         /* FIXME: is this really correct ?? */
1010         entry = (ET_ENTRY *)pstr;
1011         entry->type = 0xff;  /* movable */
1012         entry->flags = 3; /* exported & public data */
1013         entry->segnum = selector;
1014         entry->offs = odp->offset;
1015         pstr += sizeof(ET_ENTRY);
1016     }
1017     *pstr++ = 0;
1018 #endif
1019
1020       /* Dump the module content */
1021
1022     DumpBytes( outfile, (char *)pModule, (int)pstr - (int)pModule,
1023                "Module" );
1024     return (int)pstr - (int)pModule;
1025 }
1026
1027
1028 /*******************************************************************
1029  *         BuildSpec32File
1030  *
1031  * Build a Win32 C file from a spec file.
1032  */
1033 static int BuildSpec32File( FILE *outfile )
1034 {
1035     ORDDEF *odp;
1036     int i, fwd_size = 0, have_regs = FALSE;
1037     int nr_exports;
1038     const char *init_func;
1039
1040     AssignOrdinals();
1041     nr_exports = Base <= Limit ? Limit - Base + 1 : 0;
1042
1043     fprintf( outfile, "/* File generated automatically from %s; do not edit! */\n\n",
1044              input_file_name );
1045     fprintf( outfile, "#include \"builtin32.h\"\n\n" );
1046     fprintf( outfile, "static const BUILTIN32_DESCRIPTOR descriptor;\n" );
1047
1048     /* Output the DLL functions prototypes */
1049
1050     for (i = 0, odp = EntryPoints; i < nb_entry_points; i++, odp++)
1051     {
1052         switch(odp->type)
1053         {
1054         case TYPE_EXTERN:
1055             fprintf( outfile, "extern void %s();\n", odp->u.ext.link_name );
1056             break;
1057         case TYPE_STDCALL:
1058         case TYPE_VARARGS:
1059         case TYPE_CDECL:
1060             fprintf( outfile, "extern void %s();\n", odp->u.func.link_name );
1061             break;
1062         case TYPE_FORWARD:
1063             fwd_size += strlen(odp->u.fwd.link_name) + 1;
1064             break;
1065         case TYPE_REGISTER:
1066             fprintf( outfile, "extern void __regs_%d();\n", odp->ordinal );
1067             have_regs = TRUE;
1068             break;
1069         case TYPE_STUB:
1070             fprintf( outfile, "static void __stub_%d() { BUILTIN32_Unimplemented(&descriptor,%d); }\n",
1071                      odp->ordinal, odp->ordinal );
1072             break;
1073         default:
1074             fprintf(stderr,"build: function type %d not available for Win32\n",
1075                     odp->type);
1076             return -1;
1077         }
1078     }
1079
1080     /* Output code for all register functions */
1081
1082     if ( have_regs )
1083     { 
1084         fprintf( outfile, "#ifndef __GNUC__\n" );
1085         fprintf( outfile, "static void __asm__dummy(void) {\n" );
1086         fprintf( outfile, "#endif /* !defined(__GNUC__) */\n" );
1087         for (i = 0, odp = EntryPoints; i < nb_entry_points; i++, odp++)
1088         {
1089             if (odp->type != TYPE_REGISTER) continue;
1090             fprintf( outfile,
1091                      "asm(\".align 4\\n\\t\"\n"
1092                      "    \".type " PREFIX "__regs_%d,@function\\n\\t\"\n"
1093                      "    \"" PREFIX "__regs_%d:\\n\\t\"\n"
1094                      "    \"call " PREFIX "CALL32_Regs\\n\\t\"\n"
1095                      "    \".long " PREFIX "%s\\n\\t\"\n"
1096                      "    \".byte %d,%d\");\n",
1097                      odp->ordinal, odp->ordinal, odp->u.func.link_name,
1098                      4 * strlen(odp->u.func.arg_types),
1099                      4 * strlen(odp->u.func.arg_types) );
1100         }
1101         fprintf( outfile, "#ifndef __GNUC__\n" );
1102         fprintf( outfile, "}\n" );
1103         fprintf( outfile, "#endif /* !defined(__GNUC__) */\n" );
1104     }
1105
1106     if (nb_names)
1107     {
1108         /* Output the DLL names table */
1109
1110         fprintf( outfile, "static const char * const FuncNames[%d] =\n{\n", nb_names );
1111         for (i = 0; i < nb_names; i++)
1112         {
1113             if (i) fprintf( outfile, ",\n" );
1114             fprintf( outfile, "    \"%s\"", Names[i]->name );
1115         }
1116         fprintf( outfile, "\n};\n\n" );
1117
1118         /* Output the DLL ordinals table */
1119
1120         fprintf( outfile, "static const unsigned short FuncOrdinals[%d] =\n{\n", nb_names );
1121         for (i = 0; i < nb_names; i++)
1122         {
1123             if (i) fprintf( outfile, ",\n" );
1124             fprintf( outfile, "    %d", Names[i]->ordinal - Base );
1125         }
1126         fprintf( outfile, "\n};\n\n" );
1127     }
1128
1129     if (nr_exports) 
1130     {
1131         /* Output the DLL functions table */
1132
1133         fprintf( outfile, "\nstatic const ENTRYPOINT32 Functions[%d] =\n{\n",
1134                  nr_exports );
1135         for (i = Base; i <= Limit; i++)
1136         {
1137             ORDDEF *odp = Ordinals[i];
1138             if (!odp) fprintf( outfile, "    0" );
1139             else switch(odp->type)
1140             {
1141             case TYPE_EXTERN:
1142                 fprintf( outfile, "    %s", odp->u.ext.link_name );
1143                 break;
1144             case TYPE_STDCALL:
1145             case TYPE_VARARGS:
1146             case TYPE_CDECL:
1147                 fprintf( outfile, "    %s", odp->u.func.link_name);
1148                 break;
1149             case TYPE_STUB:
1150                 fprintf( outfile, "    __stub_%d", i );
1151                 break;
1152             case TYPE_REGISTER:
1153                 fprintf( outfile, "    __regs_%d", i );
1154                 break;
1155             case TYPE_FORWARD:
1156                 fprintf( outfile, "    (ENTRYPOINT32)\"%s\"", odp->u.fwd.link_name );
1157                 break;
1158             default:
1159                 return -1;
1160             }
1161             if (i < Limit) fprintf( outfile, ",\n" );
1162         }
1163         fprintf( outfile, "\n};\n\n" );
1164
1165         /* Output the DLL argument types */
1166
1167         fprintf( outfile, "static const unsigned int ArgTypes[%d] =\n{\n",
1168                  nr_exports );
1169         for (i = Base; i <= Limit; i++)
1170         {
1171             ORDDEF *odp = Ordinals[i];
1172             unsigned int j, mask = 0;
1173             if (odp &&
1174                 ((odp->type == TYPE_STDCALL) || (odp->type == TYPE_CDECL) ||
1175                 (odp->type == TYPE_REGISTER)))
1176                 for (j = 0; odp->u.func.arg_types[j]; j++)
1177                 {
1178                     if (odp->u.func.arg_types[j] == 't') mask |= 1<< (j*2);
1179                     if (odp->u.func.arg_types[j] == 'W') mask |= 2<< (j*2);
1180                 }
1181                 fprintf( outfile, "    %d", mask );
1182                 if (i < Limit) fprintf( outfile, ",\n" );
1183         }
1184         fprintf( outfile, "\n};\n\n" );
1185
1186         /* Output the DLL functions arguments */
1187
1188         fprintf( outfile, "static const unsigned char FuncArgs[%d] =\n{\n",
1189                  nr_exports );
1190         for (i = Base; i <= Limit; i++)
1191         {
1192             unsigned char args = 0xff;
1193             ORDDEF *odp = Ordinals[i];
1194             if (odp) switch(odp->type)
1195             {
1196             case TYPE_STDCALL:
1197                 args = (unsigned char)strlen(odp->u.func.arg_types);
1198                 break;
1199             case TYPE_CDECL:
1200                 args = 0x80 | (unsigned char)strlen(odp->u.func.arg_types);
1201                 break;
1202             case TYPE_REGISTER:
1203                 args = 0x40 | (unsigned char)strlen(odp->u.func.arg_types);
1204                 break;
1205             case TYPE_FORWARD:
1206                 args = 0xfd;
1207                 break;
1208             default:
1209                 args = 0xff;
1210                 break;
1211             }
1212             fprintf( outfile, "    0x%02x", args );
1213             if (i < Limit) fprintf( outfile, ",\n" );
1214         }
1215         fprintf( outfile, "\n};\n\n" );
1216     }
1217
1218     /* Output the DLL imports */
1219
1220     if (nb_imports)
1221     {
1222         fprintf( outfile, "static const char * const Imports[%d] =\n{\n", nb_imports );
1223         for (i = 0; i < nb_imports; i++)
1224         {
1225             fprintf( outfile, "    \"%s\"", DLLImports[i] );
1226             if (i < nb_imports-1) fprintf( outfile, ",\n" );
1227         }
1228         fprintf( outfile, "\n};\n\n" );
1229     }
1230
1231     /* Output LibMain function */
1232
1233     init_func = DLLInitFunc[0] ? DLLInitFunc : NULL;
1234     switch(SpecMode)
1235     {
1236     case SPEC_MODE_DLL:
1237         if (init_func) fprintf( outfile, "extern void %s();\n", init_func );
1238         break;
1239     case SPEC_MODE_GUIEXE:
1240         if (!init_func) init_func = "WinMain";
1241         fprintf( outfile,
1242                  "\n#include <winbase.h>\n"
1243                  "static void exe_main(void)\n"
1244                  "{\n"
1245                  "    extern int PASCAL %s(HINSTANCE,HINSTANCE,LPCSTR,INT);\n"
1246                  "    STARTUPINFOA info;\n"
1247                  "    const char *cmdline = GetCommandLineA();\n"
1248                  "    while (*cmdline && *cmdline != ' ') cmdline++;\n"
1249                  "    if (*cmdline) cmdline++;\n"
1250                  "    GetStartupInfoA( &info );\n"
1251                  "    if (!(info.dwFlags & STARTF_USESHOWWINDOW)) info.wShowWindow = 1;\n"
1252                  "    ExitProcess( %s( GetModuleHandleA(0), 0, cmdline, info.wShowWindow ) );\n"
1253                  "}\n\n", init_func, init_func );
1254         fprintf( outfile,
1255                  "int main( int argc, char *argv[] )\n"
1256                  "{\n"
1257                  "    extern void PROCESS_InitWinelib( int, char ** );\n"
1258                  "    PROCESS_InitWinelib( argc, argv );\n"
1259                  "    return 1;\n"
1260                  "}\n\n" );
1261         init_func = "exe_main";
1262         break;
1263     case SPEC_MODE_CUIEXE:
1264         if (!init_func) init_func = "wine_main";
1265         fprintf( outfile,
1266                  "\n#include <winbase.h>\n"
1267                  "static void exe_main(void)\n"
1268                  "{\n"
1269                  "    extern int %s( int argc, char *argv[] );\n"
1270                  "    extern int _ARGC;\n"
1271                  "    extern char *_ARGV[];\n"
1272                  "    ExitProcess( %s( _ARGC, _ARGV ) );\n"
1273                  "}\n\n", init_func, init_func );
1274         fprintf( outfile,
1275                  "int main( int argc, char *argv[] )\n"
1276                  "{\n"
1277                  "    extern void PROCESS_InitWinelib( int, char ** );\n"
1278                  "    PROCESS_InitWinelib( argc, argv );\n"
1279                  "    return 1;\n"
1280                  "}\n\n" );
1281         init_func = "exe_main";
1282         break;
1283     }
1284
1285     /* Output the DLL descriptor */
1286
1287     if (rsrc_name[0]) fprintf( outfile, "extern const char %s[];\n\n", rsrc_name );
1288
1289     fprintf( outfile, "static const BUILTIN32_DESCRIPTOR descriptor =\n{\n" );
1290     fprintf( outfile, "    \"%s\",\n", DLLName );
1291     fprintf( outfile, "    \"%s\",\n", DLLFileName );
1292     fprintf( outfile, "    %d,\n", nr_exports? Base : 0 );
1293     fprintf( outfile, "    %d,\n", nr_exports );
1294     fprintf( outfile, "    %d,\n", nb_names );
1295     fprintf( outfile, "    %d,\n", nb_imports );
1296     fprintf( outfile, "    %d,\n", (fwd_size + 3) & ~3 );
1297     fprintf( outfile, "    %s,\n", nr_exports ? "Functions" : "0" );
1298     fprintf( outfile, "    %s,\n", nb_names ? "FuncNames" : "0" );
1299     fprintf( outfile, "    %s,\n", nb_names ? "FuncOrdinals" : "0" );
1300     fprintf( outfile, "    %s,\n", nr_exports ? "FuncArgs" : "0" );
1301     fprintf( outfile, "    %s,\n", nr_exports ? "ArgTypes" : "0" );
1302     fprintf( outfile, "    %s,\n", nb_imports ? "Imports" : "0" );
1303     fprintf( outfile, "    %s,\n", init_func ? init_func : "0" );
1304     fprintf( outfile, "    %d,\n", SpecMode == SPEC_MODE_DLL ? IMAGE_FILE_DLL : 0 );
1305     fprintf( outfile, "    %s\n", rsrc_name[0] ? rsrc_name : "0" );
1306     fprintf( outfile, "};\n" );
1307
1308     /* Output the DLL constructor */
1309
1310     fprintf( outfile, "#ifdef __GNUC__\n" );
1311     fprintf( outfile, "static void %s_init(void) __attribute__((constructor));\n", DLLName );
1312     fprintf( outfile, "#else /* defined(__GNUC__) */\n" );
1313     fprintf( outfile, "static void __asm__dummy_dll_init(void) {\n" );
1314     fprintf( outfile, "asm(\"\\t.section\t.init ,\\\"ax\\\"\\n\"\n" );
1315     fprintf( outfile, "    \"\\tcall %s_init\\n\"\n", DLLName );
1316     fprintf( outfile, "    \"\\t.previous\\n\");\n" );
1317     fprintf( outfile, "}\n" );
1318     fprintf( outfile, "#endif /* defined(__GNUC__) */\n" );
1319     fprintf( outfile, "static void %s_init(void) { BUILTIN32_RegisterDLL( &descriptor ); }\n",
1320              DLLName );
1321
1322     return 0;
1323 }
1324
1325 /*******************************************************************
1326  *         Spec16TypeCompare
1327  */
1328 static int Spec16TypeCompare( const void *e1, const void *e2 )
1329 {
1330     const ORDDEF *odp1 = *(const ORDDEF **)e1;
1331     const ORDDEF *odp2 = *(const ORDDEF **)e2;
1332
1333     int type1 = (odp1->type == TYPE_CDECL) ? 0
1334               : (odp1->type == TYPE_REGISTER) ? 3
1335               : (odp1->type == TYPE_INTERRUPT) ? 4
1336               : (odp1->type == TYPE_PASCAL_16) ? 1 : 2;
1337
1338     int type2 = (odp2->type == TYPE_CDECL) ? 0
1339               : (odp2->type == TYPE_REGISTER) ? 3
1340               : (odp2->type == TYPE_INTERRUPT) ? 4
1341               : (odp2->type == TYPE_PASCAL_16) ? 1 : 2;
1342
1343     int retval = type1 - type2;
1344     if ( !retval )
1345         retval = strcmp( odp1->u.func.arg_types, odp2->u.func.arg_types );
1346
1347     return retval;
1348 }
1349
1350 /*******************************************************************
1351  *         BuildSpec16File
1352  *
1353  * Build a Win16 assembly file from a spec file.
1354  */
1355 static int BuildSpec16File( FILE *outfile )
1356 {
1357     ORDDEF **type, **typelist;
1358     int i, nFuncs, nTypes;
1359     int code_offset, data_offset, module_size;
1360     unsigned char *data;
1361
1362     /* File header */
1363
1364     fprintf( outfile, "/* File generated automatically from %s; do not edit! */\n\n",
1365              input_file_name );
1366     fprintf( outfile, "#define __FLATCS__ 0x%04x\n", Code_Selector );
1367     fprintf( outfile, "#include \"builtin16.h\"\n\n" );
1368
1369     data = (unsigned char *)xmalloc( 0x10000 );
1370     memset( data, 0, 16 );
1371     data_offset = 16;
1372
1373
1374     /* Build sorted list of all argument types, without duplicates */
1375
1376     typelist = (ORDDEF **)calloc( Limit+1, sizeof(ORDDEF *) );
1377
1378     for (i = nFuncs = 0; i <= Limit; i++)
1379     {
1380         ORDDEF *odp = Ordinals[i];
1381         if (!odp) continue;
1382         switch (odp->type)
1383         {
1384           case TYPE_REGISTER:
1385           case TYPE_INTERRUPT:
1386           case TYPE_CDECL:
1387           case TYPE_PASCAL:
1388           case TYPE_PASCAL_16:
1389           case TYPE_STUB:
1390             typelist[nFuncs++] = odp;
1391
1392           default:
1393             break;
1394         }
1395     }
1396
1397     qsort( typelist, nFuncs, sizeof(ORDDEF *), Spec16TypeCompare );
1398
1399     i = nTypes = 0;
1400     while ( i < nFuncs )
1401     {
1402         typelist[nTypes++] = typelist[i++];
1403         while ( i < nFuncs && Spec16TypeCompare( typelist + i, typelist + nTypes-1 ) == 0 )
1404             i++;
1405     }
1406
1407     /* Output CallFrom16 routines needed by this .spec file */
1408
1409     for ( i = 0; i < nTypes; i++ )
1410     {
1411         char profile[101];
1412
1413         sprintf( profile, "%s_%s_%s",
1414                  (typelist[i]->type == TYPE_CDECL) ? "c" : "p",
1415                  (typelist[i]->type == TYPE_REGISTER) ? "regs" :
1416                  (typelist[i]->type == TYPE_INTERRUPT) ? "intr" :
1417                  (typelist[i]->type == TYPE_PASCAL_16) ? "word" : "long",
1418                  typelist[i]->u.func.arg_types );
1419
1420         BuildCallFrom16Func( outfile, profile, DLLName, TRUE );
1421     }
1422
1423     /* Output the DLL functions prototypes */
1424
1425     for (i = 0; i <= Limit; i++)
1426     {
1427         ORDDEF *odp = Ordinals[i];
1428         if (!odp) continue;
1429         switch(odp->type)
1430         {
1431         case TYPE_REGISTER:
1432         case TYPE_INTERRUPT:
1433         case TYPE_CDECL:
1434         case TYPE_PASCAL:
1435         case TYPE_PASCAL_16:
1436             fprintf( outfile, "extern void %s();\n", odp->u.func.link_name );
1437             break;
1438         default:
1439             break;
1440         }
1441     }
1442
1443     /* Output code segment */
1444
1445     fprintf( outfile, "\nstatic struct\n{\n    CALLFROM16   call[%d];\n"
1446                       "    ENTRYPOINT16 entry[%d];\n} Code_Segment = \n{\n    {\n",
1447                       nTypes, nFuncs );
1448     code_offset = 0;
1449
1450     for ( i = 0; i < nTypes; i++ )
1451     {
1452         char profile[101], *arg;
1453         int argsize = 0;
1454
1455         sprintf( profile, "%s_%s_%s", 
1456                           (typelist[i]->type == TYPE_CDECL) ? "c" : "p",
1457                           (typelist[i]->type == TYPE_REGISTER) ? "regs" :
1458                           (typelist[i]->type == TYPE_INTERRUPT) ? "intr" :
1459                           (typelist[i]->type == TYPE_PASCAL_16) ? "word" : "long",
1460                           typelist[i]->u.func.arg_types );
1461
1462         if ( typelist[i]->type != TYPE_CDECL )
1463             for ( arg = typelist[i]->u.func.arg_types; *arg; arg++ )
1464                 switch ( *arg )
1465                 {
1466                 case 'w':  /* word */
1467                 case 's':  /* s_word */
1468                     argsize += 2;
1469                     break;
1470         
1471                 case 'l':  /* long or segmented pointer */
1472                 case 'T':  /* segmented pointer to null-terminated string */
1473                 case 'p':  /* linear pointer */
1474                 case 't':  /* linear pointer to null-terminated string */
1475                     argsize += 4;
1476                     break;
1477                 }
1478
1479         if ( typelist[i]->type == TYPE_INTERRUPT )
1480             argsize += 2;
1481
1482         fprintf( outfile, "        CF16_%s( %s_CallFrom16_%s, %d, \"%s\" ),\n",
1483                  (   typelist[i]->type == TYPE_REGISTER 
1484                   || typelist[i]->type == TYPE_INTERRUPT)? "REGS":
1485                  typelist[i]->type == TYPE_PASCAL_16? "WORD" : "LONG",
1486                  DLLName, profile, argsize, profile );
1487
1488         code_offset += sizeof(CALLFROM16);
1489     }
1490     fprintf( outfile, "    },\n    {\n" );
1491
1492     for (i = 0; i <= Limit; i++)
1493     {
1494         ORDDEF *odp = Ordinals[i];
1495         if (!odp) continue;
1496         switch (odp->type)
1497         {
1498           case TYPE_ABS:
1499             odp->offset = LOWORD(odp->u.abs.value);
1500             break;
1501
1502           case TYPE_BYTE:
1503             odp->offset = data_offset;
1504             data_offset += StoreVariableCode( data + data_offset, 1, odp);
1505             break;
1506
1507           case TYPE_WORD:
1508             odp->offset = data_offset;
1509             data_offset += StoreVariableCode( data + data_offset, 2, odp);
1510             break;
1511
1512           case TYPE_LONG:
1513             odp->offset = data_offset;
1514             data_offset += StoreVariableCode( data + data_offset, 4, odp);
1515             break;
1516
1517           case TYPE_REGISTER:
1518           case TYPE_INTERRUPT:
1519           case TYPE_CDECL:
1520           case TYPE_PASCAL:
1521           case TYPE_PASCAL_16:
1522           case TYPE_STUB:
1523             type = bsearch( &odp, typelist, nTypes, sizeof(ORDDEF *), Spec16TypeCompare );
1524             assert( type );
1525
1526             fprintf( outfile, "        /* %s.%d */ ", DLLName, i );
1527             fprintf( outfile, "EP( %s, %d /* %s_%s_%s */ ),\n",
1528                               odp->u.func.link_name,
1529                               (type-typelist)*sizeof(CALLFROM16) - 
1530                               (code_offset + sizeof(ENTRYPOINT16)),
1531                               (odp->type == TYPE_CDECL) ? "c" : "p",
1532                               (odp->type == TYPE_REGISTER) ? "regs" :
1533                               (odp->type == TYPE_INTERRUPT) ? "intr" :
1534                               (odp->type == TYPE_PASCAL_16) ? "word" : "long",
1535                               odp->u.func.arg_types );
1536                                  
1537             odp->offset = code_offset;
1538             code_offset += sizeof(ENTRYPOINT16);
1539             break;
1540                 
1541           default:
1542             fprintf(stderr,"build: function type %d not available for Win16\n",
1543                     odp->type);
1544             return -1;
1545         }
1546     }
1547
1548     fprintf( outfile, "    }\n};\n" );
1549
1550     /* Output data segment */
1551
1552     DumpBytes( outfile, data, data_offset, "Data_Segment" );
1553
1554     /* Build the module */
1555
1556     module_size = BuildModule16( outfile, code_offset, data_offset );
1557
1558     /* Output the DLL descriptor */
1559
1560     if (rsrc_name[0]) fprintf( outfile, "extern const char %s[];\n\n", rsrc_name );
1561
1562     fprintf( outfile, "\nstatic const BUILTIN16_DESCRIPTOR descriptor = \n{\n" );
1563     fprintf( outfile, "    \"%s\",\n", DLLName );
1564     fprintf( outfile, "    Module,\n" );
1565     fprintf( outfile, "    sizeof(Module),\n" );
1566     fprintf( outfile, "    (BYTE *)&Code_Segment,\n" );
1567     fprintf( outfile, "    (BYTE *)Data_Segment,\n" );
1568     fprintf( outfile, "    %s\n", rsrc_name[0] ? rsrc_name : "0" );
1569     fprintf( outfile, "};\n" );
1570     
1571     /* Output the DLL constructor */
1572
1573     fprintf( outfile, "#ifdef __GNUC__\n" );
1574     fprintf( outfile, "static void %s_init(void) __attribute__((constructor));\n", DLLName );
1575     fprintf( outfile, "#else /* defined(__GNUC__) */\n" );
1576     fprintf( outfile, "static void __asm__dummy_dll_init(void) {\n" );
1577     fprintf( outfile, "asm(\"\\t.section\t.init ,\\\"ax\\\"\\n\"\n" );
1578     fprintf( outfile, "    \"\\tcall %s_init\\n\"\n", DLLName );
1579     fprintf( outfile, "    \"\\t.previous\\n\");\n" );
1580     fprintf( outfile, "}\n" );
1581     fprintf( outfile, "#endif /* defined(__GNUC__) */\n" );
1582     fprintf( outfile, "static void %s_init(void) { BUILTIN_RegisterDLL( &descriptor ); }\n",
1583              DLLName );
1584
1585     return 0;
1586 }
1587
1588
1589 /*******************************************************************
1590  *         BuildSpecFile
1591  *
1592  * Build an assembly file from a spec file.
1593  */
1594 static void BuildSpecFile( FILE *outfile, FILE *infile )
1595 {
1596     SpecFp = infile;
1597     ParseTopLevel();
1598
1599     switch(SpecType)
1600     {
1601     case SPEC_WIN16:
1602         BuildSpec16File( outfile );
1603         break;
1604     case SPEC_WIN32:
1605         BuildSpec32File( outfile );
1606         break;
1607     default:
1608         fatal_error( "Missing 'type' declaration\n" );
1609     }
1610 }
1611
1612
1613 /*******************************************************************
1614  *         BuildCallFrom16Func
1615  *
1616  * Build a 16-bit-to-Wine callback glue function. 
1617  *
1618  * The generated routines are intended to be used as argument conversion 
1619  * routines to be called by the CallFrom16... core. Thus, the prototypes of
1620  * the generated routines are (see also CallFrom16):
1621  *
1622  *  extern WORD WINAPI PREFIX_CallFrom16_C_word_xxx( FARPROC func, LPBYTE args );
1623  *  extern LONG WINAPI PREFIX_CallFrom16_C_long_xxx( FARPROC func, LPBYTE args );
1624  *  extern void WINAPI PREFIX_CallFrom16_C_regs_xxx( FARPROC func, LPBYTE args, 
1625  *                                                   CONTEXT86 *context );
1626  *  extern void WINAPI PREFIX_CallFrom16_C_intr_xxx( FARPROC func, LPBYTE args, 
1627  *                                                   CONTEXT86 *context );
1628  *
1629  * where 'C' is the calling convention ('p' for pascal or 'c' for cdecl), 
1630  * and each 'x' is an argument  ('w'=word, 's'=signed word, 'l'=long, 
1631  * 'p'=linear pointer, 't'=linear pointer to null-terminated string,
1632  * 'T'=segmented pointer to null-terminated string).
1633  *
1634  * The generated routines fetch the arguments from the 16-bit stack (pointed
1635  * to by 'args'); the offsets of the single argument values are computed 
1636  * according to the calling convention and the argument types.  Then, the
1637  * 32-bit entry point is called with these arguments.
1638  * 
1639  * For register functions, the arguments (if present) are converted just
1640  * the same as for normal functions, but in addition the CONTEXT86 pointer 
1641  * filled with the current register values is passed to the 32-bit routine.
1642  * (An 'intr' interrupt handler routine is treated exactly like a register 
1643  * routine, except that upon return, the flags word pushed onto the stack 
1644  * by the interrupt is removed by the 16-bit call stub.)
1645  *
1646  */
1647 static void BuildCallFrom16Func( FILE *outfile, char *profile, char *prefix, int local )
1648 {
1649     int i, pos, argsize = 0;
1650     int short_ret = 0;
1651     int reg_func = 0;
1652     int usecdecl = 0;
1653     char *args = profile + 7;
1654     char *ret_type;
1655
1656     /* Parse function type */
1657
1658     if (!strncmp( "c_", profile, 2 )) usecdecl = 1;
1659     else if (strncmp( "p_", profile, 2 ))
1660     {
1661         fprintf( stderr, "Invalid function name '%s', ignored\n", profile );
1662         return;
1663     }
1664
1665     if (!strncmp( "word_", profile + 2, 5 )) short_ret = 1;
1666     else if (!strncmp( "regs_", profile + 2, 5 )) reg_func = 1;
1667     else if (!strncmp( "intr_", profile + 2, 5 )) reg_func = 2;
1668     else if (strncmp( "long_", profile + 2, 5 ))
1669     {
1670         fprintf( stderr, "Invalid function name '%s', ignored\n", profile );
1671         return;
1672     }
1673
1674     for ( i = 0; args[i]; i++ )
1675         switch ( args[i] )
1676         {
1677         case 'w':  /* word */
1678         case 's':  /* s_word */
1679             argsize += 2;
1680             break;
1681         
1682         case 'l':  /* long or segmented pointer */
1683         case 'T':  /* segmented pointer to null-terminated string */
1684         case 'p':  /* linear pointer */
1685         case 't':  /* linear pointer to null-terminated string */
1686             argsize += 4;
1687             break;
1688         }
1689
1690     ret_type = reg_func? "void" : short_ret? "WORD" : "LONG";
1691
1692     fprintf( outfile, "typedef %s WINAPI (*proc_%s_t)( ", 
1693                       ret_type, profile );
1694     args = profile + 7;
1695     for ( i = 0; args[i]; i++ )
1696     {
1697         if ( i ) fprintf( outfile, ", " );
1698         switch (args[i])
1699         {
1700         case 'w':           fprintf( outfile, "WORD" ); break;
1701         case 's':           fprintf( outfile, "INT16" ); break;
1702         case 'l': case 'T': fprintf( outfile, "LONG" ); break;
1703         case 'p': case 't': fprintf( outfile, "LPVOID" ); break;
1704         }
1705     }
1706     if ( reg_func )
1707         fprintf( outfile, "%sstruct _CONTEXT86 *", i? ", " : "" );
1708     else if ( !i )
1709         fprintf( outfile, "void" );
1710     fprintf( outfile, " );\n" );
1711     
1712     fprintf( outfile, "%s%s WINAPI %s_CallFrom16_%s( FARPROC proc, LPBYTE args%s )\n{\n",
1713              local? "static " : "", ret_type, prefix, profile,
1714              reg_func? ", struct _CONTEXT86 *context" : "" );
1715
1716     fprintf( outfile, "    %s((proc_%s_t) proc) (\n",
1717              reg_func? "" : "return ", profile );
1718     args = profile + 7;
1719     pos = !usecdecl? argsize : 0;
1720     for ( i = 0; args[i]; i++ )
1721     {
1722         if ( i ) fprintf( outfile, ",\n" );
1723         fprintf( outfile, "        " );
1724         switch (args[i])
1725         {
1726         case 'w':  /* word */
1727             if ( !usecdecl ) pos -= 2;
1728             fprintf( outfile, "*(WORD *)(args+%d)", pos );
1729             if (  usecdecl ) pos += 2;
1730             break;
1731
1732         case 's':  /* s_word */
1733             if ( !usecdecl ) pos -= 2;
1734             fprintf( outfile, "*(INT16 *)(args+%d)", pos );
1735             if (  usecdecl ) pos += 2;
1736             break;
1737
1738         case 'l':  /* long or segmented pointer */
1739         case 'T':  /* segmented pointer to null-terminated string */
1740             if ( !usecdecl ) pos -= 4;
1741             fprintf( outfile, "*(LONG *)(args+%d)", pos );
1742             if (  usecdecl ) pos += 4;
1743             break;
1744
1745         case 'p':  /* linear pointer */
1746         case 't':  /* linear pointer to null-terminated string */
1747             if ( !usecdecl ) pos -= 4;
1748             fprintf( outfile, "PTR_SEG_TO_LIN( *(SEGPTR *)(args+%d) )", pos );
1749             if (  usecdecl ) pos += 4;
1750             break;
1751
1752         default:
1753             fprintf( stderr, "Unknown arg type '%c'\n", args[i] );
1754         }
1755     }
1756     if ( reg_func )
1757         fprintf( outfile, "%s        context", i? ",\n" : "" );
1758     fprintf( outfile, " );\n}\n\n" );
1759 }
1760
1761 /*******************************************************************
1762  *         BuildCallTo16Func
1763  *
1764  * Build a Wine-to-16-bit callback glue function. 
1765  *
1766  * Prototypes for the CallTo16 functions:
1767  *   extern WORD CALLBACK PREFIX_CallTo16_word_xxx( FARPROC16 func, args... );
1768  *   extern LONG CALLBACK PREFIX_CallTo16_long_xxx( FARPROC16 func, args... );
1769  * 
1770  * These routines are provided solely for convenience; they simply
1771  * write the arguments onto the 16-bit stack, and call the appropriate
1772  * CallTo16... core routine.
1773  *
1774  * If you have more sophisticated argument conversion requirements than
1775  * are provided by these routines, you might as well call the core 
1776  * routines by yourself.
1777  *
1778  */
1779 static void BuildCallTo16Func( FILE *outfile, char *profile, char *prefix )
1780 {
1781     char *args = profile + 5;
1782     int i, argsize = 0, short_ret = 0;
1783
1784     if (!strncmp( "word_", profile, 5 )) short_ret = 1;
1785     else if (strncmp( "long_", profile, 5 ))
1786     {
1787         fprintf( stderr, "Invalid function name '%s'.\n", profile );
1788         exit(1);
1789     }
1790
1791     fprintf( outfile, "%s %s_CallTo16_%s( FARPROC16 proc",
1792              short_ret? "WORD" : "LONG", prefix, profile );
1793     args = profile + 5;
1794     for ( i = 0; args[i]; i++ )
1795     {
1796         fprintf( outfile, ", " );
1797         switch (args[i])
1798         {
1799         case 'w': fprintf( outfile, "WORD" ); argsize += 2; break;
1800         case 'l': fprintf( outfile, "LONG" ); argsize += 4; break;
1801         }
1802         fprintf( outfile, " arg%d", i+1 );
1803     }
1804     fprintf( outfile, " )\n{\n" );
1805
1806     if ( argsize > 0 )
1807         fprintf( outfile, "    LPBYTE args = (LPBYTE)CURRENT_STACK16;\n" );
1808
1809     args = profile + 5;
1810     for ( i = 0; args[i]; i++ )
1811     {
1812         switch (args[i])
1813         {
1814         case 'w': fprintf( outfile, "    args -= sizeof(WORD); *(WORD" ); break;
1815         case 'l': fprintf( outfile, "    args -= sizeof(LONG); *(LONG" ); break;
1816         default:  fprintf( stderr, "Unexpected case '%c' in BuildCallTo16Func\n",
1817                                    args[i] );
1818         }
1819         fprintf( outfile, " *)args = arg%d;\n", i+1 );
1820     }
1821
1822     fprintf( outfile, "    return CallTo16%s( proc, %d );\n}\n\n",
1823              short_ret? "Word" : "Long", argsize );
1824 }
1825
1826
1827
1828 /*******************************************************************
1829  *         BuildCallFrom16Core
1830  *
1831  * This routine builds the core routines used in 16->32 thunks:
1832  * CallFrom16Word, CallFrom16Long, CallFrom16Register, and CallFrom16Thunk.
1833  *
1834  * These routines are intended to be called via a far call (with 32-bit
1835  * operand size) from 16-bit code.  The 16-bit code stub must push %bp,
1836  * the 32-bit entry point to be called, and the argument conversion 
1837  * routine to be used (see stack layout below).  
1838  *
1839  * The core routine completes the STACK16FRAME on the 16-bit stack and
1840  * switches to the 32-bit stack.  Then, the argument conversion routine 
1841  * is called; it gets passed the 32-bit entry point and a pointer to the 
1842  * 16-bit arguments (on the 16-bit stack) as parameters. (You can either 
1843  * use conversion routines automatically generated by BuildCallFrom16, 
1844  * or write your own for special purposes.)
1845  * 
1846  * The conversion routine must call the 32-bit entry point, passing it
1847  * the converted arguments, and return its return value to the core.  
1848  * After the conversion routine has returned, the core switches back
1849  * to the 16-bit stack, converts the return value to the DX:AX format
1850  * (CallFrom16Long), and returns to the 16-bit call stub.  All parameters,
1851  * including %bp, are popped off the stack.
1852  *
1853  * The 16-bit call stub now returns to the caller, popping the 16-bit
1854  * arguments if necessary (pascal calling convention).
1855  *
1856  * In the case of a 'register' function, CallFrom16Register fills a
1857  * CONTEXT86 structure with the values all registers had at the point
1858  * the first instruction of the 16-bit call stub was about to be 
1859  * executed.  A pointer to this CONTEXT86 is passed as third parameter 
1860  * to the argument conversion routine, which typically passes it on
1861  * to the called 32-bit entry point.
1862  *
1863  * CallFrom16Thunk is a special variant used by the implementation of 
1864  * the Win95 16->32 thunk functions C16ThkSL and C16ThkSL01 and is 
1865  * implemented as follows:
1866  * On entry, the EBX register is set up to contain a flat pointer to the
1867  * 16-bit stack such that EBX+22 points to the first argument.
1868  * Then, the entry point is called, while EBP is set up to point
1869  * to the return address (on the 32-bit stack).
1870  * The called function returns with CX set to the number of bytes
1871  * to be popped of the caller's stack.
1872  *
1873  * Stack layout upon entry to the core routine (STACK16FRAME):
1874  *  ...           ...
1875  * (sp+24) word   first 16-bit arg
1876  * (sp+22) word   cs
1877  * (sp+20) word   ip
1878  * (sp+18) word   bp
1879  * (sp+14) long   32-bit entry point (reused for Win16 mutex recursion count)
1880  * (sp+12) word   ip of actual entry point (necessary for relay debugging)
1881  * (sp+8)  long   relay (argument conversion) function entry point
1882  * (sp+4)  long   cs of 16-bit entry point
1883  * (sp)    long   ip of 16-bit entry point
1884  *
1885  * Added on the stack:
1886  * (sp-2)  word   saved gs
1887  * (sp-4)  word   saved fs
1888  * (sp-6)  word   saved es
1889  * (sp-8)  word   saved ds
1890  * (sp-12) long   saved ebp
1891  * (sp-16) long   saved ecx
1892  * (sp-20) long   saved edx
1893  * (sp-24) long   saved previous stack
1894  */
1895 static void BuildCallFrom16Core( FILE *outfile, int reg_func, int thunk, int short_ret )
1896 {
1897     char *name = thunk? "Thunk" : reg_func? "Register" : short_ret? "Word" : "Long";
1898
1899     /* Function header */
1900     fprintf( outfile, "\n\t.align 4\n" );
1901 #ifdef USE_STABS
1902     fprintf( outfile, ".stabs \"CallFrom16%s:F1\",36,0,0," PREFIX "CallFrom16%s\n", 
1903              name, name);
1904 #endif
1905     fprintf( outfile, "\t.type " PREFIX "CallFrom16%s,@function\n", name );
1906     fprintf( outfile, "\t.globl " PREFIX "CallFrom16%s\n", name );
1907     fprintf( outfile, PREFIX "CallFrom16%s:\n", name );
1908
1909     /* Create STACK16FRAME (except STACK32FRAME link) */
1910     fprintf( outfile, "\tpushw %%gs\n" );
1911     fprintf( outfile, "\tpushw %%fs\n" );
1912     fprintf( outfile, "\tpushw %%es\n" );
1913     fprintf( outfile, "\tpushw %%ds\n" );
1914     fprintf( outfile, "\tpushl %%ebp\n" );
1915     fprintf( outfile, "\tpushl %%ecx\n" );
1916     fprintf( outfile, "\tpushl %%edx\n" );
1917
1918     /* Save original EFlags register */
1919     fprintf( outfile, "\tpushfl\n" );
1920
1921     if ( UsePIC )
1922     {
1923         /* Get Global Offset Table into %ecx */
1924         fprintf( outfile, "\tcall .LCallFrom16%s.getgot1\n", name );
1925         fprintf( outfile, ".LCallFrom16%s.getgot1:\n", name );
1926         fprintf( outfile, "\tpopl %%ecx\n" );
1927         fprintf( outfile, "\taddl $_GLOBAL_OFFSET_TABLE_+[.-.LCallFrom16%s.getgot1], %%ecx\n", name );
1928     }
1929
1930     /* Load 32-bit segment registers */
1931     fprintf( outfile, "\tmovw $0x%04x, %%dx\n", Data_Selector );
1932 #ifdef __svr4__
1933     fprintf( outfile, "\tdata16\n");
1934 #endif
1935     fprintf( outfile, "\tmovw %%dx, %%ds\n" );
1936 #ifdef __svr4__
1937     fprintf( outfile, "\tdata16\n");
1938 #endif
1939     fprintf( outfile, "\tmovw %%dx, %%es\n" );
1940
1941     if ( UsePIC )
1942     {
1943         fprintf( outfile, "\tmovl " PREFIX "SYSLEVEL_Win16CurrentTeb@GOT(%%ecx), %%edx\n" );
1944         fprintf( outfile, "\tmovw (%%edx), %%fs\n" );
1945     }
1946     else
1947         fprintf( outfile, "\tmovw " PREFIX "SYSLEVEL_Win16CurrentTeb, %%fs\n" );
1948
1949     /* Get address of ldt_copy array into %ecx */
1950     if ( UsePIC )
1951         fprintf( outfile, "\tmovl " PREFIX "ldt_copy@GOT(%%ecx), %%ecx\n" );
1952     else
1953         fprintf( outfile, "\tmovl $" PREFIX "ldt_copy, %%ecx\n" );
1954
1955     /* Translate STACK16FRAME base to flat offset in %edx */
1956     fprintf( outfile, "\tmovw %%ss, %%dx\n" );
1957     fprintf( outfile, "\tandl $0xfff8, %%edx\n" );
1958     fprintf( outfile, "\tmovl (%%ecx,%%edx), %%edx\n" );
1959     fprintf( outfile, "\tmovzwl %%sp, %%ebp\n" );
1960     fprintf( outfile, "\tleal (%%ebp,%%edx), %%edx\n" );  
1961
1962     /* Get saved flags into %ecx */
1963     fprintf( outfile, "\tpopl %%ecx\n" );
1964
1965     /* Get the 32-bit stack pointer from the TEB and complete STACK16FRAME */
1966     fprintf( outfile, "\t.byte 0x64\n\tmovl (%d), %%ebp\n", STACKOFFSET );
1967     fprintf( outfile, "\tpushl %%ebp\n" );
1968
1969     /* Switch stacks */
1970 #ifdef __svr4__
1971     fprintf( outfile,"\tdata16\n");
1972 #endif
1973     fprintf( outfile, "\t.byte 0x64\n\tmovw %%ss, (%d)\n", STACKOFFSET + 2 );
1974     fprintf( outfile, "\t.byte 0x64\n\tmovw %%sp, (%d)\n", STACKOFFSET );
1975     fprintf( outfile, "\tpushl %%ds\n" );
1976     fprintf( outfile, "\tpopl %%ss\n" );
1977     fprintf( outfile, "\tmovl %%ebp, %%esp\n" );
1978     fprintf( outfile, "\taddl $%d, %%ebp\n", STRUCTOFFSET(STACK32FRAME, ebp) );
1979
1980
1981     /* At this point:
1982        STACK16FRAME is completely set up
1983        DS, ES, SS: flat data segment
1984        FS: current TEB
1985        ESP: points to last STACK32FRAME
1986        EBP: points to ebp member of last STACK32FRAME
1987        EDX: points to current STACK16FRAME
1988        ECX: contains saved flags
1989        all other registers: unchanged */
1990
1991     /* Special case: C16ThkSL stub */
1992     if ( thunk )
1993     {
1994         /* Set up registers as expected and call thunk */
1995         fprintf( outfile, "\tleal %d(%%edx), %%ebx\n", sizeof(STACK16FRAME)-22 );
1996         fprintf( outfile, "\tleal -4(%%esp), %%ebp\n" );
1997
1998         fprintf( outfile, "\tcall *%d(%%edx)\n", STACK16OFFSET(entry_point) );
1999
2000         /* Switch stack back */
2001         /* fprintf( outfile, "\t.byte 0x64\n\tlssw (%d), %%sp\n", STACKOFFSET ); */
2002         fprintf( outfile, "\t.byte 0x64,0x66,0x0f,0xb2,0x25\n\t.long %d\n", STACKOFFSET );
2003         fprintf( outfile, "\t.byte 0x64\n\tpopl (%d)\n", STACKOFFSET );
2004
2005         /* Restore registers and return directly to caller */
2006         fprintf( outfile, "\taddl $8, %%esp\n" );
2007         fprintf( outfile, "\tpopl %%ebp\n" );
2008         fprintf( outfile, "\tpopw %%ds\n" );
2009         fprintf( outfile, "\tpopw %%es\n" );
2010         fprintf( outfile, "\tpopw %%fs\n" );
2011         fprintf( outfile, "\tpopw %%gs\n" );
2012         fprintf( outfile, "\taddl $20, %%esp\n" );
2013
2014         fprintf( outfile, "\txorb %%ch, %%ch\n" );
2015         fprintf( outfile, "\tpopl %%ebx\n" );
2016         fprintf( outfile, "\taddw %%cx, %%sp\n" );
2017         fprintf( outfile, "\tpush %%ebx\n" );
2018
2019         fprintf( outfile, "\t.byte 0x66\n" );
2020         fprintf( outfile, "\tlret\n" );
2021
2022         return;
2023     }
2024
2025
2026     /* Build register CONTEXT */
2027     if ( reg_func )
2028     {
2029         fprintf( outfile, "\tsubl $%d, %%esp\n", sizeof(CONTEXT86) );
2030
2031         fprintf( outfile, "\tmovl %%ecx, %d(%%esp)\n", CONTEXTOFFSET(EFlags) );  
2032
2033         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(Eax) );
2034         fprintf( outfile, "\tmovl %%ebx, %d(%%esp)\n", CONTEXTOFFSET(Ebx) );
2035         fprintf( outfile, "\tmovl %%esi, %d(%%esp)\n", CONTEXTOFFSET(Esi) );
2036         fprintf( outfile, "\tmovl %%edi, %d(%%esp)\n", CONTEXTOFFSET(Edi) );
2037
2038         fprintf( outfile, "\tmovl %d(%%edx), %%eax\n", STACK16OFFSET(ebp) );
2039         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(Ebp) );
2040         fprintf( outfile, "\tmovl %d(%%edx), %%eax\n", STACK16OFFSET(ecx) );
2041         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(Ecx) );
2042         fprintf( outfile, "\tmovl %d(%%edx), %%eax\n", STACK16OFFSET(edx) );
2043         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(Edx) );
2044
2045         fprintf( outfile, "\tmovzwl %d(%%edx), %%eax\n", STACK16OFFSET(ds) );
2046         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(SegDs) );
2047         fprintf( outfile, "\tmovzwl %d(%%edx), %%eax\n", STACK16OFFSET(es) );
2048         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(SegEs) );
2049         fprintf( outfile, "\tmovzwl %d(%%edx), %%eax\n", STACK16OFFSET(fs) );
2050         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(SegFs) );
2051         fprintf( outfile, "\tmovzwl %d(%%edx), %%eax\n", STACK16OFFSET(gs) );
2052         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(SegGs) );
2053
2054         fprintf( outfile, "\tmovzwl %d(%%edx), %%eax\n", STACK16OFFSET(cs) );
2055         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(SegCs) );
2056         fprintf( outfile, "\tmovzwl %d(%%edx), %%eax\n", STACK16OFFSET(ip) );
2057         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(Eip) );
2058
2059         fprintf( outfile, "\t.byte 0x64\n\tmovzwl (%d), %%eax\n", STACKOFFSET+2 );
2060         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(SegSs) );
2061         fprintf( outfile, "\t.byte 0x64\n\tmovzwl (%d), %%eax\n", STACKOFFSET );
2062         fprintf( outfile, "\taddl $%d, %%eax\n", STACK16OFFSET(ip) );
2063         fprintf( outfile, "\tmovl %%eax, %d(%%esp)\n", CONTEXTOFFSET(Esp) );
2064 #if 0
2065         fprintf( outfile, "\tfsave %d(%%esp)\n", CONTEXTOFFSET(FloatSave) );
2066 #endif
2067
2068         /* Push address of CONTEXT86 structure -- popped by the relay routine */
2069         fprintf( outfile, "\tpushl %%esp\n" );
2070     }
2071
2072
2073     /* Print debug info before call */
2074     if ( debugging )
2075     {
2076         if ( UsePIC )
2077         {
2078             fprintf( outfile, "\tpushl %%ebx\n" );
2079
2080             /* Get Global Offset Table into %ebx (for PLT call) */
2081             fprintf( outfile, "\tcall .LCallFrom16%s.getgot2\n", name );
2082             fprintf( outfile, ".LCallFrom16%s.getgot2:\n", name );
2083             fprintf( outfile, "\tpopl %%ebx\n" );
2084             fprintf( outfile, "\taddl $_GLOBAL_OFFSET_TABLE_+[.-.LCallFrom16%s.getgot2], %%ebx\n", name );
2085         }
2086
2087         fprintf( outfile, "\tpushl %%edx\n" );
2088         if ( reg_func )
2089             fprintf( outfile, "\tleal -%d(%%ebp), %%eax\n\tpushl %%eax\n",
2090                               sizeof(CONTEXT) + STRUCTOFFSET(STACK32FRAME, ebp) );
2091         else
2092             fprintf( outfile, "\tpushl $0\n" );
2093
2094         if ( UsePIC )
2095             fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallFrom16@PLT\n ");
2096         else
2097             fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallFrom16\n ");
2098
2099         fprintf( outfile, "\tpopl %%edx\n" );
2100         fprintf( outfile, "\tpopl %%edx\n" );
2101
2102         if ( UsePIC )
2103             fprintf( outfile, "\tpopl %%ebx\n" );
2104     }
2105
2106     /* Call relay routine (which will call the API entry point) */
2107     fprintf( outfile, "\tleal %d(%%edx), %%eax\n", sizeof(STACK16FRAME) );
2108     fprintf( outfile, "\tpushl %%eax\n" );
2109     fprintf( outfile, "\tpushl %d(%%edx)\n", STACK16OFFSET(entry_point) );
2110     fprintf( outfile, "\tcall *%d(%%edx)\n", STACK16OFFSET(relay) );
2111
2112     /* Print debug info after call */
2113     if ( debugging )
2114     {
2115         if ( UsePIC )
2116         {
2117             fprintf( outfile, "\tpushl %%ebx\n" );
2118
2119             /* Get Global Offset Table into %ebx (for PLT call) */
2120             fprintf( outfile, "\tcall .LCallFrom16%s.getgot3\n", name );
2121             fprintf( outfile, ".LCallFrom16%s.getgot3:\n", name );
2122             fprintf( outfile, "\tpopl %%ebx\n" );
2123             fprintf( outfile, "\taddl $_GLOBAL_OFFSET_TABLE_+[.-.LCallFrom16%s.getgot3], %%ebx\n", name );
2124         }
2125
2126         fprintf( outfile, "\tpushl %%eax\n" );
2127         if ( reg_func )
2128             fprintf( outfile, "\tleal -%d(%%ebp), %%eax\n\tpushl %%eax\n",
2129                               sizeof(CONTEXT) + STRUCTOFFSET(STACK32FRAME, ebp) );
2130         else
2131             fprintf( outfile, "\tpushl $0\n" );
2132
2133         if ( UsePIC )
2134             fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallFrom16Ret@PLT\n ");
2135         else
2136             fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallFrom16Ret\n ");
2137
2138         fprintf( outfile, "\tpopl %%eax\n" );
2139         fprintf( outfile, "\tpopl %%eax\n" );
2140
2141         if ( UsePIC )
2142             fprintf( outfile, "\tpopl %%ebx\n" );
2143     }
2144
2145
2146     if ( reg_func )
2147     {
2148         fprintf( outfile, "\tmovl %%esp, %%ebx\n" );
2149
2150         /* Switch stack back */
2151         /* fprintf( outfile, "\t.byte 0x64\n\tlssw (%d), %%sp\n", STACKOFFSET ); */
2152         fprintf( outfile, "\t.byte 0x64,0x66,0x0f,0xb2,0x25\n\t.long %d\n", STACKOFFSET );
2153         fprintf( outfile, "\t.byte 0x64\n\tpopl (%d)\n", STACKOFFSET );
2154
2155         /* Get return address to CallFrom16 stub */
2156         fprintf( outfile, "\taddw $%d, %%sp\n", STACK16OFFSET(callfrom_ip)-4 );
2157         fprintf( outfile, "\tpopl %%eax\n" );
2158         fprintf( outfile, "\tpopl %%edx\n" );
2159
2160         /* Restore all registers from CONTEXT */
2161         fprintf( outfile, "\tmovw %d(%%ebx), %%ss\n", CONTEXTOFFSET(SegSs) );
2162         fprintf( outfile, "\tmovl %d(%%ebx), %%esp\n", CONTEXTOFFSET(Esp) );
2163         fprintf( outfile, "\taddl $4, %%esp\n" );  /* room for final return address */
2164
2165         fprintf( outfile, "\tpushw %d(%%ebx)\n", CONTEXTOFFSET(SegCs) );
2166         fprintf( outfile, "\tpushw %d(%%ebx)\n", CONTEXTOFFSET(Eip) );
2167         fprintf( outfile, "\tpushl %%edx\n" );
2168         fprintf( outfile, "\tpushl %%eax\n" );
2169         fprintf( outfile, "\tpushl %d(%%ebx)\n", CONTEXTOFFSET(EFlags) );
2170         fprintf( outfile, "\tpushl %d(%%ebx)\n", CONTEXTOFFSET(SegDs) );
2171
2172         fprintf( outfile, "\tmovw %d(%%ebx), %%es\n", CONTEXTOFFSET(SegEs) );
2173         fprintf( outfile, "\tmovw %d(%%ebx), %%fs\n", CONTEXTOFFSET(SegFs) );
2174         fprintf( outfile, "\tmovw %d(%%ebx), %%gs\n", CONTEXTOFFSET(SegGs) );
2175
2176         fprintf( outfile, "\tmovl %d(%%ebx), %%ebp\n", CONTEXTOFFSET(Ebp) );
2177         fprintf( outfile, "\tmovl %d(%%ebx), %%esi\n", CONTEXTOFFSET(Esi) );
2178         fprintf( outfile, "\tmovl %d(%%ebx), %%edi\n", CONTEXTOFFSET(Edi) );
2179         fprintf( outfile, "\tmovl %d(%%ebx), %%eax\n", CONTEXTOFFSET(Eax) );
2180         fprintf( outfile, "\tmovl %d(%%ebx), %%edx\n", CONTEXTOFFSET(Edx) );
2181         fprintf( outfile, "\tmovl %d(%%ebx), %%ecx\n", CONTEXTOFFSET(Ecx) );
2182         fprintf( outfile, "\tmovl %d(%%ebx), %%ebx\n", CONTEXTOFFSET(Ebx) );
2183   
2184         fprintf( outfile, "\tpopl %%ds\n" );
2185         fprintf( outfile, "\tpopfl\n" );
2186         fprintf( outfile, "\tlret\n" );
2187     }
2188     else
2189     {
2190         /* Switch stack back */
2191         /* fprintf( outfile, "\t.byte 0x64\n\tlssw (%d), %%sp\n", STACKOFFSET ); */
2192         fprintf( outfile, "\t.byte 0x64,0x66,0x0f,0xb2,0x25\n\t.long %d\n", STACKOFFSET );
2193         fprintf( outfile, "\t.byte 0x64\n\tpopl (%d)\n", STACKOFFSET );
2194
2195         /* Restore registers */
2196         fprintf( outfile, "\tpopl %%edx\n" );
2197         fprintf( outfile, "\tpopl %%ecx\n" );
2198         fprintf( outfile, "\tpopl %%ebp\n" );
2199         fprintf( outfile, "\tpopw %%ds\n" );
2200         fprintf( outfile, "\tpopw %%es\n" );
2201         fprintf( outfile, "\tpopw %%fs\n" );
2202         fprintf( outfile, "\tpopw %%gs\n" );
2203
2204         /* Prepare return value and set flags accordingly */
2205         if ( !short_ret )
2206             fprintf( outfile, "\tshldl $16, %%eax, %%edx\n" );
2207         fprintf( outfile, "\torl %%eax, %%eax\n" );
2208
2209         /* Return to return stub which will return to caller */
2210         fprintf( outfile, "\tlret $12\n" );
2211     }
2212 }
2213   
2214
2215 /*******************************************************************
2216  *         BuildCallTo16Core
2217  *
2218  * This routine builds the core routines used in 32->16 thunks:
2219  *
2220  *   extern void CALLBACK CallTo16Word( SEGPTR target, int nb_args );
2221  *   extern void CALLBACK CallTo16Long( SEGPTR target, int nb_args );
2222  *   extern void CALLBACK CallTo16RegisterShort( const CONTEXT86 *context, int nb_args );
2223  *   extern void CALLBACK CallTo16RegisterLong ( const CONTEXT86 *context, int nb_args );
2224  *
2225  * These routines can be called directly from 32-bit code. 
2226  *
2227  * All routines expect that the 16-bit stack contents (arguments) were 
2228  * already set up by the caller; nb_args must contain the number of bytes 
2229  * to be conserved.  The 16-bit SS:SP will be set accordinly.
2230  *
2231  * All other registers are either taken from the CONTEXT86 structure 
2232  * or else set to default values.  The target routine address is either
2233  * given directly or taken from the CONTEXT86.
2234  *
2235  * If you want to call a 16-bit routine taking only standard argument types 
2236  * (WORD and LONG), you can also have an appropriate argument conversion 
2237  * stub automatically generated (see BuildCallTo16); you'd then call this
2238  * stub, which in turn would prepare the 16-bit stack and call the appropiate
2239  * core routine.
2240  *
2241  */
2242
2243 static void BuildCallTo16Core( FILE *outfile, int short_ret, int reg_func )
2244 {
2245     char *name = reg_func == 2 ? "RegisterLong" : 
2246                  reg_func == 1 ? "RegisterShort" :
2247                  short_ret? "Word" : "Long";
2248
2249     /* Function header */
2250     fprintf( outfile, "\n\t.align 4\n" );
2251 #ifdef USE_STABS
2252     fprintf( outfile, ".stabs \"CallTo16%s:F1\",36,0,0," PREFIX "CallTo16%s\n", 
2253              name, name);
2254 #endif
2255     fprintf( outfile, "\t.type " PREFIX "CallTo16%s,@function\n", name );
2256     fprintf( outfile, "\t.globl " PREFIX "CallTo16%s\n", name );
2257     fprintf( outfile, PREFIX "CallTo16%s:\n", name );
2258
2259     /* Function entry sequence */
2260     fprintf( outfile, "\tpushl %%ebp\n" );
2261     fprintf( outfile, "\tmovl %%esp, %%ebp\n" );
2262
2263     /* Save the 32-bit registers */
2264     fprintf( outfile, "\tpushl %%ebx\n" );
2265     fprintf( outfile, "\tpushl %%ecx\n" );
2266     fprintf( outfile, "\tpushl %%edx\n" );
2267     fprintf( outfile, "\tpushl %%esi\n" );
2268     fprintf( outfile, "\tpushl %%edi\n" );
2269
2270     if ( UsePIC )
2271     {
2272         /* Get Global Offset Table into %ebx */
2273         fprintf( outfile, "\tcall .LCallTo16%s.getgot1\n", name );
2274         fprintf( outfile, ".LCallTo16%s.getgot1:\n", name );
2275         fprintf( outfile, "\tpopl %%ebx\n" );
2276         fprintf( outfile, "\taddl $_GLOBAL_OFFSET_TABLE_+[.-.LCallTo16%s.getgot1], %%ebx\n", name );
2277     }
2278
2279     /* Enter Win16 Mutex */
2280     if ( UsePIC )
2281         fprintf( outfile, "\tcall " PREFIX "SYSLEVEL_EnterWin16Lock@PLT\n" );
2282     else
2283         fprintf( outfile, "\tcall " PREFIX "SYSLEVEL_EnterWin16Lock\n" );
2284
2285     /* Print debugging info */
2286     if (debugging)
2287     {
2288         /* Push flags, number of arguments, and target */
2289         fprintf( outfile, "\tpushl $%d\n", reg_func );
2290         fprintf( outfile, "\tpushl 12(%%ebp)\n" );
2291         fprintf( outfile, "\tpushl  8(%%ebp)\n" );
2292
2293         if ( UsePIC )
2294             fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallTo16@PLT\n" );
2295         else
2296             fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallTo16\n" );
2297
2298         fprintf( outfile, "\taddl $12, %%esp\n" );
2299     }
2300
2301     /* Get return address */
2302     if ( UsePIC )
2303     {
2304         fprintf( outfile, "\tmovl " PREFIX "CallTo16_RetAddr@GOT(%%ebx), %%ecx\n" );
2305         fprintf( outfile, "\tmovl " PREFIX "(%%ecx), %%ecx\n" );
2306     }
2307     else
2308         fprintf( outfile, "\tmovl " PREFIX "CallTo16_RetAddr, %%ecx\n" );
2309
2310     /* Call the actual CallTo16 routine (simulate a lcall) */
2311     fprintf( outfile, "\tpushl %%cs\n" );
2312     fprintf( outfile, "\tcall .LCallTo16%s\n", name );
2313
2314     /* Convert and push return value */
2315     if ( short_ret )
2316     {
2317         fprintf( outfile, "\tmovzwl %%ax, %%eax\n" );
2318         fprintf( outfile, "\tpushl %%eax\n" );
2319     }
2320     else if ( reg_func != 2 )
2321     {
2322         fprintf( outfile, "\tshll $16,%%edx\n" );
2323         fprintf( outfile, "\tmovw %%ax,%%dx\n" );
2324         fprintf( outfile, "\tpushl %%edx\n" );
2325     }
2326     else
2327         fprintf( outfile, "\tpushl %%eax\n" );
2328
2329     if ( UsePIC )
2330     {
2331         /* Get Global Offset Table into %ebx (might have been overwritten) */
2332         fprintf( outfile, "\tcall .LCallTo16%s.getgot2\n", name );
2333         fprintf( outfile, ".LCallTo16%s.getgot2:\n", name );
2334         fprintf( outfile, "\tpopl %%ebx\n" );
2335         fprintf( outfile, "\taddl $_GLOBAL_OFFSET_TABLE_+[.-.LCallTo16%s.getgot2], %%ebx\n", name );
2336     }
2337
2338     /* Print debugging info */
2339     if (debugging)
2340     {
2341         if ( UsePIC )
2342             fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallTo16Ret@PLT\n" );
2343         else
2344             fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallTo16Ret\n" );
2345     }
2346
2347     /* Leave Win16 Mutex */
2348     if ( UsePIC )
2349         fprintf( outfile, "\tcall " PREFIX "SYSLEVEL_LeaveWin16Lock@PLT\n" );
2350     else
2351         fprintf( outfile, "\tcall " PREFIX "SYSLEVEL_LeaveWin16Lock\n" );
2352
2353     /* Get return value */
2354     fprintf( outfile, "\tpopl %%eax\n" );
2355
2356     /* Restore the 32-bit registers */
2357     fprintf( outfile, "\tpopl %%edi\n" );
2358     fprintf( outfile, "\tpopl %%esi\n" );
2359     fprintf( outfile, "\tpopl %%edx\n" );
2360     fprintf( outfile, "\tpopl %%ecx\n" );
2361     fprintf( outfile, "\tpopl %%ebx\n" );
2362
2363     /* Function exit sequence */
2364     fprintf( outfile, "\tpopl %%ebp\n" );
2365     fprintf( outfile, "\tret $8\n" );
2366
2367
2368     /* Start of the actual CallTo16 routine */
2369
2370     fprintf( outfile, ".LCallTo16%s:\n", name );
2371
2372     /* Complete STACK32FRAME */
2373     fprintf( outfile, "\t.byte 0x64\n\tpushl (%d)\n", STACKOFFSET );
2374     fprintf( outfile, "\tmovl %%esp,%%edx\n" );
2375
2376     /* Switch to the 16-bit stack */
2377 #ifdef __svr4__
2378     fprintf( outfile,"\tdata16\n");
2379 #endif
2380     fprintf( outfile, "\t.byte 0x64\n\tmovw (%d),%%ss\n", STACKOFFSET + 2);
2381     fprintf( outfile, "\t.byte 0x64\n\tmovw (%d),%%sp\n", STACKOFFSET );
2382     fprintf( outfile, "\t.byte 0x64\n\tmovl %%edx,(%d)\n", STACKOFFSET );
2383
2384     /* Make %bp point to the previous stackframe (built by CallFrom16) */
2385     fprintf( outfile, "\tmovzwl %%sp,%%ebp\n" );
2386     fprintf( outfile, "\tleal %d(%%ebp),%%ebp\n", STACK16OFFSET(bp) );
2387
2388     /* Add the specified offset to the new sp */
2389     fprintf( outfile, "\tsubw %d(%%edx), %%sp\n", STACK32OFFSET(nb_args) );
2390
2391     /* Push the return address 
2392      * With sreg suffix, we push 16:16 address (normal lret)
2393      * With lreg suffix, we push 16:32 address (0x66 lret, for KERNEL32_45)
2394      */
2395     if (reg_func != 2)
2396         fprintf( outfile, "\tpushl %%ecx\n" );
2397     else 
2398     {
2399         fprintf( outfile, "\tshldl $16, %%ecx, %%eax\n" );
2400         fprintf( outfile, "\tpushw $0\n" );
2401         fprintf( outfile, "\tpushw %%ax\n" );
2402         fprintf( outfile, "\tpushw $0\n" );
2403         fprintf( outfile, "\tpushw %%cx\n" );
2404     }
2405
2406     if (reg_func)
2407     {
2408         /* Push the called routine address */
2409         fprintf( outfile, "\tmovl %d(%%edx),%%edx\n", STACK32OFFSET(target) );
2410         fprintf( outfile, "\tpushw %d(%%edx)\n", CONTEXTOFFSET(SegCs) );
2411         fprintf( outfile, "\tpushw %d(%%edx)\n", CONTEXTOFFSET(Eip) );
2412
2413         /* Get the registers */
2414         fprintf( outfile, "\tpushw %d(%%edx)\n", CONTEXTOFFSET(SegDs) );
2415         fprintf( outfile, "\tmovl %d(%%edx),%%eax\n", CONTEXTOFFSET(SegEs) );
2416         fprintf( outfile, "\tmovw %%ax,%%es\n" );
2417         fprintf( outfile, "\tmovl %d(%%edx),%%eax\n", CONTEXTOFFSET(SegFs) );
2418         fprintf( outfile, "\tmovw %%ax,%%fs\n" );
2419         fprintf( outfile, "\tmovl %d(%%edx),%%ebp\n", CONTEXTOFFSET(Ebp) );
2420         fprintf( outfile, "\tmovl %d(%%edx),%%esi\n", CONTEXTOFFSET(Esi) );
2421         fprintf( outfile, "\tmovl %d(%%edx),%%edi\n", CONTEXTOFFSET(Edi) );
2422         fprintf( outfile, "\tmovl %d(%%edx),%%eax\n", CONTEXTOFFSET(Eax) );
2423         fprintf( outfile, "\tmovl %d(%%edx),%%ebx\n", CONTEXTOFFSET(Ebx) );
2424         fprintf( outfile, "\tmovl %d(%%edx),%%ecx\n", CONTEXTOFFSET(Ecx) );
2425         fprintf( outfile, "\tmovl %d(%%edx),%%edx\n", CONTEXTOFFSET(Edx) );
2426
2427         /* Get the 16-bit ds */
2428         fprintf( outfile, "\tpopw %%ds\n" );
2429     }
2430     else  /* not a register function */
2431     {
2432         /* Push the called routine address */
2433         fprintf( outfile, "\tpushl %d(%%edx)\n", STACK32OFFSET(target) );
2434
2435         /* Set %fs to the value saved by the last CallFrom16 */
2436         fprintf( outfile, "\tmovw %d(%%ebp),%%ax\n", STACK16OFFSET(fs)-STACK16OFFSET(bp) );
2437         fprintf( outfile, "\tmovw %%ax,%%fs\n" );
2438
2439         /* Set %ds and %es (and %ax just in case) equal to %ss */
2440         fprintf( outfile, "\tmovw %%ss,%%ax\n" );
2441         fprintf( outfile, "\tmovw %%ax,%%ds\n" );
2442         fprintf( outfile, "\tmovw %%ax,%%es\n" );
2443     }
2444
2445     /* Jump to the called routine */
2446     fprintf( outfile, "\t.byte 0x66\n" );
2447     fprintf( outfile, "\tlret\n" );
2448 }
2449
2450 /*******************************************************************
2451  *         BuildRet16Func
2452  *
2453  * Build the return code for 16-bit callbacks
2454  */
2455 static void BuildRet16Func( FILE *outfile )
2456 {
2457     /* 
2458      *  Note: This must reside in the .data section to allow
2459      *        run-time relocation of the SYSLEVEL_Win16CurrentTeb symbol
2460      */
2461
2462     fprintf( outfile, "\n\t.type " PREFIX "CallTo16_Ret,@function\n" );
2463     fprintf( outfile, "\t.globl " PREFIX "CallTo16_Ret\n" );
2464     fprintf( outfile, PREFIX "CallTo16_Ret:\n" );
2465
2466     /* Restore 32-bit segment registers */
2467
2468     fprintf( outfile, "\tmovw $0x%04x,%%bx\n", Data_Selector );
2469 #ifdef __svr4__
2470     fprintf( outfile, "\tdata16\n");
2471 #endif
2472     fprintf( outfile, "\tmovw %%bx,%%ds\n" );
2473 #ifdef __svr4__
2474     fprintf( outfile, "\tdata16\n");
2475 #endif
2476     fprintf( outfile, "\tmovw %%bx,%%es\n" );
2477
2478     fprintf( outfile, "\tmovw " PREFIX "SYSLEVEL_Win16CurrentTeb,%%fs\n" );
2479
2480     /* Restore the 32-bit stack */
2481
2482 #ifdef __svr4__
2483     fprintf( outfile, "\tdata16\n");
2484 #endif
2485     fprintf( outfile, "\tmovw %%bx,%%ss\n" );
2486     fprintf( outfile, "\t.byte 0x64\n\tmovl (%d),%%esp\n", STACKOFFSET );
2487     fprintf( outfile, "\t.byte 0x64\n\tpopl (%d)\n", STACKOFFSET );
2488
2489     /* Return to caller */
2490
2491     fprintf( outfile, "\tlret\n" );
2492
2493     /* Declare the return address variable */
2494
2495     fprintf( outfile, "\n\t.globl " PREFIX "CallTo16_RetAddr\n" );
2496     fprintf( outfile, PREFIX "CallTo16_RetAddr:\t.long 0\n" );
2497 }
2498
2499 /*******************************************************************
2500  *         BuildCallTo32CBClient
2501  *
2502  * Call a CBClient relay stub from 32-bit code (KERNEL.620).
2503  *
2504  * Since the relay stub is itself 32-bit, this should not be a problem;
2505  * unfortunately, the relay stubs are expected to switch back to a 
2506  * 16-bit stack (and 16-bit code) after completion :-(
2507  *
2508  * This would conflict with our 16- vs. 32-bit stack handling, so
2509  * we simply switch *back* to our 32-bit stack before returning to
2510  * the caller ...
2511  *
2512  * The CBClient relay stub expects to be called with the following
2513  * 16-bit stack layout, and with ebp and ebx pointing into the 16-bit
2514  * stack at the designated places:
2515  *
2516  *    ...
2517  *  (ebp+14) original arguments to the callback routine
2518  *  (ebp+10) far return address to original caller
2519  *  (ebp+6)  Thunklet target address
2520  *  (ebp+2)  Thunklet relay ID code
2521  *  (ebp)    BP (saved by CBClientGlueSL)
2522  *  (ebp-2)  SI (saved by CBClientGlueSL)
2523  *  (ebp-4)  DI (saved by CBClientGlueSL)
2524  *  (ebp-6)  DS (saved by CBClientGlueSL)
2525  *
2526  *   ...     buffer space used by the 16-bit side glue for temp copies
2527  *
2528  *  (ebx+4)  far return address to 16-bit side glue code
2529  *  (ebx)    saved 16-bit ss:sp (pointing to ebx+4)
2530  *
2531  * The 32-bit side glue code accesses both the original arguments (via ebp)
2532  * and the temporary copies prepared by the 16-bit side glue (via ebx).
2533  * After completion, the stub will load ss:sp from the buffer at ebx
2534  * and perform a far return to 16-bit code.  
2535  *
2536  * To trick the relay stub into returning to us, we replace the 16-bit
2537  * return address to the glue code by a cs:ip pair pointing to our
2538  * return entry point (the original return address is saved first).
2539  * Our return stub thus called will then reload the 32-bit ss:esp and
2540  * return to 32-bit code (by using and ss:esp value that we have also
2541  * pushed onto the 16-bit stack before and a cs:eip values found at
2542  * that position on the 32-bit stack).  The ss:esp to be restored is
2543  * found relative to the 16-bit stack pointer at:
2544  *
2545  *  (ebx-4)   ss  (flat)
2546  *  (ebx-8)   sp  (32-bit stack pointer)
2547  *
2548  * The second variant of this routine, CALL32_CBClientEx, which is used
2549  * to implement KERNEL.621, has to cope with yet another problem: Here,
2550  * the 32-bit side directly returns to the caller of the CBClient thunklet,
2551  * restoring registers saved by CBClientGlueSL and cleaning up the stack.
2552  * As we have to return to our 32-bit code first, we have to adapt the
2553  * layout of our temporary area so as to include values for the registers
2554  * that are to be restored, and later (in the implementation of KERNEL.621)
2555  * we *really* restore them. The return stub restores DS, DI, SI, and BP
2556  * from the stack, skips the next 8 bytes (CBClient relay code / target),
2557  * and then performs a lret NN, where NN is the number of arguments to be
2558  * removed. Thus, we prepare our temporary area as follows:
2559  *
2560  *     (ebx+22) 16-bit cs  (this segment)
2561  *     (ebx+20) 16-bit ip  ('16-bit' return entry point)
2562  *     (ebx+16) 32-bit ss  (flat)
2563  *     (ebx+12) 32-bit sp  (32-bit stack pointer)
2564  *     (ebx+10) 16-bit bp  (points to ebx+24)
2565  *     (ebx+8)  16-bit si  (ignored)
2566  *     (ebx+6)  16-bit di  (ignored)
2567  *     (ebx+4)  16-bit ds  (we actually use the flat DS here)
2568  *     (ebx+2)  16-bit ss  (16-bit stack segment)
2569  *     (ebx+0)  16-bit sp  (points to ebx+4)
2570  *
2571  * Note that we ensure that DS is not changed and remains the flat segment,
2572  * and the 32-bit stack pointer our own return stub needs fits just 
2573  * perfectly into the 8 bytes that are skipped by the Windows stub.
2574  * One problem is that we have to determine the number of removed arguments,
2575  * as these have to be really removed in KERNEL.621. Thus, the BP value 
2576  * that we place in the temporary area to be restored, contains the value 
2577  * that SP would have if no arguments were removed. By comparing the actual
2578  * value of SP with this value in our return stub we can compute the number
2579  * of removed arguments. This is then returned to KERNEL.621.
2580  *
2581  * The stack layout of this function:
2582  * (ebp+20)  nArgs     pointer to variable receiving nr. of args (Ex only)
2583  * (ebp+16)  esi       pointer to caller's esi value
2584  * (ebp+12)  arg       ebp value to be set for relay stub
2585  * (ebp+8)   func      CBClient relay stub address
2586  * (ebp+4)   ret addr
2587  * (ebp)     ebp
2588  */
2589 static void BuildCallTo32CBClient( FILE *outfile, BOOL isEx )
2590 {
2591     char *name = isEx? "CBClientEx" : "CBClient";
2592     int size = isEx? 24 : 12;
2593
2594     /* Function header */
2595
2596     fprintf( outfile, "\n\t.align 4\n" );
2597 #ifdef USE_STABS
2598     fprintf( outfile, ".stabs \"CALL32_%s:F1\",36,0,0," PREFIX "CALL32_%s\n",
2599                       name, name );
2600 #endif
2601     fprintf( outfile, "\t.globl " PREFIX "CALL32_%s\n", name );
2602     fprintf( outfile, PREFIX "CALL32_%s:\n", name );
2603
2604     /* Entry code */
2605
2606     fprintf( outfile, "\tpushl %%ebp\n" );
2607     fprintf( outfile, "\tmovl %%esp,%%ebp\n" );
2608     fprintf( outfile, "\tpushl %%edi\n" );
2609     fprintf( outfile, "\tpushl %%esi\n" );
2610     fprintf( outfile, "\tpushl %%ebx\n" );
2611
2612     /* Get the 16-bit stack */
2613
2614     fprintf( outfile, "\t.byte 0x64\n\tmovl (%d),%%ebx\n", STACKOFFSET);
2615     
2616     /* Convert it to a flat address */
2617
2618     fprintf( outfile, "\tshldl $16,%%ebx,%%eax\n" );
2619     fprintf( outfile, "\tandl $0xfff8,%%eax\n" );
2620     fprintf( outfile, "\tmovl " PREFIX "ldt_copy(%%eax),%%esi\n" );
2621     fprintf( outfile, "\tmovw %%bx,%%ax\n" );
2622     fprintf( outfile, "\taddl %%eax,%%esi\n" );
2623
2624     /* Allocate temporary area (simulate STACK16_PUSH) */
2625
2626     fprintf( outfile, "\tpushf\n" );
2627     fprintf( outfile, "\tcld\n" );
2628     fprintf( outfile, "\tleal -%d(%%esi), %%edi\n", size );
2629     fprintf( outfile, "\tmovl $%d, %%ecx\n", sizeof(STACK16FRAME) );
2630     fprintf( outfile, "\trep\n\tmovsb\n" );
2631     fprintf( outfile, "\tpopf\n" );
2632
2633     fprintf( outfile, "\t.byte 0x64\n\tsubw $%d,(%d)\n", size, STACKOFFSET );
2634
2635     fprintf( outfile, "\tpushl %%edi\n" );  /* remember address */
2636
2637     /* Set up temporary area */
2638
2639     if ( !isEx )
2640     {
2641         fprintf( outfile, "\tleal 4(%%edi), %%edi\n" );
2642
2643         fprintf( outfile, "\tleal -8(%%esp), %%eax\n" );
2644         fprintf( outfile, "\tmovl %%eax, -8(%%edi)\n" );    /* 32-bit sp */
2645
2646         fprintf( outfile, "\tmovw %%ss, %%ax\n" );
2647         fprintf( outfile, "\tandl $0x0000ffff, %%eax\n" );
2648         fprintf( outfile, "\tmovl %%eax, -4(%%edi)\n" );    /* 32-bit ss */
2649
2650         fprintf( outfile, "\taddl $%d, %%ebx\n", sizeof(STACK16FRAME)-size+4 + 4 );
2651         fprintf( outfile, "\tmovl %%ebx, 0(%%edi)\n" );    /* 16-bit ss:sp */
2652
2653         fprintf( outfile, "\tmovl " PREFIX "CALL32_%s_RetAddr, %%eax\n", name );
2654         fprintf( outfile, "\tmovl %%eax, 4(%%edi)\n" );   /* overwrite return address */
2655     }
2656     else
2657     {
2658         fprintf( outfile, "\taddl $%d, %%ebx\n", sizeof(STACK16FRAME)-size+4 );
2659         fprintf( outfile, "\tmovl %%ebx, 0(%%edi)\n" );
2660
2661         fprintf( outfile, "\tmovw %%ds, %%ax\n" );
2662         fprintf( outfile, "\tmovw %%ax, 4(%%edi)\n" );
2663
2664         fprintf( outfile, "\taddl $20, %%ebx\n" );
2665         fprintf( outfile, "\tmovw %%bx, 10(%%edi)\n" );
2666
2667         fprintf( outfile, "\tleal -8(%%esp), %%eax\n" );
2668         fprintf( outfile, "\tmovl %%eax, 12(%%edi)\n" );
2669
2670         fprintf( outfile, "\tmovw %%ss, %%ax\n" );
2671         fprintf( outfile, "\tandl $0x0000ffff, %%eax\n" );
2672         fprintf( outfile, "\tmovl %%eax, 16(%%edi)\n" );
2673
2674         fprintf( outfile, "\tmovl " PREFIX "CALL32_%s_RetAddr, %%eax\n", name );
2675         fprintf( outfile, "\tmovl %%eax, 20(%%edi)\n" );
2676     }
2677
2678     /* Set up registers and call CBClient relay stub (simulating a far call) */
2679
2680     fprintf( outfile, "\tmovl 16(%%ebp), %%esi\n" );
2681     fprintf( outfile, "\tmovl (%%esi), %%esi\n" );
2682
2683     fprintf( outfile, "\tmovl %%edi, %%ebx\n" );
2684     fprintf( outfile, "\tmovl 8(%%ebp), %%eax\n" );
2685     fprintf( outfile, "\tmovl 12(%%ebp), %%ebp\n" );
2686
2687     fprintf( outfile, "\tpushl %%cs\n" );
2688     fprintf( outfile, "\tcall *%%eax\n" );
2689
2690     /* Return new esi value to caller */
2691
2692     fprintf( outfile, "\tmovl 32(%%esp), %%edi\n" );
2693     fprintf( outfile, "\tmovl %%esi, (%%edi)\n" );
2694
2695     /* Cleanup temporary area (simulate STACK16_POP) */
2696
2697     fprintf( outfile, "\tpop %%esi\n" );
2698
2699     fprintf( outfile, "\tpushf\n" );
2700     fprintf( outfile, "\tstd\n" );
2701     fprintf( outfile, "\tdec %%esi\n" );
2702     fprintf( outfile, "\tleal %d(%%esi), %%edi\n", size );
2703     fprintf( outfile, "\tmovl $%d, %%ecx\n", sizeof(STACK16FRAME) );
2704     fprintf( outfile, "\trep\n\tmovsb\n" );
2705     fprintf( outfile, "\tpopf\n" );
2706
2707     fprintf( outfile, "\t.byte 0x64\n\taddw $%d,(%d)\n", size, STACKOFFSET );
2708
2709     /* Return argument size to caller */
2710     if ( isEx )
2711     {
2712         fprintf( outfile, "\tmovl 32(%%esp), %%ebx\n" );
2713         fprintf( outfile, "\tmovl %%ebp, (%%ebx)\n" );
2714     }
2715
2716     /* Restore registers and return */
2717
2718     fprintf( outfile, "\tpopl %%ebx\n" );
2719     fprintf( outfile, "\tpopl %%esi\n" );
2720     fprintf( outfile, "\tpopl %%edi\n" );
2721     fprintf( outfile, "\tpopl %%ebp\n" );
2722     fprintf( outfile, "\tret\n" );
2723 }
2724
2725 static void BuildCallTo32CBClientRet( FILE *outfile, BOOL isEx )
2726 {
2727     char *name = isEx? "CBClientEx" : "CBClient";
2728
2729     /* '16-bit' return stub */
2730
2731     fprintf( outfile, "\n\t.globl " PREFIX "CALL32_%s_Ret\n", name );
2732     fprintf( outfile, PREFIX "CALL32_%s_Ret:\n", name );
2733
2734     if ( !isEx )
2735     {
2736         fprintf( outfile, "\tmovzwl %%sp, %%ebx\n" );
2737         fprintf( outfile, "\tlssl %%ss:-16(%%ebx), %%esp\n" );
2738     }
2739     else
2740     {
2741         fprintf( outfile, "\tmovzwl %%bp, %%ebx\n" );
2742         fprintf( outfile, "\tsubw %%bp, %%sp\n" );
2743         fprintf( outfile, "\tmovzwl %%sp, %%ebp\n" );
2744         fprintf( outfile, "\tlssl %%ss:-12(%%ebx), %%esp\n" );
2745     }
2746     fprintf( outfile, "\tlret\n" );
2747
2748     /* Declare the return address variable */
2749
2750     fprintf( outfile, "\n\t.globl " PREFIX "CALL32_%s_RetAddr\n", name );
2751     fprintf( outfile, PREFIX "CALL32_%s_RetAddr:\t.long 0\n", name );
2752 }
2753
2754
2755 /*******************************************************************
2756  *         BuildCallTo32LargeStack
2757  *
2758  * Build the function used to switch to the original 32-bit stack
2759  * before calling a 32-bit function from 32-bit code. This is used for
2760  * functions that need a large stack, like X bitmaps functions.
2761  *
2762  * The generated function has the following prototype:
2763  *   int xxx( int (*func)(), void *arg );
2764  *
2765  * The pointer to the function can be retrieved by calling CALL32_Init,
2766  * which also takes care of saving the current 32-bit stack pointer.
2767  * Furthermore, CALL32_Init switches to a new stack and jumps to the
2768  * specified target address.
2769  *
2770  * NOTE: The CALL32_LargeStack routine may be recursively entered by the 
2771  *       same thread, but not concurrently entered by several threads.
2772  *
2773  * Stack layout of CALL32_Init:
2774  *
2775  * (esp+12)  new stack address
2776  * (esp+8)   target address
2777  * (esp+4)   pointer to variable to receive CALL32_LargeStack address
2778  * (esp)     ret addr
2779  *
2780  * Stack layout of CALL32_LargeStack:
2781  *   ...     ...
2782  * (ebp+12)  arg
2783  * (ebp+8)   func
2784  * (ebp+4)   ret addr
2785  * (ebp)     ebp
2786  */
2787 static void BuildCallTo32LargeStack( FILE *outfile )
2788 {
2789     /* Initialization function */
2790
2791     fprintf( outfile, "\n\t.align 4\n" );
2792 #ifdef USE_STABS
2793     fprintf( outfile, ".stabs \"CALL32_Init:F1\",36,0,0," PREFIX "CALL32_Init\n");
2794 #endif
2795     fprintf( outfile, "\t.globl " PREFIX "CALL32_Init\n" );
2796     fprintf( outfile, "\t.type " PREFIX "CALL32_Init,@function\n" );
2797     fprintf( outfile, PREFIX "CALL32_Init:\n" );
2798     fprintf( outfile, "\tmovl %%esp,CALL32_Original32_esp\n" );
2799     fprintf( outfile, "\tpopl %%eax\n" );
2800     fprintf( outfile, "\tpopl %%eax\n" );
2801     fprintf( outfile, "\tmovl $CALL32_LargeStack,(%%eax)\n" );
2802     fprintf( outfile, "\tpopl %%eax\n" );
2803     fprintf( outfile, "\tpopl %%esp\n" );
2804     fprintf( outfile, "\tpushl %%eax\n" );
2805     fprintf( outfile, "\tret\n" );
2806
2807     /* Function header */
2808
2809     fprintf( outfile, "\n\t.align 4\n" );
2810 #ifdef USE_STABS
2811     fprintf( outfile, ".stabs \"CALL32_LargeStack:F1\",36,0,0,CALL32_LargeStack\n");
2812 #endif
2813     fprintf( outfile, "CALL32_LargeStack:\n" );
2814     
2815     /* Entry code */
2816
2817     fprintf( outfile, "\tpushl %%ebp\n" );
2818     fprintf( outfile, "\tmovl %%esp,%%ebp\n" );
2819
2820     /* Switch to the original 32-bit stack pointer */
2821
2822     fprintf( outfile, "\tcmpl $0, CALL32_RecursionCount\n" );
2823     fprintf( outfile, "\tjne  CALL32_skip\n" );
2824     fprintf( outfile, "\tmovl CALL32_Original32_esp, %%esp\n" );
2825     fprintf( outfile, "CALL32_skip:\n" );
2826
2827     fprintf( outfile, "\tincl CALL32_RecursionCount\n" );
2828
2829     /* Transfer the argument and call the function */
2830
2831     fprintf( outfile, "\tpushl 12(%%ebp)\n" );
2832     fprintf( outfile, "\tcall *8(%%ebp)\n" );
2833
2834     /* Restore registers and return */
2835
2836     fprintf( outfile, "\tdecl CALL32_RecursionCount\n" );
2837
2838     fprintf( outfile, "\tmovl %%ebp,%%esp\n" );
2839     fprintf( outfile, "\tpopl %%ebp\n" );
2840     fprintf( outfile, "\tret\n" );
2841
2842     /* Data */
2843
2844     fprintf( outfile, "\t.data\n" );
2845     fprintf( outfile, "CALL32_Original32_esp:\t.long 0\n" );
2846     fprintf( outfile, "CALL32_RecursionCount:\t.long 0\n" );
2847     fprintf( outfile, "\t.text\n" );
2848 }
2849
2850
2851 /*******************************************************************
2852  *         BuildCallFrom32Regs
2853  *
2854  * Build a 32-bit-to-Wine call-back function for a 'register' function.
2855  * 'args' is the number of dword arguments.
2856  *
2857  * Stack layout:
2858  *   ...
2859  * (ebp+12)  first arg
2860  * (ebp+8)   ret addr to user code
2861  * (ebp+4)   ret addr to relay code
2862  * (ebp+0)   saved ebp
2863  * (ebp-128) buffer area to allow stack frame manipulation
2864  * (ebp-332) CONTEXT86 struct
2865  * (ebp-336) CONTEXT86 *argument
2866  *  ....     other arguments copied from (ebp+12)
2867  *
2868  * The entry point routine is called with a CONTEXT* extra argument,
2869  * following the normal args. In this context structure, EIP_reg
2870  * contains the return address to user code, and ESP_reg the stack
2871  * pointer on return (with the return address and arguments already
2872  * removed).
2873  */
2874 static void BuildCallFrom32Regs( FILE *outfile )
2875 {
2876     static const int STACK_SPACE = 128 + sizeof(CONTEXT86);
2877
2878     /* Function header */
2879
2880     fprintf( outfile, "\n\t.align 4\n" );
2881 #ifdef USE_STABS
2882     fprintf( outfile, ".stabs \"CALL32_Regs:F1\",36,0,0," PREFIX "CALL32_Regs\n" );
2883 #endif
2884     fprintf( outfile, "\t.globl " PREFIX "CALL32_Regs\n" );
2885     fprintf( outfile, PREFIX "CALL32_Regs:\n" );
2886
2887     /* Allocate some buffer space on the stack */
2888
2889     fprintf( outfile, "\tpushl %%ebp\n" );
2890     fprintf( outfile, "\tmovl %%esp,%%ebp\n ");
2891     fprintf( outfile, "\tleal -%d(%%esp), %%esp\n", STACK_SPACE );
2892     
2893     /* Build the context structure */
2894
2895     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(Eax) - STACK_SPACE );
2896     fprintf( outfile, "\tpushfl\n" );
2897     fprintf( outfile, "\tpopl %%eax\n" );
2898     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(EFlags) - STACK_SPACE );
2899     fprintf( outfile, "\tmovl 0(%%ebp),%%eax\n" );
2900     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(Ebp) - STACK_SPACE );
2901     fprintf( outfile, "\tmovl %%ebx,%d(%%ebp)\n", CONTEXTOFFSET(Ebx) - STACK_SPACE );
2902     fprintf( outfile, "\tmovl %%ecx,%d(%%ebp)\n", CONTEXTOFFSET(Ecx) - STACK_SPACE );
2903     fprintf( outfile, "\tmovl %%edx,%d(%%ebp)\n", CONTEXTOFFSET(Edx) - STACK_SPACE );
2904     fprintf( outfile, "\tmovl %%esi,%d(%%ebp)\n", CONTEXTOFFSET(Esi) - STACK_SPACE );
2905     fprintf( outfile, "\tmovl %%edi,%d(%%ebp)\n", CONTEXTOFFSET(Edi) - STACK_SPACE );
2906
2907     fprintf( outfile, "\txorl %%eax,%%eax\n" );
2908     fprintf( outfile, "\tmovw %%cs,%%ax\n" );
2909     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(SegCs) - STACK_SPACE );
2910     fprintf( outfile, "\tmovw %%es,%%ax\n" );
2911     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(SegEs) - STACK_SPACE );
2912     fprintf( outfile, "\tmovw %%fs,%%ax\n" );
2913     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(SegFs) - STACK_SPACE );
2914     fprintf( outfile, "\tmovw %%gs,%%ax\n" );
2915     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(SegGs) - STACK_SPACE );
2916     fprintf( outfile, "\tmovw %%ss,%%ax\n" );
2917     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(SegSs) - STACK_SPACE );
2918     fprintf( outfile, "\tmovw %%ds,%%ax\n" );
2919     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(SegDs) - STACK_SPACE );
2920     fprintf( outfile, "\tmovw %%ax,%%es\n" );  /* set %es equal to %ds just in case */
2921
2922     fprintf( outfile, "\tmovl $0x%x,%%eax\n", CONTEXT86_FULL );
2923     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(ContextFlags) - STACK_SPACE );
2924
2925     fprintf( outfile, "\tmovl 8(%%ebp),%%eax\n" ); /* Get %eip at time of call */
2926     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(Eip) - STACK_SPACE );
2927
2928     /* Transfer the arguments */
2929
2930     fprintf( outfile, "\tmovl 4(%%ebp),%%ebx\n" );   /* get relay code addr */
2931     fprintf( outfile, "\tpushl %%esp\n" );           /* push ptr to context struct */
2932     fprintf( outfile, "\tmovzbl 4(%%ebx),%%ecx\n" ); /* fetch number of args to copy */
2933     fprintf( outfile, "\tjecxz 1f\n" );
2934     fprintf( outfile, "\tsubl %%ecx,%%esp\n" );
2935     fprintf( outfile, "\tleal 12(%%ebp),%%esi\n" );  /* get %esp at time of call */
2936     fprintf( outfile, "\tmovl %%esp,%%edi\n" );
2937     fprintf( outfile, "\tshrl $2,%%ecx\n" );
2938     fprintf( outfile, "\tcld\n" );
2939     fprintf( outfile, "\trep\n\tmovsl\n" );  /* copy args */
2940
2941     fprintf( outfile, "1:\tmovzbl 5(%%ebx),%%eax\n" ); /* fetch number of args to remove */
2942     fprintf( outfile, "\tleal 12(%%ebp,%%eax),%%eax\n" );
2943     fprintf( outfile, "\tmovl %%eax,%d(%%ebp)\n", CONTEXTOFFSET(Esp) - STACK_SPACE );
2944
2945     /* Call the entry point */
2946
2947     fprintf( outfile, "\tcall *0(%%ebx)\n" );
2948
2949     /* Store %eip and %ebp onto the new stack */
2950
2951     fprintf( outfile, "\tmovl %d(%%ebp),%%edx\n", CONTEXTOFFSET(Esp) - STACK_SPACE );
2952     fprintf( outfile, "\tmovl %d(%%ebp),%%eax\n", CONTEXTOFFSET(Eip) - STACK_SPACE );
2953     fprintf( outfile, "\tmovl %%eax,-4(%%edx)\n" );
2954     fprintf( outfile, "\tmovl %d(%%ebp),%%eax\n", CONTEXTOFFSET(Ebp) - STACK_SPACE );
2955     fprintf( outfile, "\tmovl %%eax,-8(%%edx)\n" );
2956
2957     /* Restore the context structure */
2958
2959     /* Note: we don't bother to restore %cs, %ds and %ss
2960      *       changing them in 32-bit code is a recipe for disaster anyway
2961      */
2962     fprintf( outfile, "\tmovl %d(%%ebp),%%eax\n", CONTEXTOFFSET(SegEs) - STACK_SPACE );
2963     fprintf( outfile, "\tmovw %%ax,%%es\n" );
2964     fprintf( outfile, "\tmovl %d(%%ebp),%%eax\n", CONTEXTOFFSET(SegFs) - STACK_SPACE );
2965     fprintf( outfile, "\tmovw %%ax,%%fs\n" );
2966     fprintf( outfile, "\tmovl %d(%%ebp),%%eax\n", CONTEXTOFFSET(SegGs) - STACK_SPACE );
2967     fprintf( outfile, "\tmovw %%ax,%%gs\n" );
2968
2969     fprintf( outfile, "\tmovl %d(%%ebp),%%edi\n", CONTEXTOFFSET(Edi) - STACK_SPACE );
2970     fprintf( outfile, "\tmovl %d(%%ebp),%%esi\n", CONTEXTOFFSET(Esi) - STACK_SPACE );
2971     fprintf( outfile, "\tmovl %d(%%ebp),%%edx\n", CONTEXTOFFSET(Edx) - STACK_SPACE );
2972     fprintf( outfile, "\tmovl %d(%%ebp),%%ecx\n", CONTEXTOFFSET(Ecx) - STACK_SPACE );
2973     fprintf( outfile, "\tmovl %d(%%ebp),%%ebx\n", CONTEXTOFFSET(Ebx) - STACK_SPACE );
2974
2975     fprintf( outfile, "\tmovl %d(%%ebp),%%eax\n", CONTEXTOFFSET(EFlags) - STACK_SPACE );
2976     fprintf( outfile, "\tpushl %%eax\n" );
2977     fprintf( outfile, "\tpopfl\n" );
2978     fprintf( outfile, "\tmovl %d(%%ebp),%%eax\n", CONTEXTOFFSET(Eax) - STACK_SPACE );
2979
2980     fprintf( outfile, "\tmovl %d(%%ebp),%%ebp\n", CONTEXTOFFSET(Esp) - STACK_SPACE );
2981     fprintf( outfile, "\tleal -8(%%ebp),%%esp\n" );
2982     fprintf( outfile, "\tpopl %%ebp\n" );
2983     fprintf( outfile, "\tret\n" );
2984 }
2985
2986
2987 /*******************************************************************
2988  *         BuildGlue
2989  *
2990  * Build the 16-bit-to-Wine/Wine-to-16-bit callback glue code
2991  */
2992 static void BuildGlue( FILE *outfile, FILE *infile )
2993 {
2994     char buffer[1024];
2995
2996     /* File header */
2997
2998     fprintf( outfile, "/* File generated automatically from %s; do not edit! */\n\n",
2999              input_file_name );
3000     fprintf( outfile, "#include \"builtin16.h\"\n" );
3001     fprintf( outfile, "#include \"stackframe.h\"\n\n" );
3002
3003     /* Build the callback glue functions */
3004
3005     while (fgets( buffer, sizeof(buffer), infile ))
3006     {
3007         if (strstr( buffer, "### start build ###" )) break;
3008     }
3009     while (fgets( buffer, sizeof(buffer), infile ))
3010     {
3011         char *p; 
3012         if ( (p = strstr( buffer, "CallFrom16_" )) != NULL )
3013         {
3014             char *q, *profile = p + strlen( "CallFrom16_" );
3015             for (q = profile; (*q == '_') || isalpha(*q); q++ )
3016                 ;
3017             *q = '\0';
3018             for (q = p-1; q > buffer && ((*q == '_') || isalnum(*q)); q-- )
3019                 ;
3020             if ( ++q < p ) p[-1] = '\0'; else q = "";
3021             BuildCallFrom16Func( outfile, profile, q, FALSE );
3022         }
3023         if ( (p = strstr( buffer, "CallTo16_" )) != NULL )
3024         {
3025             char *q, *profile = p + strlen( "CallTo16_" );
3026             for (q = profile; (*q == '_') || isalpha(*q); q++ )
3027                 ;
3028             *q = '\0';
3029             for (q = p-1; q > buffer && ((*q == '_') || isalnum(*q)); q-- )
3030                 ;
3031             if ( ++q < p ) p[-1] = '\0'; else q = "";
3032             BuildCallTo16Func( outfile, profile, q );
3033         }
3034         if (strstr( buffer, "### stop build ###" )) break;
3035     }
3036
3037     fclose( infile );
3038 }
3039
3040 /*******************************************************************
3041  *         BuildCall16
3042  *
3043  * Build the 16-bit callbacks
3044  */
3045 static void BuildCall16( FILE *outfile )
3046 {
3047     /* File header */
3048
3049     fprintf( outfile, "/* File generated automatically. Do not edit! */\n\n" );
3050     fprintf( outfile, "\t.text\n" );
3051
3052 #ifdef __i386__
3053
3054 #ifdef USE_STABS
3055     if (output_file_name)
3056     {
3057         char buffer[1024];
3058         getcwd(buffer, sizeof(buffer));
3059         fprintf( outfile, "\t.file\t\"%s\"\n", output_file_name );
3060
3061         /*
3062          * The stabs help the internal debugger as they are an indication that it
3063          * is sensible to step into a thunk/trampoline.
3064          */
3065         fprintf( outfile, ".stabs \"%s/\",100,0,0,Code_Start\n", buffer);
3066         fprintf( outfile, ".stabs \"%s\",100,0,0,Code_Start\n", output_file_name );
3067         fprintf( outfile, "Code_Start:\n\n" );
3068     }
3069 #endif
3070     fprintf( outfile, PREFIX"Call16_Start:\n" );
3071     fprintf( outfile, "\t.globl "PREFIX"Call16_Start\n" );
3072     fprintf( outfile, "\t.byte 0\n\n" );
3073
3074
3075     /* Standard CallFrom16 routine (WORD return) */
3076     BuildCallFrom16Core( outfile, FALSE, FALSE, TRUE );
3077
3078     /* Standard CallFrom16 routine (DWORD return) */
3079     BuildCallFrom16Core( outfile, FALSE, FALSE, FALSE );
3080
3081     /* Register CallFrom16 routine */
3082     BuildCallFrom16Core( outfile, TRUE, FALSE, FALSE );
3083
3084     /* C16ThkSL CallFrom16 routine */
3085     BuildCallFrom16Core( outfile, FALSE, TRUE, FALSE );
3086
3087     /* Standard CallTo16 routine (WORD return) */
3088     BuildCallTo16Core( outfile, TRUE, FALSE );
3089
3090     /* Standard CallTo16 routine (DWORD return) */
3091     BuildCallTo16Core( outfile, FALSE, FALSE );
3092
3093     /* Register CallTo16 routine (16:16 retf) */
3094     BuildCallTo16Core( outfile, FALSE, 1 );
3095
3096     /* Register CallTo16 routine (16:32 retf) */
3097     BuildCallTo16Core( outfile, FALSE, 2 );
3098
3099     /* CBClientThunkSL routine */
3100     BuildCallTo32CBClient( outfile, FALSE );
3101
3102     /* CBClientThunkSLEx routine */
3103     BuildCallTo32CBClient( outfile, TRUE  );
3104
3105     fprintf( outfile, PREFIX"Call16_End:\n" );
3106     fprintf( outfile, "\t.globl "PREFIX"Call16_End\n" );
3107
3108 #ifdef USE_STABS
3109     fprintf( outfile, "\t.stabs \"\",100,0,0,.Letext\n");
3110     fprintf( outfile, ".Letext:\n");
3111 #endif
3112
3113     /* The whole Call16_Ret segment must lie within the .data section */
3114     fprintf( outfile, "\n\t.data\n" );
3115     fprintf( outfile, "\t.globl " PREFIX "Call16_Ret_Start\n" );
3116     fprintf( outfile, PREFIX "Call16_Ret_Start:\n" );
3117
3118     /* Standard CallTo16 return stub */
3119     BuildRet16Func( outfile );
3120
3121     /* CBClientThunkSL return stub */
3122     BuildCallTo32CBClientRet( outfile, FALSE );
3123
3124     /* CBClientThunkSLEx return stub */
3125     BuildCallTo32CBClientRet( outfile, TRUE  );
3126
3127     /* End of Call16_Ret segment */
3128     fprintf( outfile, "\n\t.globl " PREFIX "Call16_Ret_End\n" );
3129     fprintf( outfile, PREFIX "Call16_Ret_End:\n" );
3130
3131 #else  /* __i386__ */
3132
3133     fprintf( outfile, PREFIX"Call16_Start:\n" );
3134     fprintf( outfile, "\t.globl "PREFIX"Call16_Start\n" );
3135     fprintf( outfile, "\t.byte 0\n\n" );
3136     fprintf( outfile, PREFIX"Call16_End:\n" );
3137     fprintf( outfile, "\t.globl "PREFIX"Call16_End\n" );
3138
3139     fprintf( outfile, "\t.globl " PREFIX "Call16_Ret_Start\n" );
3140     fprintf( outfile, PREFIX "Call16_Ret_Start:\n" );
3141     fprintf( outfile, "\t.byte 0\n\n" );
3142     fprintf( outfile, "\n\t.globl " PREFIX "Call16_Ret_End\n" );
3143     fprintf( outfile, PREFIX "Call16_Ret_End:\n" );
3144
3145 #endif  /* __i386__ */
3146 }
3147
3148 /*******************************************************************
3149  *         BuildCall32
3150  *
3151  * Build the 32-bit callbacks
3152  */
3153 static void BuildCall32( FILE *outfile )
3154 {
3155     /* File header */
3156
3157     fprintf( outfile, "/* File generated automatically. Do not edit! */\n\n" );
3158     fprintf( outfile, "\t.text\n" );
3159
3160 #ifdef __i386__
3161
3162 #ifdef USE_STABS
3163     if (output_file_name)
3164     {
3165         char buffer[1024];
3166         getcwd(buffer, sizeof(buffer));
3167         fprintf( outfile, "\t.file\t\"%s\"\n", output_file_name );
3168
3169         /*
3170          * The stabs help the internal debugger as they are an indication that it
3171          * is sensible to step into a thunk/trampoline.
3172          */
3173         fprintf( outfile, ".stabs \"%s/\",100,0,0,Code_Start\n", buffer);
3174         fprintf( outfile, ".stabs \"%s\",100,0,0,Code_Start\n", output_file_name );
3175         fprintf( outfile, "Code_Start:\n" );
3176     }
3177 #endif
3178
3179     /* Build the 32-bit large stack callback */
3180
3181     BuildCallTo32LargeStack( outfile );
3182
3183     /* Build the register callback function */
3184
3185     BuildCallFrom32Regs( outfile );
3186
3187 #ifdef USE_STABS
3188     fprintf( outfile, "\t.text\n");
3189     fprintf( outfile, "\t.stabs \"\",100,0,0,.Letext\n");
3190     fprintf( outfile, ".Letext:\n");
3191 #endif
3192
3193 #else  /* __i386__ */
3194
3195     /* Just to avoid an empty file */
3196     fprintf( outfile, "\t.long 0\n" );
3197
3198 #endif  /* __i386__ */
3199 }
3200
3201
3202 /*******************************************************************
3203  *         usage
3204  */
3205 static void usage(void)
3206 {
3207     fprintf( stderr,
3208              "usage: build [-pic] [-o outfile] -spec SPEC_FILE\n"
3209              "       build [-pic] [-o outfile] -glue SOURCE_FILE\n"
3210              "       build [-pic] [-o outfile] -call16\n"
3211              "       build [-pic] [-o outfile] -call32\n" );
3212     if (output_file_name) unlink( output_file_name );
3213     exit(1);
3214 }
3215
3216
3217 /*******************************************************************
3218  *         open_input
3219  */
3220 static FILE *open_input( const char *name )
3221 {
3222     FILE *f;
3223
3224     if (!name)
3225     {
3226         input_file_name = "<stdin>";
3227         return stdin;
3228     }
3229     input_file_name = name;
3230     if (!(f = fopen( name, "r" )))
3231     {
3232         fprintf( stderr, "Cannot open input file '%s'\n", name );
3233         if (output_file_name) unlink( output_file_name );
3234         exit(1);
3235     }
3236     return f;
3237 }
3238
3239 /*******************************************************************
3240  *         main
3241  */
3242 int main(int argc, char **argv)
3243 {
3244     FILE *outfile = stdout;
3245
3246     if (argc < 2) usage();
3247
3248     if (!strcmp( argv[1], "-pic" ))
3249     {
3250         UsePIC = 1;
3251         argv += 1;
3252         argc -= 1;
3253         if (argc < 2) usage();
3254     }
3255
3256     if (!strcmp( argv[1], "-o" ))
3257     {
3258         output_file_name = argv[2];
3259         argv += 2;
3260         argc -= 2;
3261         if (argc < 2) usage();
3262         if (!(outfile = fopen( output_file_name, "w" )))
3263         {
3264             fprintf( stderr, "Unable to create output file '%s'\n", output_file_name );
3265             exit(1);
3266         }
3267     }
3268
3269     /* Retrieve the selector values; this assumes that we are building
3270      * the asm files on the platform that will also run them. Probably
3271      * a safe assumption to make.
3272      */
3273     Code_Selector = __get_cs();
3274     Data_Selector = __get_ds();
3275
3276     if (!strcmp( argv[1], "-spec" )) BuildSpecFile( outfile, open_input( argv[2] ) );
3277     else if (!strcmp( argv[1], "-glue" )) BuildGlue( outfile, open_input( argv[2] ) );
3278     else if (!strcmp( argv[1], "-call16" )) BuildCall16( outfile );
3279     else if (!strcmp( argv[1], "-call32" )) BuildCall32( outfile );
3280     else
3281     {
3282         fclose( outfile );
3283         usage();
3284     }
3285
3286     fclose( outfile );
3287     return 0;
3288 }