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