Release 980104
[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  */
7
8 #include <assert.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <ctype.h>
13 #include <unistd.h>
14
15 #include "windows.h"
16 #include "winnt.h"
17 #include "module.h"
18 #include "neexe.h"
19 #include "selectors.h"
20 #include "stackframe.h"
21
22 #ifdef NEED_UNDERSCORE_PREFIX
23 # define PREFIX "_"
24 #else
25 # define PREFIX
26 #endif
27
28 #if defined(__GNUC__) && !defined(__svr4__)
29 # define USE_STABS
30 #else
31 # undef USE_STABS
32 #endif
33
34 typedef enum
35 {
36     TYPE_INVALID,
37     TYPE_BYTE,         /* byte variable (Win16) */
38     TYPE_WORD,         /* word variable (Win16) */
39     TYPE_LONG,         /* long variable (Win16) */
40     TYPE_PASCAL_16,    /* pascal function with 16-bit return (Win16) */
41     TYPE_PASCAL,       /* pascal function with 32-bit return (Win16) */
42     TYPE_ABS,          /* absolute value (Win16) */
43     TYPE_RETURN,       /* simple return value function (Win16) */
44     TYPE_REGISTER,     /* register function */
45     TYPE_STUB,         /* unimplemented stub */
46     TYPE_STDCALL,      /* stdcall function (Win32) */
47     TYPE_CDECL,        /* cdecl function (Win32) */
48     TYPE_VARARGS,      /* varargs function (Win32) */
49     TYPE_EXTERN,       /* external symbol (Win32) */
50     TYPE_NBTYPES
51 } ORD_TYPE;
52
53 static const char * const TypeNames[TYPE_NBTYPES] =
54 {
55     NULL,
56     "byte",         /* TYPE_BYTE */
57     "word",         /* TYPE_WORD */
58     "long",         /* TYPE_LONG */
59     "pascal16",     /* TYPE_PASCAL_16 */
60     "pascal",       /* TYPE_PASCAL */
61     "equate",       /* TYPE_ABS */
62     "return",       /* TYPE_RETURN */
63     "register",     /* TYPE_REGISTER */
64     "stub",         /* TYPE_STUB */
65     "stdcall",      /* TYPE_STDCALL */
66     "cdecl",        /* TYPE_CDECL */
67     "varargs",      /* TYPE_VARARGS */
68     "extern"        /* TYPE_EXTERN */
69 };
70
71 #define MAX_ORDINALS    2048
72
73   /* Callback function used for stub functions */
74 #define STUB_CALLBACK \
75   ((SpecType == SPEC_WIN16) ? "RELAY_Unimplemented16": "RELAY_Unimplemented32")
76
77 typedef enum
78 {
79     SPEC_INVALID,
80     SPEC_WIN16,
81     SPEC_WIN32
82 } SPEC_TYPE;
83
84 typedef struct
85 {
86     int n_values;
87     int *values;
88 } ORD_VARIABLE;
89
90 typedef struct
91 {
92     int  n_args;
93     char arg_types[32];
94     char link_name[80];
95 } ORD_FUNCTION;
96
97 typedef struct
98 {
99     int arg_size;
100     int ret_value;
101 } ORD_RETURN;
102
103 typedef struct
104 {
105     int value;
106 } ORD_ABS;
107
108 typedef struct
109 {
110     char link_name[80];
111 } ORD_VARARGS;
112
113 typedef struct
114 {
115     char link_name[80];
116 } ORD_EXTERN;
117
118 typedef struct
119 {
120     ORD_TYPE    type;
121     int         offset;
122     int         lineno;
123     char        name[80];
124     union
125     {
126         ORD_VARIABLE   var;
127         ORD_FUNCTION   func;
128         ORD_RETURN     ret;
129         ORD_ABS        abs;
130         ORD_VARARGS    vargs;
131         ORD_EXTERN     ext;
132     } u;
133 } ORDDEF;
134
135 static ORDDEF OrdinalDefinitions[MAX_ORDINALS];
136
137 static SPEC_TYPE SpecType = SPEC_INVALID;
138 static char DLLName[80];
139 static char DLLFileName[80];
140 static int Limit = 0;
141 static int Base = MAX_ORDINALS;
142 static int DLLHeapSize = 0;
143 static char *SpecName;
144 static FILE *SpecFp;
145 static WORD Code_Selector, Data_Selector;
146
147 char *ParseBuffer = NULL;
148 char *ParseNext;
149 char ParseSaveChar;
150 int Line;
151
152 static int debugging = 1;
153
154   /* Offset of a structure field relative to the start of the struct */
155 #define STRUCTOFFSET(type,field) ((int)&((type *)0)->field)
156
157   /* Offset of register relative to the start of the CONTEXT struct */
158 #define CONTEXTOFFSET(reg)  STRUCTOFFSET(CONTEXT,reg)
159
160 static void *xmalloc (size_t size)
161 {
162     void *res;
163
164     res = malloc (size ? size : 1);
165     if (res == NULL)
166     {
167         fprintf (stderr, "Virtual memory exhausted.\n");
168         exit (1);
169     }
170     return res;
171 }
172
173
174 static void *xrealloc (void *ptr, size_t size)
175 {
176     void *res = realloc (ptr, size);
177     if (res == NULL)
178     {
179         fprintf (stderr, "Virtual memory exhausted.\n");
180         exit (1);
181     }
182     return res;
183 }
184
185
186 static int IsNumberString(char *s)
187 {
188     while (*s != '\0')
189         if (!isdigit(*s++))
190             return 0;
191
192     return 1;
193 }
194
195 static char *strupper(char *s)
196 {
197     char *p;
198     
199     for(p = s; *p != '\0'; p++)
200         *p = toupper(*p);
201
202     return s;
203 }
204
205 static char * GetTokenInLine(void)
206 {
207     char *p;
208     char *token;
209
210     if (ParseNext != ParseBuffer)
211     {
212         if (ParseSaveChar == '\0')
213             return NULL;
214         *ParseNext = ParseSaveChar;
215     }
216     
217     /*
218      * Remove initial white space.
219      */
220     for (p = ParseNext; isspace(*p); p++)
221         ;
222     
223     if ((*p == '\0') || (*p == '#'))
224         return NULL;
225     
226     /*
227      * Find end of token.
228      */
229     token = p++;
230     if (*token != '(' && *token != ')')
231         while (*p != '\0' && *p != '(' && *p != ')' && !isspace(*p))
232             p++;
233     
234     ParseSaveChar = *p;
235     ParseNext = p;
236     *p = '\0';
237
238     return token;
239 }
240
241 static char * GetToken(void)
242 {
243     char *token;
244
245     if (ParseBuffer == NULL)
246     {
247         ParseBuffer = xmalloc(512);
248         ParseNext = ParseBuffer;
249         while (1)
250         {
251             Line++;
252             if (fgets(ParseBuffer, 511, SpecFp) == NULL)
253                 return NULL;
254             if (ParseBuffer[0] != '#')
255                 break;
256         }
257     }
258
259     while ((token = GetTokenInLine()) == NULL)
260     {
261         ParseNext = ParseBuffer;
262         while (1)
263         {
264             Line++;
265             if (fgets(ParseBuffer, 511, SpecFp) == NULL)
266                 return NULL;
267             if (ParseBuffer[0] != '#')
268                 break;
269         }
270     }
271
272     return token;
273 }
274
275
276 /*******************************************************************
277  *         ParseVariable
278  *
279  * Parse a variable definition.
280  */
281 static int ParseVariable( ORDDEF *odp )
282 {
283     char *endptr;
284     int *value_array;
285     int n_values;
286     int value_array_size;
287     
288     char *token = GetToken();
289     if (*token != '(')
290     {
291         fprintf(stderr, "%s:%d: Expected '(' got '%s'\n",
292                 SpecName, Line, token);
293         return -1;
294     }
295
296     n_values = 0;
297     value_array_size = 25;
298     value_array = xmalloc(sizeof(*value_array) * value_array_size);
299     
300     while ((token = GetToken()) != NULL)
301     {
302         if (*token == ')')
303             break;
304
305         value_array[n_values++] = strtol(token, &endptr, 0);
306         if (n_values == value_array_size)
307         {
308             value_array_size += 25;
309             value_array = xrealloc(value_array, 
310                                    sizeof(*value_array) * value_array_size);
311         }
312         
313         if (endptr == NULL || *endptr != '\0')
314         {
315             fprintf(stderr, "%s:%d: Expected number value, got '%s'\n",
316                     SpecName, Line, token);
317             return -1;
318         }
319     }
320     
321     if (token == NULL)
322     {
323         fprintf(stderr, "%s:%d: End of file in variable declaration\n",
324                 SpecName, Line);
325         return -1;
326     }
327
328     odp->u.var.n_values = n_values;
329     odp->u.var.values = xrealloc(value_array, sizeof(*value_array) * n_values);
330
331     return 0;
332 }
333
334
335 /*******************************************************************
336  *         ParseExportFunction
337  *
338  * Parse a function definition.
339  */
340 static int ParseExportFunction( ORDDEF *odp )
341 {
342     char *token;
343     int i;
344
345     switch(SpecType)
346     {
347     case SPEC_WIN16:
348         if (odp->type == TYPE_STDCALL)
349         {
350             fprintf( stderr, "%s:%d: 'stdcall' not supported for Win16\n",
351                      SpecName, Line );
352             return -1;
353         }
354         if (odp->type == TYPE_CDECL)
355         {
356             fprintf( stderr, "%s:%d: 'cdecl' not supported for Win16\n",
357                      SpecName, Line );
358             return -1;
359         }
360         break;
361     case SPEC_WIN32:
362         if ((odp->type == TYPE_PASCAL) || (odp->type == TYPE_PASCAL_16))
363         {
364             fprintf( stderr, "%s:%d: 'pascal' not supported for Win32\n",
365                      SpecName, Line );
366             return -1;
367         }
368         break;
369     default:
370         break;
371     }
372
373     token = GetToken();
374     if (*token != '(')
375     {
376         fprintf(stderr, "%s:%d: Expected '(' got '%s'\n",
377                 SpecName, Line, token);
378         return -1;
379     }
380
381     for (i = 0; i < sizeof(odp->u.func.arg_types)-1; i++)
382     {
383         token = GetToken();
384         if (*token == ')')
385             break;
386
387         if (!strcmp(token, "word"))
388             odp->u.func.arg_types[i] = 'w';
389         else if (!strcmp(token, "s_word"))
390             odp->u.func.arg_types[i] = 's';
391         else if (!strcmp(token, "long") || !strcmp(token, "segptr"))
392             odp->u.func.arg_types[i] = 'l';
393         else if (!strcmp(token, "ptr"))
394             odp->u.func.arg_types[i] = 'p';
395         else if (!strcmp(token, "str"))
396             odp->u.func.arg_types[i] = 't';
397         else if (!strcmp(token, "wstr"))
398             odp->u.func.arg_types[i] = 'W';
399         else if (!strcmp(token, "segstr"))
400             odp->u.func.arg_types[i] = 'T';
401         else if (!strcmp(token, "double"))
402         {
403             odp->u.func.arg_types[i++] = 'l';
404             odp->u.func.arg_types[i] = 'l';
405         }
406         else
407         {
408             fprintf(stderr, "%s:%d: Unknown variable type '%s'\n",
409                     SpecName, Line, token);
410             return -1;
411         }
412         if (SpecType == SPEC_WIN32)
413         {
414             if (strcmp(token, "long") &&
415                 strcmp(token, "ptr") &&
416                 strcmp(token, "str") &&
417                 strcmp(token, "wstr") &&
418                 strcmp(token, "double"))
419             {
420                 fprintf( stderr, "%s:%d: Type '%s' not supported for Win32\n",
421                          SpecName, Line, token );
422                 return -1;
423             }
424         }
425     }
426     if ((*token != ')') || (i >= sizeof(odp->u.func.arg_types)))
427     {
428         fprintf( stderr, "%s:%d: Too many arguments\n", SpecName, Line );
429         return -1;
430     }
431     odp->u.func.arg_types[i] = '\0';
432     if ((odp->type == TYPE_STDCALL) && !i)
433         odp->type = TYPE_CDECL; /* stdcall is the same as cdecl for 0 args */
434     if ((odp->type == TYPE_REGISTER) && (SpecType == SPEC_WIN32) && i)
435     {
436         fprintf( stderr, "%s:%d: register functions cannot have arguments in Win32\n",
437                  SpecName, Line );
438         return -1;
439     }
440     strcpy(odp->u.func.link_name, GetToken());
441     return 0;
442 }
443
444
445 /*******************************************************************
446  *         ParseEquate
447  *
448  * Parse an 'equate' definition.
449  */
450 static int ParseEquate( ORDDEF *odp )
451 {
452     char *endptr;
453     
454     char *token = GetToken();
455     int value = strtol(token, &endptr, 0);
456     if (endptr == NULL || *endptr != '\0')
457     {
458         fprintf(stderr, "%s:%d: Expected number value, got '%s'\n",
459                 SpecName, Line, token);
460         return -1;
461     }
462
463     if (SpecType == SPEC_WIN32)
464     {
465         fprintf( stderr, "%s:%d: 'equate' not supported for Win32\n",
466                  SpecName, Line );
467         return -1;
468     }
469
470     odp->u.abs.value = value;
471     return 0;
472 }
473
474
475 /*******************************************************************
476  *         ParseReturn
477  *
478  * Parse a 'return' definition.
479  */
480 static int ParseReturn( ORDDEF *odp )
481 {
482     char *token;
483     char *endptr;
484     
485     token = GetToken();
486     odp->u.ret.arg_size = strtol(token, &endptr, 0);
487     if (endptr == NULL || *endptr != '\0')
488     {
489         fprintf(stderr, "%s:%d: Expected number value, got '%s'\n",
490                 SpecName, Line, token);
491         return -1;
492     }
493
494     token = GetToken();
495     odp->u.ret.ret_value = strtol(token, &endptr, 0);
496     if (endptr == NULL || *endptr != '\0')
497     {
498         fprintf(stderr, "%s:%d: Expected number value, got '%s'\n",
499                 SpecName, Line, token);
500         return -1;
501     }
502
503     if (SpecType == SPEC_WIN32)
504     {
505         fprintf( stderr, "%s:%d: 'return' not supported for Win32\n",
506                  SpecName, Line );
507         return -1;
508     }
509
510     return 0;
511 }
512
513
514 /*******************************************************************
515  *         ParseStub
516  *
517  * Parse a 'stub' definition.
518  */
519 static int ParseStub( ORDDEF *odp )
520 {
521     odp->u.func.arg_types[0] = '\0';
522     strcpy( odp->u.func.link_name, STUB_CALLBACK );
523     return 0;
524 }
525
526
527 /*******************************************************************
528  *         ParseVarargs
529  *
530  * Parse an 'varargs' definition.
531  */
532 static int ParseVarargs( ORDDEF *odp )
533 {
534     char *token;
535
536     if (SpecType == SPEC_WIN16)
537     {
538         fprintf( stderr, "%s:%d: 'varargs' not supported for Win16\n",
539                  SpecName, Line );
540         return -1;
541     }
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     token = GetToken();
551     if (*token != ')')
552     {
553         fprintf(stderr, "%s:%d: Expected ')' got '%s'\n",
554                 SpecName, Line, token);
555         return -1;
556     }
557
558     strcpy( odp->u.vargs.link_name, GetToken() );
559     return 0;
560 }
561
562
563 /*******************************************************************
564  *         ParseExtern
565  *
566  * Parse an 'extern' definition.
567  */
568 static int ParseExtern( ORDDEF *odp )
569 {
570     if (SpecType == SPEC_WIN16)
571     {
572         fprintf( stderr, "%s:%d: 'extern' not supported for Win16\n",
573                  SpecName, Line );
574         return -1;
575     }
576     strcpy( odp->u.ext.link_name, GetToken() );
577     return 0;
578 }
579
580
581 /*******************************************************************
582  *         ParseOrdinal
583  *
584  * Parse an ordinal definition.
585  */
586 static int ParseOrdinal(int ordinal)
587 {
588     ORDDEF *odp;
589     char *token;
590
591     if (ordinal >= MAX_ORDINALS)
592     {
593         fprintf(stderr, "%s:%d: Ordinal number too large\n", SpecName, Line );
594         return -1;
595     }
596     if (ordinal > Limit) Limit = ordinal;
597     if (ordinal < Base) Base = ordinal;
598
599     odp = &OrdinalDefinitions[ordinal];
600     if (!(token = GetToken()))
601     {
602         fprintf(stderr, "%s:%d: Expected type after ordinal\n", SpecName, Line);
603         return -1;
604     }
605
606     for (odp->type = 0; odp->type < TYPE_NBTYPES; odp->type++)
607         if (TypeNames[odp->type] && !strcmp( token, TypeNames[odp->type] ))
608             break;
609
610     if (odp->type >= TYPE_NBTYPES)
611     {
612         fprintf( stderr,
613                  "%s:%d: Expected type after ordinal, found '%s' instead\n",
614                  SpecName, Line, token );
615         return -1;
616     }
617
618     if (!(token = GetToken()))
619     {
620         fprintf( stderr, "%s:%d: Expected name after type\n", SpecName, Line );
621         return -1;
622     }
623     strcpy( odp->name, token );
624     odp->lineno = Line;
625
626     switch(odp->type)
627     {
628     case TYPE_BYTE:
629     case TYPE_WORD:
630     case TYPE_LONG:
631         return ParseVariable( odp );
632     case TYPE_PASCAL_16:
633     case TYPE_PASCAL:
634     case TYPE_REGISTER:
635     case TYPE_STDCALL:
636     case TYPE_CDECL:
637         return ParseExportFunction( odp );
638     case TYPE_ABS:
639         return ParseEquate( odp );
640     case TYPE_RETURN:
641         return ParseReturn( odp );
642     case TYPE_STUB:
643         return ParseStub( odp );
644     case TYPE_VARARGS:
645         return ParseVarargs( odp );
646     case TYPE_EXTERN:
647         return ParseExtern( odp );
648     default:
649         fprintf( stderr, "Should not happen\n" );
650         return -1;
651     }
652 }
653
654
655 /*******************************************************************
656  *         ParseTopLevel
657  *
658  * Parse a spec file.
659  */
660 static int ParseTopLevel(void)
661 {
662     char *token;
663     
664     while ((token = GetToken()) != NULL)
665     {
666         if (strcmp(token, "name") == 0)
667         {
668             strcpy(DLLName, GetToken());
669             strupper(DLLName);
670             if (!DLLFileName[0]) sprintf( DLLFileName, "%s.DLL", DLLName );
671         }
672         else if (strcmp(token, "file") == 0)
673         {
674             strcpy(DLLFileName, GetToken());
675             strupper(DLLFileName);
676         }
677         else if (strcmp(token, "type") == 0)
678         {
679             token = GetToken();
680             if (!strcmp(token, "win16" )) SpecType = SPEC_WIN16;
681             else if (!strcmp(token, "win32" )) SpecType = SPEC_WIN32;
682             else
683             {
684                 fprintf(stderr, "%s:%d: Type must be 'win16' or 'win32'\n",
685                         SpecName, Line);
686                 return -1;
687             }
688         }
689         else if (strcmp(token, "heap") == 0)
690         {
691             token = GetToken();
692             if (!IsNumberString(token))
693             {
694                 fprintf(stderr, "%s:%d: Expected number after heap\n",
695                         SpecName, Line);
696                 return -1;
697             }
698             DLLHeapSize = atoi(token);
699         }
700         else if (IsNumberString(token))
701         {
702             int ordinal;
703             int rv;
704             
705             ordinal = atoi(token);
706             if ((rv = ParseOrdinal(ordinal)) < 0)
707                 return rv;
708         }
709         else
710         {
711             fprintf(stderr, 
712                     "%s:%d: Expected name, id, length or ordinal\n",
713                     SpecName, Line);
714             return -1;
715         }
716     }
717
718     return 0;
719 }
720
721
722 /*******************************************************************
723  *         StoreVariableCode
724  *
725  * Store a list of ints into a byte array.
726  */
727 static int StoreVariableCode( unsigned char *buffer, int size, ORDDEF *odp )
728 {
729     int i;
730
731     switch(size)
732     {
733     case 1:
734         for (i = 0; i < odp->u.var.n_values; i++)
735             buffer[i] = odp->u.var.values[i];
736         break;
737     case 2:
738         for (i = 0; i < odp->u.var.n_values; i++)
739             ((unsigned short *)buffer)[i] = odp->u.var.values[i];
740         break;
741     case 4:
742         for (i = 0; i < odp->u.var.n_values; i++)
743             ((unsigned int *)buffer)[i] = odp->u.var.values[i];
744         break;
745     }
746     return odp->u.var.n_values * size;
747 }
748
749
750 /*******************************************************************
751  *         DumpBytes
752  *
753  * Dump a byte stream into the assembly code.
754  */
755 static void DumpBytes( FILE *outfile, const unsigned char *data, int len,
756                        const char *section, const char *label_start )
757 {
758     int i;
759     if (section) fprintf( outfile, "\t%s\n", section );
760     if (label_start) fprintf( outfile, "%s:\n", label_start );
761     for (i = 0; i < len; i++)
762     {
763         if (!(i & 0x0f)) fprintf( outfile, "\t.byte " );
764         fprintf( outfile, "%d", *data++ );
765         if (i < len - 1)
766             fprintf( outfile, "%c", ((i & 0x0f) != 0x0f) ? ',' : '\n' );
767     }
768     fprintf( outfile, "\n" );
769 }
770
771
772 /*******************************************************************
773  *         BuildModule16
774  *
775  * Build the in-memory representation of a 16-bit NE module, and dump it
776  * as a byte stream into the assembly code.
777  */
778 static int BuildModule16( FILE *outfile, int max_code_offset,
779                           int max_data_offset )
780 {
781     ORDDEF *odp;
782     int i;
783     char *buffer;
784     NE_MODULE *pModule;
785     SEGTABLEENTRY *pSegment;
786     OFSTRUCT *pFileInfo;
787     BYTE *pstr, *bundle;
788     WORD *pword;
789
790     /*   Module layout:
791      * NE_MODULE       Module
792      * OFSTRUCT        File information
793      * SEGTABLEENTRY   Segment 1 (code)
794      * SEGTABLEENTRY   Segment 2 (data)
795      * WORD[2]         Resource table (empty)
796      * BYTE[2]         Imported names (empty)
797      * BYTE[n]         Resident names table
798      * BYTE[n]         Entry table
799      */
800
801     buffer = xmalloc( 0x10000 );
802
803     pModule = (NE_MODULE *)buffer;
804     pModule->magic = IMAGE_OS2_SIGNATURE;
805     pModule->count = 1;
806     pModule->next = 0;
807     pModule->flags = NE_FFLAGS_SINGLEDATA | NE_FFLAGS_BUILTIN | NE_FFLAGS_LIBMODULE;
808     pModule->dgroup = 2;
809     pModule->heap_size = DLLHeapSize;
810     pModule->stack_size = 0;
811     pModule->ip = 0;
812     pModule->cs = 0;
813     pModule->sp = 0;
814     pModule->ss = 0;
815     pModule->seg_count = 2;
816     pModule->modref_count = 0;
817     pModule->nrname_size = 0;
818     pModule->modref_table = 0;
819     pModule->nrname_fpos = 0;
820     pModule->moveable_entries = 0;
821     pModule->alignment = 0;
822     pModule->truetype = 0;
823     pModule->os_flags = NE_OSFLAGS_WINDOWS;
824     pModule->misc_flags = 0;
825     pModule->dlls_to_init  = 0;
826     pModule->nrname_handle = 0;
827     pModule->min_swap_area = 0;
828     pModule->expected_version = 0x030a;
829     pModule->module32 = 0;
830     pModule->self = 0;
831     pModule->self_loading_sel = 0;
832
833       /* File information */
834
835     pFileInfo = (OFSTRUCT *)(pModule + 1);
836     pModule->fileinfo = (int)pFileInfo - (int)pModule;
837     memset( pFileInfo, 0, sizeof(*pFileInfo) - sizeof(pFileInfo->szPathName) );
838     pFileInfo->cBytes = sizeof(*pFileInfo) - sizeof(pFileInfo->szPathName)
839                         + strlen(DLLFileName);
840     strcpy( pFileInfo->szPathName, DLLFileName );
841     pstr = (char *)pFileInfo + pFileInfo->cBytes + 1;
842         
843       /* Segment table */
844
845     pSegment = (SEGTABLEENTRY *)pstr;
846     pModule->seg_table = (int)pSegment - (int)pModule;
847     pSegment->filepos = 0;
848     pSegment->size = max_code_offset;
849     pSegment->flags = 0;
850     pSegment->minsize = max_code_offset;
851     pSegment->selector = 0;
852     pSegment++;
853
854     pModule->dgroup_entry = (int)pSegment - (int)pModule;
855     pSegment->filepos = 0;
856     pSegment->size = max_data_offset;
857     pSegment->flags = NE_SEGFLAGS_DATA;
858     pSegment->minsize = max_data_offset;
859     pSegment->selector = 0;
860     pSegment++;
861
862       /* Resource table */
863
864     pword = (WORD *)pSegment;
865     pModule->res_table = (int)pword - (int)pModule;
866     *pword++ = 0;
867     *pword++ = 0;
868
869       /* Imported names table */
870
871     pstr = (char *)pword;
872     pModule->import_table = (int)pstr - (int)pModule;
873     *pstr++ = 0;
874     *pstr++ = 0;
875
876       /* Resident names table */
877
878     pModule->name_table = (int)pstr - (int)pModule;
879     /* First entry is module name */
880     *pstr = strlen(DLLName );
881     strcpy( pstr + 1, DLLName );
882     pstr += *pstr + 1;
883     *(WORD *)pstr = 0;
884     pstr += sizeof(WORD);
885     /* Store all ordinals */
886     odp = OrdinalDefinitions + 1;
887     for (i = 1; i <= Limit; i++, odp++)
888     {
889         if (!odp->name[0]) continue;
890         *pstr = strlen( odp->name );
891         strcpy( pstr + 1, odp->name );
892         strupper( pstr + 1 );
893         pstr += *pstr + 1;
894         *(WORD *)pstr = i;
895         pstr += sizeof(WORD);
896     }
897     *pstr++ = 0;
898
899       /* Entry table */
900
901     pModule->entry_table = (int)pstr - (int)pModule;
902     bundle = NULL;
903     odp = OrdinalDefinitions + 1;
904     for (i = 1; i <= Limit; i++, odp++)
905     {
906         int selector = 0;
907
908         switch (odp->type)
909         {
910         case TYPE_PASCAL:
911         case TYPE_PASCAL_16:
912         case TYPE_REGISTER:
913         case TYPE_RETURN:
914         case TYPE_STUB:
915             selector = 1;  /* Code selector */
916             break;
917
918         case TYPE_BYTE:
919         case TYPE_WORD:
920         case TYPE_LONG:
921             selector = 2;  /* Data selector */
922             break;
923
924         case TYPE_ABS:
925             selector = 0xfe;  /* Constant selector */
926             break;
927
928         default:
929             selector = 0;  /* Invalid selector */
930             break;
931         }
932
933           /* create a new bundle if necessary */
934         if (!bundle || (bundle[0] >= 254) || (bundle[1] != selector))
935         {
936             bundle = pstr;
937             bundle[0] = 0;
938             bundle[1] = selector;
939             pstr += 2;
940         }
941
942         (*bundle)++;
943         if (selector != 0)
944         {
945             *pstr++ = 1;
946             *(WORD *)pstr = odp->offset;
947             pstr += sizeof(WORD);
948         }
949     }
950     *pstr++ = 0;
951
952       /* Dump the module content */
953
954     DumpBytes( outfile, (char *)pModule, (int)pstr - (int)pModule,
955                ".data", "Module_Start" );
956     return (int)pstr - (int)pModule;
957 }
958
959
960 /*******************************************************************
961  *         BuildSpec32File
962  *
963  * Build a Win32 C file from a spec file.
964  */
965 static int BuildSpec32File( char * specfile, FILE *outfile )
966 {
967     ORDDEF *odp;
968     int i, nb_names, nb_reg_funcs = 0;
969
970     fprintf( outfile, "/* File generated automatically from %s; do not edit! */\n\n",
971              specfile );
972     fprintf( outfile, "#include \"builtin32.h\"\n\n" );
973
974     /* Output code for all stubs functions */
975
976     fprintf( outfile, "extern const BUILTIN32_DESCRIPTOR %s_Descriptor;\n",
977              DLLName );
978     for (i = Base, odp = OrdinalDefinitions + Base; i <= Limit; i++, odp++)
979     {
980         if (odp->type != TYPE_STUB) continue;
981         fprintf( outfile, "static void __stub_%d() { BUILTIN32_Unimplemented(&%s_Descriptor,%d); }\n",
982                  i, DLLName, i );
983     }
984
985     /* Output the DLL functions prototypes */
986
987     for (i = Base, odp = OrdinalDefinitions + Base; i <= Limit; i++, odp++)
988     {
989         switch(odp->type)
990         {
991         case TYPE_VARARGS:
992             fprintf( outfile, "extern void %s();\n", odp->u.vargs.link_name );
993             break;
994         case TYPE_EXTERN:
995             fprintf( outfile, "extern void %s();\n", odp->u.ext.link_name );
996             break;
997         case TYPE_REGISTER:
998         case TYPE_STDCALL:
999         case TYPE_CDECL:
1000             fprintf( outfile, "extern void %s();\n", odp->u.func.link_name );
1001             break;
1002         case TYPE_INVALID:
1003         case TYPE_STUB:
1004             break;
1005         default:
1006             fprintf(stderr,"build: function type %d not available for Win32\n",
1007                     odp->type);
1008             return -1;
1009         }
1010     }
1011
1012     /* Output the DLL functions table */
1013
1014     fprintf( outfile, "\nstatic const ENTRYPOINT32 Functions[%d] =\n{\n",
1015              Limit - Base + 1 );
1016     for (i = Base, odp = OrdinalDefinitions + Base; i <= Limit; i++, odp++)
1017     {
1018         switch(odp->type)
1019         {
1020         case TYPE_INVALID:
1021             fprintf( outfile, "    0" );
1022             break;
1023         case TYPE_VARARGS:
1024             fprintf( outfile, "    %s", odp->u.vargs.link_name );
1025             break;
1026         case TYPE_EXTERN:
1027             fprintf( outfile, "    %s", odp->u.ext.link_name );
1028             break;
1029         case TYPE_REGISTER:
1030         case TYPE_STDCALL:
1031         case TYPE_CDECL:
1032             fprintf( outfile, "    %s", odp->u.func.link_name);
1033             break;
1034         case TYPE_STUB:
1035             fprintf( outfile, "    __stub_%d", i );
1036             break;
1037         default:
1038             return -1;
1039         }
1040         if (i < Limit) fprintf( outfile, ",\n" );
1041     }
1042     fprintf( outfile, "\n};\n\n" );
1043
1044     /* Output the DLL names table */
1045
1046     nb_names = 0;
1047     fprintf( outfile, "static const char * const FuncNames[] =\n{\n" );
1048     for (i = Base, odp = OrdinalDefinitions + Base; i <= Limit; i++, odp++)
1049     {
1050         if (odp->type == TYPE_INVALID) continue;
1051         if (nb_names++) fprintf( outfile, ",\n" );
1052         fprintf( outfile, "    \"%s\"", odp->name );
1053     }
1054     fprintf( outfile, "\n};\n\n" );
1055
1056     /* Output the DLL argument types */
1057
1058     fprintf( outfile, "static const unsigned int ArgTypes[%d] =\n{\n",
1059              Limit - Base + 1 );
1060     for (i = Base, odp = OrdinalDefinitions + Base; i <= Limit; i++, odp++)
1061     {
1062         unsigned int j, mask = 0;
1063         if ((odp->type == TYPE_STDCALL) || (odp->type == TYPE_CDECL))
1064             for (j = 0; odp->u.func.arg_types[j]; j++)
1065             {
1066                 if (odp->u.func.arg_types[j] == 't') mask |= 1<< (j*2);
1067                 if (odp->u.func.arg_types[j] == 'W') mask |= 2<< (j*2);
1068             }
1069         fprintf( outfile, "    %d", mask );
1070         if (i < Limit) fprintf( outfile, ",\n" );
1071     }
1072     fprintf( outfile, "\n};\n\n" );
1073
1074     /* Output the DLL ordinals table */
1075
1076     fprintf( outfile, "static const unsigned short FuncOrdinals[] =\n{\n" );
1077     nb_names = 0;
1078     for (i = Base, odp = OrdinalDefinitions + Base; i <= Limit; i++, odp++)
1079     {
1080         if (odp->type == TYPE_INVALID) continue;
1081         if (nb_names++) fprintf( outfile, ",\n" );
1082         fprintf( outfile, "    %d", i - Base );
1083     }
1084     fprintf( outfile, "\n};\n\n" );
1085
1086     /* Output the DLL functions arguments */
1087
1088     fprintf( outfile, "static const unsigned char FuncArgs[%d] =\n{\n",
1089              Limit - Base + 1 );
1090     for (i = Base, odp = OrdinalDefinitions + Base; i <= Limit; i++, odp++)
1091     {
1092         unsigned char args;
1093         switch(odp->type)
1094         {
1095         case TYPE_STDCALL:
1096             args = (unsigned char)strlen(odp->u.func.arg_types);
1097             break;
1098         case TYPE_CDECL:
1099             args = 0x80 | (unsigned char)strlen(odp->u.func.arg_types);
1100             break;
1101         case TYPE_REGISTER:
1102             args = 0xfe;
1103             nb_reg_funcs++;
1104             break;
1105         default:
1106             args = 0xff;
1107             break;
1108         }
1109         fprintf( outfile, "    0x%02x", args );
1110         if (i < Limit) fprintf( outfile, ",\n" );
1111     }
1112     fprintf( outfile, "\n};\n\n" );
1113
1114     /* Output the DLL descriptor */
1115
1116     fprintf( outfile, "const BUILTIN32_DESCRIPTOR %s_Descriptor =\n{\n",
1117              DLLName );
1118     fprintf( outfile, "    \"%s\",\n", DLLName );
1119     fprintf( outfile, "    %d,\n", Base );
1120     fprintf( outfile, "    %d,\n", Limit - Base + 1 );
1121     fprintf( outfile, "    %d,\n", nb_names );
1122     fprintf( outfile, "    %d,\n", nb_reg_funcs );
1123     fprintf( outfile,
1124              "    Functions,\n"
1125              "    FuncNames,\n"
1126              "    FuncOrdinals,\n"
1127              "    FuncArgs,\n"
1128              "    ArgTypes\n"
1129              "};\n" );
1130     return 0;
1131 }
1132
1133
1134 /*******************************************************************
1135  *         BuildSpec16File
1136  *
1137  * Build a Win16 assembly file from a spec file.
1138  */
1139 static int BuildSpec16File( char * specfile, FILE *outfile )
1140 {
1141     ORDDEF *odp;
1142     int i;
1143     int code_offset, data_offset, module_size;
1144     unsigned char *data;
1145
1146     data = (unsigned char *)xmalloc( 0x10000 );
1147     memset( data, 0, 16 );
1148     data_offset = 16;
1149
1150     fprintf( outfile, "/* File generated automatically; do not edit! */\n" );
1151     fprintf( outfile, "\t.text\n" );
1152     fprintf( outfile, "Code_Start:\n" );
1153     code_offset = 0;
1154
1155     odp = OrdinalDefinitions;
1156     for (i = 0; i <= Limit; i++, odp++)
1157     {
1158         switch (odp->type)
1159         {
1160           case TYPE_INVALID:
1161             odp->offset = 0xffff;
1162             break;
1163
1164           case TYPE_ABS:
1165             odp->offset = LOWORD(odp->u.abs.value);
1166             break;
1167
1168           case TYPE_BYTE:
1169             odp->offset = data_offset;
1170             data_offset += StoreVariableCode( data + data_offset, 1, odp);
1171             break;
1172
1173           case TYPE_WORD:
1174             odp->offset = data_offset;
1175             data_offset += StoreVariableCode( data + data_offset, 2, odp);
1176             break;
1177
1178           case TYPE_LONG:
1179             odp->offset = data_offset;
1180             data_offset += StoreVariableCode( data + data_offset, 4, odp);
1181             break;
1182
1183           case TYPE_RETURN:
1184             fprintf( outfile,"/* %s.%d */\n", DLLName, i);
1185             fprintf( outfile,"\tmovw $%d,%%ax\n",LOWORD(odp->u.ret.ret_value));
1186             fprintf( outfile,"\tmovw $%d,%%dx\n",HIWORD(odp->u.ret.ret_value));
1187             fprintf( outfile,"\t.byte 0x66\n");
1188             if (odp->u.ret.arg_size != 0)
1189                 fprintf( outfile, "\tlret $%d\n\n", odp->u.ret.arg_size);
1190             else
1191             {
1192                 fprintf( outfile, "\tlret\n");
1193                 fprintf( outfile, "\tnop\n");
1194                 fprintf( outfile, "\tnop\n\n");
1195             }
1196             odp->offset = code_offset;
1197             code_offset += 12;  /* Assembly code is 12 bytes long */
1198             break;
1199
1200           case TYPE_REGISTER:
1201           case TYPE_PASCAL:
1202           case TYPE_PASCAL_16:
1203           case TYPE_STUB:
1204             fprintf( outfile, "/* %s.%d */\n", DLLName, i);
1205             fprintf( outfile, "\tpushw %%bp\n" );
1206             fprintf( outfile, "\tpushl $" PREFIX "%s\n",odp->u.func.link_name);
1207             /* FreeBSD does not understand lcall, so do it the hard way */
1208             fprintf( outfile, "\t.byte 0x9a\n" );
1209             fprintf( outfile, "\t.long " PREFIX "CallFrom16_%s_%s\n",
1210                      (odp->type == TYPE_REGISTER) ? "regs" :
1211                      (odp->type == TYPE_PASCAL) ? "long" : "word",
1212                      odp->u.func.arg_types );
1213             fprintf( outfile, "\t.long 0x%08lx\n",
1214                      MAKELONG( Code_Selector, 0x9090 /* nop ; nop */ ) );
1215             odp->offset = code_offset;
1216             code_offset += 16;  /* Assembly code is 16 bytes long */
1217             break;
1218                 
1219           default:
1220             fprintf(stderr,"build: function type %d not available for Win16\n",
1221                     odp->type);
1222             return -1;
1223         }
1224     }
1225
1226     if (!code_offset)  /* Make sure the code segment is not empty */
1227     {
1228         fprintf( outfile, "\t.byte 0\n" );
1229         code_offset++;
1230     }
1231
1232     /* Output data segment */
1233
1234     DumpBytes( outfile, data, data_offset, NULL, "Data_Start" );
1235
1236     /* Build the module */
1237
1238     module_size = BuildModule16( outfile, code_offset, data_offset );
1239
1240     /* Output the DLL descriptor */
1241
1242     fprintf( outfile, "\t.text\n" );
1243     fprintf( outfile, "DLLName:\t.string \"%s\\0\"\n", DLLName );
1244     fprintf( outfile, "\t.align 4\n" );
1245     fprintf( outfile, "\t.globl " PREFIX "%s_Descriptor\n", DLLName );
1246     fprintf( outfile, PREFIX "%s_Descriptor:\n", DLLName );
1247     fprintf( outfile, "\t.long DLLName\n" );          /* Name */
1248     fprintf( outfile, "\t.long Module_Start\n" );     /* Module start */
1249     fprintf( outfile, "\t.long %d\n", module_size );  /* Module size */
1250     fprintf( outfile, "\t.long Code_Start\n" );       /* Code start */
1251     fprintf( outfile, "\t.long Data_Start\n" );       /* Data start */
1252     return 0;
1253 }
1254
1255
1256 /*******************************************************************
1257  *         BuildSpecFile
1258  *
1259  * Build an assembly file from a spec file.
1260  */
1261 static int BuildSpecFile( FILE *outfile, char *specname )
1262 {
1263     SpecName = specname;
1264     SpecFp = fopen( specname, "r");
1265     if (SpecFp == NULL)
1266     {
1267         fprintf(stderr, "Could not open specification file, '%s'\n", specname);
1268         return -1;
1269     }
1270
1271     if (ParseTopLevel() < 0) return -1;
1272
1273     switch(SpecType)
1274     {
1275     case SPEC_WIN16:
1276         return BuildSpec16File( specname, outfile );
1277     case SPEC_WIN32:
1278         return BuildSpec32File( specname, outfile );
1279     default:
1280         fprintf( stderr, "%s: Missing 'type' declaration\n", specname );
1281         return -1;
1282     }
1283 }
1284
1285
1286 /*******************************************************************
1287  *         TransferArgs16To32
1288  *
1289  * Get the arguments from the 16-bit stack and push them on the 32-bit stack.
1290  * The 16-bit stack layout is:
1291  *   ...     ...
1292  *  (bp+8)    arg2
1293  *  (bp+6)    arg1
1294  *  (bp+4)    cs
1295  *  (bp+2)    ip
1296  *  (bp)      bp
1297  */
1298 static int TransferArgs16To32( FILE *outfile, char *args )
1299 {
1300     int i, pos16, pos32;
1301
1302     /* Save ebx first */
1303
1304     fprintf( outfile, "\tpushl %%ebx\n" );
1305
1306     /* Get the 32-bit stack pointer */
1307
1308     fprintf( outfile, "\tmovl " PREFIX "CALLTO16_Saved32_esp,%%ebx\n" );
1309
1310     /* Copy the arguments */
1311
1312     pos16 = 6;  /* skip bp and return address */
1313     pos32 = 0;
1314
1315     for (i = strlen(args); i > 0; i--)
1316     {
1317         pos32 -= 4;
1318         switch(args[i-1])
1319         {
1320         case 'w':  /* word */
1321             fprintf( outfile, "\tmovzwl %d(%%ebp),%%eax\n", pos16 );
1322             fprintf( outfile, "\tmovl %%eax,%d(%%ebx)\n", pos32 );
1323             pos16 += 2;
1324             break;
1325
1326         case 's':  /* s_word */
1327             fprintf( outfile, "\tmovswl %d(%%ebp),%%eax\n", pos16 );
1328             fprintf( outfile, "\tmovl %%eax,%d(%%ebx)\n", pos32 );
1329             pos16 += 2;
1330             break;
1331
1332         case 'l':  /* long or segmented pointer */
1333         case 'T':  /* segmented pointer to null-terminated string */
1334             fprintf( outfile, "\tmovl %d(%%ebp),%%eax\n", pos16 );
1335             fprintf( outfile, "\tmovl %%eax,%d(%%ebx)\n", pos32 );
1336             pos16 += 4;
1337             break;
1338
1339         case 'p':  /* linear pointer */
1340         case 't':  /* linear pointer to null-terminated string */
1341             /* Get the selector */
1342             fprintf( outfile, "\tmovw %d(%%ebp),%%ax\n", pos16 + 2 );
1343             /* Get the selector base */
1344             fprintf( outfile, "\tandl $0xfff8,%%eax\n" );
1345             fprintf( outfile, "\tmovl " PREFIX "ldt_copy(%%eax),%%eax\n" );
1346             fprintf( outfile, "\tmovl %%eax,%d(%%ebx)\n", pos32 );
1347             /* Add the offset */
1348             fprintf( outfile, "\tmovzwl %d(%%ebp),%%eax\n", pos16 );
1349             fprintf( outfile, "\taddl %%eax,%d(%%ebx)\n", pos32 );
1350             pos16 += 4;
1351             break;
1352
1353         default:
1354             fprintf( stderr, "Unknown arg type '%c'\n", args[i-1] );
1355         }
1356     }
1357
1358     /* Restore ebx */
1359     
1360     fprintf( outfile, "\tpopl %%ebx\n" );
1361
1362     return pos16 - 6;  /* Return the size of the 16-bit args */
1363 }
1364
1365
1366 /*******************************************************************
1367  *         BuildContext16
1368  *
1369  * Build the context structure on the 32-bit stack.
1370  */
1371 static void BuildContext16( FILE *outfile )
1372 {
1373     /* Save ebx first */
1374
1375     fprintf( outfile, "\tpushl %%ebx\n" );
1376
1377     /* Get the 32-bit stack pointer */
1378
1379     fprintf( outfile, "\tmovl " PREFIX "CALLTO16_Saved32_esp,%%ebx\n" );
1380
1381     /* Store the registers */
1382
1383     fprintf( outfile, "\tpopl %d(%%ebx)\n", /* Get ebx from stack*/
1384              CONTEXTOFFSET(Ebx) - sizeof(CONTEXT) );
1385     fprintf( outfile, "\tmovl %%eax,%d(%%ebx)\n",
1386              CONTEXTOFFSET(Eax) - sizeof(CONTEXT) );
1387     fprintf( outfile, "\tmovl %%ecx,%d(%%ebx)\n",
1388              CONTEXTOFFSET(Ecx) - sizeof(CONTEXT) );
1389     fprintf( outfile, "\tmovl %%edx,%d(%%ebx)\n",
1390              CONTEXTOFFSET(Edx) - sizeof(CONTEXT) );
1391     fprintf( outfile, "\tmovl %%esi,%d(%%ebx)\n",
1392              CONTEXTOFFSET(Esi) - sizeof(CONTEXT) );
1393     fprintf( outfile, "\tmovl %%edi,%d(%%ebx)\n",
1394              CONTEXTOFFSET(Edi) - sizeof(CONTEXT) );
1395
1396     fprintf( outfile, "\tmovzwl -10(%%ebp),%%eax\n" ); /* Get %ds from stack*/
1397     fprintf( outfile, "\tmovl %%eax,%d(%%ebx)\n",
1398              CONTEXTOFFSET(SegDs) - sizeof(CONTEXT) );
1399     fprintf( outfile, "\tmovzwl -6(%%ebp),%%eax\n" ); /* Get %es from stack*/
1400     fprintf( outfile, "\tmovl %%eax,%d(%%ebx)\n",
1401              CONTEXTOFFSET(SegEs) - sizeof(CONTEXT) );
1402     fprintf( outfile, "\tpushfl\n" );
1403     fprintf( outfile, "\tpopl %d(%%ebx)\n",
1404              CONTEXTOFFSET(EFlags) - sizeof(CONTEXT) );
1405     fprintf( outfile, "\tmovl -16(%%ebp),%%eax\n" ); /* Get %ebp from stack */
1406     fprintf( outfile, "\tmovl %%eax,%d(%%ebx)\n",
1407              CONTEXTOFFSET(Ebp) - sizeof(CONTEXT) );
1408     fprintf( outfile, "\tmovzwl 2(%%ebp),%%eax\n" ); /* Get %ip from stack */
1409     fprintf( outfile, "\tmovl %%eax,%d(%%ebx)\n",
1410              CONTEXTOFFSET(Eip) - sizeof(CONTEXT) );
1411     fprintf( outfile, "\tmovzwl 4(%%ebp),%%eax\n" ); /* Get %cs from stack */
1412     fprintf( outfile, "\tmovl %%eax,%d(%%ebx)\n",
1413              CONTEXTOFFSET(SegCs) - sizeof(CONTEXT) );
1414     fprintf( outfile, "\tmovw %%fs,%%ax\n" );
1415     fprintf( outfile, "\tmovl %%eax,%d(%%ebx)\n",
1416              CONTEXTOFFSET(SegFs) - sizeof(CONTEXT) );
1417     fprintf( outfile, "\tmovw %%gs,%%ax\n" );
1418     fprintf( outfile, "\tmovl %%eax,%d(%%ebx)\n",
1419              CONTEXTOFFSET(SegGs) - sizeof(CONTEXT) );
1420     fprintf( outfile, "\tmovw %%ss,%%ax\n" );
1421     fprintf( outfile, "\tmovl %%eax,%d(%%ebx)\n",
1422              CONTEXTOFFSET(SegSs) - sizeof(CONTEXT) );
1423 #if 0
1424     fprintf( outfile, "\tfsave %d(%%ebx)\n",
1425              CONTEXTOFFSET(FloatSave) - sizeof(CONTEXT) );
1426 #endif
1427 }
1428
1429
1430 /*******************************************************************
1431  *         RestoreContext16
1432  *
1433  * Restore the registers from the context structure.
1434  * %edx must point to the 32-bit stack top.
1435  */
1436 static void RestoreContext16( FILE *outfile )
1437 {
1438     /* Get the 32-bit stack pointer */
1439
1440     fprintf( outfile, "\tmovl %%edx,%%ebx\n" );
1441
1442     /* Remove everything up to the return address from the 16-bit stack */
1443
1444     fprintf( outfile, "\taddl $22,%%esp\n" );
1445
1446     /* Restore the registers */
1447
1448     fprintf( outfile, "\tmovl %d(%%ebx),%%ecx\n",
1449              CONTEXTOFFSET(Ecx) - sizeof(CONTEXT) );
1450     fprintf( outfile, "\tmovl %d(%%ebx),%%edx\n",
1451              CONTEXTOFFSET(Edx) - sizeof(CONTEXT) );
1452     fprintf( outfile, "\tmovl %d(%%ebx),%%esi\n",
1453              CONTEXTOFFSET(Esi) - sizeof(CONTEXT) );
1454     fprintf( outfile, "\tmovl %d(%%ebx),%%edi\n",
1455              CONTEXTOFFSET(Edi) - sizeof(CONTEXT) );
1456     fprintf( outfile, "\tmovl %d(%%ebx),%%ebp\n",
1457              CONTEXTOFFSET(Ebp) - sizeof(CONTEXT) );
1458     fprintf( outfile, "\tpushw %d(%%ebx)\n",  /* Push new cs */
1459              CONTEXTOFFSET(SegCs) - sizeof(CONTEXT) );
1460     fprintf( outfile, "\tpushw %d(%%ebx)\n",  /* Push new ip */
1461              CONTEXTOFFSET(Eip) - sizeof(CONTEXT) );
1462     fprintf( outfile, "\tpushl %d(%%ebx)\n",  /* Push new ds */
1463              CONTEXTOFFSET(SegDs) - sizeof(CONTEXT) );
1464     fprintf( outfile, "\tpushl %d(%%ebx)\n",  /* Push new es */
1465              CONTEXTOFFSET(SegEs) - sizeof(CONTEXT) );
1466     fprintf( outfile, "\tpushl %d(%%ebx)\n",
1467              CONTEXTOFFSET(EFlags) - sizeof(CONTEXT) );
1468     fprintf( outfile, "\tpopfl\n" );
1469     fprintf( outfile, "\tmovl %d(%%ebx),%%eax\n",
1470              CONTEXTOFFSET(Eax) - sizeof(CONTEXT) );
1471     fprintf( outfile, "\tmovl %d(%%ebx),%%ebx\n",
1472              CONTEXTOFFSET(Ebx) - sizeof(CONTEXT) );
1473     fprintf( outfile, "\tpopl %%es\n" );  /* Set es */
1474     fprintf( outfile, "\tpopl %%ds\n" );  /* Set ds */
1475 }
1476
1477
1478 /*******************************************************************
1479  *         BuildCallFrom16Func
1480  *
1481  * Build a 16-bit-to-Wine callback function. The syntax of the function
1482  * profile is: type_xxxxx, where 'type' is one of 'regs', 'word' or
1483  * 'long' and each 'x' is an argument ('w'=word, 's'=signed word,
1484  * 'l'=long, 'p'=linear pointer, 't'=linear pointer to null-terminated string,
1485  * 'T'=segmented pointer to null-terminated string).
1486  * For register functions, the arguments are ignored, but they are still
1487  * removed from the stack upon return.
1488  *
1489  * Stack layout upon entry to the callback function:
1490  *  ...           ...
1491  * (sp+18) word   first 16-bit arg
1492  * (sp+16) word   cs
1493  * (sp+14) word   ip
1494  * (sp+12) word   bp
1495  * (sp+8)  long   32-bit entry point (used to store edx)
1496  * (sp+6)  word   high word of cs (always 0, used to store es)
1497  * (sp+4)  word   low word of cs of 16-bit entry point
1498  * (sp+2)  word   high word of ip (always 0, used to store ds)
1499  * (sp)    word   low word of ip of 16-bit entry point
1500  *
1501  * Added on the stack:
1502  * (sp-4)  long   ebp
1503  * (sp-6)  word   saved previous sp
1504  * (sp-8)  word   saved previous ss
1505  */
1506 static void BuildCallFrom16Func( FILE *outfile, char *profile )
1507 {
1508     int argsize = 0;
1509     int short_ret = 0;
1510     int reg_func = 0;
1511     char *args = profile + 5;
1512
1513     /* Parse function type */
1514
1515     if (!strncmp( "word_", profile, 5 )) short_ret = 1;
1516     else if (!strncmp( "regs_", profile, 5 )) reg_func = 1;
1517     else if (strncmp( "long_", profile, 5 ))
1518     {
1519         fprintf( stderr, "Invalid function name '%s', ignored\n", profile );
1520         return;
1521     }
1522
1523     /* Function header */
1524
1525     fprintf( outfile, "\n\t.align 4\n" );
1526 #ifdef USE_STABS
1527     fprintf( outfile, ".stabs \"CallFrom16_%s:F1\",36,0,0," PREFIX "CallFrom16_%s\n", 
1528              profile, profile);
1529 #endif
1530     fprintf( outfile, "\t.globl " PREFIX "CallFrom16_%s\n", profile );
1531     fprintf( outfile, PREFIX "CallFrom16_%s:\n", profile );
1532
1533     /* Setup bp to point to its copy on the stack */
1534
1535     fprintf( outfile, "\tpushl %%ebp\n" );  /* Save the full 32-bit ebp */
1536     fprintf( outfile, "\tmovzwl %%sp,%%ebp\n" );
1537     fprintf( outfile, "\taddw $16,%%bp\n" );
1538
1539     /* Save 16-bit ds and es */
1540
1541     /* Stupid FreeBSD assembler doesn't know these either */
1542     /* fprintf( outfile, "\tmovw %%ds,-10(%%ebp)\n" ); */
1543     fprintf( outfile, "\t.byte 0x66,0x8c,0x5d,0xf6\n" );
1544     /* fprintf( outfile, "\tmovw %%es,-6(%%ebp)\n" ); */
1545     fprintf( outfile, "\t.byte 0x66,0x8c,0x45,0xfa\n" );
1546
1547     /* Restore 32-bit ds and es */
1548
1549     fprintf( outfile, "\tpushl $0x%04x%04x\n", Data_Selector, Data_Selector );
1550     fprintf( outfile, "\t.byte 0x66\n\tpopl %%ds\n" );
1551     fprintf( outfile, "\t.byte 0x66\n\tpopl %%es\n" );
1552
1553
1554     /* Save the 16-bit stack */
1555
1556     fprintf( outfile, "\tpushl " PREFIX "IF1632_Saved16_ss_sp\n" );
1557 #ifdef __svr4__
1558     fprintf( outfile,"\tdata16\n");
1559 #endif
1560     fprintf( outfile, "\tmovw %%ss," PREFIX "IF1632_Saved16_ss_sp+2\n" );
1561     fprintf( outfile, "\tmovw %%sp," PREFIX "IF1632_Saved16_ss_sp\n" );
1562
1563     /* Transfer the arguments */
1564
1565     if (reg_func) BuildContext16( outfile );
1566     else if (*args) argsize = TransferArgs16To32( outfile, args );
1567
1568     /* Get the address of the API function */
1569
1570     fprintf( outfile, "\tmovl -4(%%ebp),%%eax\n" );
1571
1572     /* If necessary, save %edx over the API function address */
1573
1574     if (!reg_func && short_ret)
1575         fprintf( outfile, "\tmovl %%edx,-4(%%ebp)\n" );
1576
1577     /* Switch to the 32-bit stack */
1578
1579     fprintf( outfile, "\tmovl " PREFIX "CALLTO16_Saved32_esp,%%ebp\n" );
1580     fprintf( outfile, "\tpushl %%ds\n" );
1581     fprintf( outfile, "\tpopl %%ss\n" );
1582     fprintf( outfile, "\tleal -%d(%%ebp),%%esp\n",
1583              reg_func ? sizeof(CONTEXT) : 4 * strlen(args) );
1584     if (reg_func)  /* Push the address of the context struct */
1585         fprintf( outfile, "\tpushl %%esp\n" );
1586
1587     /* Setup %ebp to point to the previous stack frame (built by CallTo16) */
1588
1589     fprintf( outfile, "\taddl $%d,%%ebp\n", STRUCTOFFSET(STACK32FRAME,ebp) );
1590
1591     /* Print the debug information before the call */
1592
1593     if (debugging)
1594     {
1595         fprintf( outfile, "\tpushl %%eax\n" );
1596         fprintf( outfile, "\tpushl $Profile_%s\n", profile );
1597         fprintf( outfile, "\tpushl $%d\n", reg_func ? 2 : (short_ret ? 1 : 0));
1598         fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallFrom16\n" );
1599         fprintf( outfile, "\tpopl %%eax\n" );
1600         fprintf( outfile, "\tpopl %%eax\n" );
1601         fprintf( outfile, "\tpopl %%eax\n" );
1602     }
1603
1604     /* Call the entry point */
1605
1606     fprintf( outfile, "\tcall *%%eax\n" );
1607
1608     /* Print the debug information after the call */
1609
1610     if (debugging)
1611     {
1612         if (reg_func)
1613         {
1614             /* Push again the address of the context struct in case */
1615             /* it has been removed by an stdcall function */
1616             fprintf( outfile, "\tleal -%d(%%ebp),%%esp\n",
1617                      sizeof(CONTEXT) + STRUCTOFFSET(STACK32FRAME,ebp) );
1618             fprintf( outfile, "\tpushl %%esp\n" );
1619         }
1620         fprintf( outfile, "\tpushl %%eax\n" );
1621         fprintf( outfile, "\tpushl $%d\n", reg_func ? 2 : (short_ret ? 1 : 0));
1622         fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallFrom16Ret\n" );
1623         fprintf( outfile, "\tpopl %%eax\n" );
1624         fprintf( outfile, "\tpopl %%eax\n" );
1625     }
1626
1627     /* Restore the value of the saved 32-bit stack pointer */
1628
1629     fprintf( outfile, "\tleal -%d(%%ebp),%%edx\n",
1630              STRUCTOFFSET(STACK32FRAME,ebp) );
1631     fprintf( outfile, "movl %%edx," PREFIX "CALLTO16_Saved32_esp\n" );
1632
1633     /* Restore the 16-bit stack */
1634
1635 #ifdef __svr4__
1636     fprintf( outfile, "\tdata16\n");
1637 #endif
1638     fprintf( outfile, "\tmovw " PREFIX "IF1632_Saved16_ss_sp+2,%%ss\n" );
1639     fprintf( outfile, "\tmovw " PREFIX "IF1632_Saved16_ss_sp,%%sp\n" );
1640     fprintf( outfile, "\tpopl " PREFIX "IF1632_Saved16_ss_sp\n" );
1641
1642     if (reg_func)
1643     {
1644         /* Calc the arguments size */
1645         while (*args)
1646         {
1647             switch(*args)
1648             {
1649             case 'w':
1650             case 's':
1651                 argsize += 2;
1652                 break;
1653             case 'p':
1654             case 't':
1655             case 'l':
1656             case 'T':
1657                 argsize += 4;
1658                 break;
1659             default:
1660                 fprintf( stderr, "Unknown arg type '%c'\n", *args );
1661             }
1662             args++;
1663         }
1664
1665         /* Restore registers from the context structure */
1666         RestoreContext16( outfile );
1667     }
1668     else
1669     {
1670         /* Restore high 16 bits of ebp */
1671         fprintf( outfile, "\tpopl %%ebp\n" );
1672
1673         /* Restore ds and es */
1674         fprintf( outfile, "\tincl %%esp\n" );      /* Remove ip */
1675         fprintf( outfile, "\tincl %%esp\n" );
1676         fprintf( outfile, "\tpopl %%edx\n" );      /* Remove cs and ds */
1677         fprintf( outfile, "\tmovw %%dx,%%ds\n" );  /* and restore ds */
1678         fprintf( outfile, "\t.byte 0x66\n\tpopl %%es\n" );       /* Restore es */
1679
1680         if (short_ret) fprintf( outfile, "\tpopl %%edx\n" );  /* Restore edx */
1681         else
1682         {
1683             /* Get the return value into dx:ax */
1684             fprintf( outfile, "\tmovl %%eax,%%edx\n" );
1685             fprintf( outfile, "\tshrl $16,%%edx\n" );
1686             /* Remove API entry point */
1687             fprintf( outfile, "\taddl $4,%%esp\n" );
1688         }
1689
1690         /* Restore low 16 bits of ebp */
1691         fprintf( outfile, "\tpopw %%bp\n" );
1692     }
1693
1694     /* Remove the arguments and return */
1695
1696     if (argsize)
1697     {
1698         fprintf( outfile, "\t.byte 0x66\n" );
1699         fprintf( outfile, "\tlret $%d\n", argsize );
1700     }
1701     else
1702     {
1703         fprintf( outfile, "\t.byte 0x66\n" );
1704         fprintf( outfile, "\tlret\n" );
1705     }
1706 }
1707
1708
1709 /*******************************************************************
1710  *         BuildCallTo16Func
1711  *
1712  * Build a Wine-to-16-bit callback function.
1713  *
1714  * Stack frame of the callback function:
1715  *  ...      ...
1716  * (ebp+16) arg2
1717  * (ebp+12) arg1
1718  * (ebp+8)  func to call
1719  * (ebp+4)  return address
1720  * (ebp)    previous ebp
1721  *
1722  * Prototypes for the CallTo16 functions:
1723  *   extern WINAPI WORD CallTo16_word_xxx( FARPROC16 func, args... );
1724  *   extern WINAPI LONG CallTo16_long_xxx( FARPROC16 func, args... );
1725  *   extern WINAPI void CallTo16_sreg_( const CONTEXT *context );
1726  *   extern WINAPI void CallTo16_lreg_( const CONTEXT *context );
1727  */
1728 static void BuildCallTo16Func( FILE *outfile, char *profile )
1729 {
1730     int short_ret = 0;
1731     int reg_func = 0;
1732     char *args = profile + 5;
1733
1734     if (!strncmp( "word_", profile, 5 )) short_ret = 1;
1735     else if (!strncmp( "sreg_", profile, 5 )) reg_func = 1;
1736     else if (!strncmp( "lreg_", profile, 5 )) reg_func = 2;
1737     else if (strncmp( "long_", profile, 5 ))
1738     {
1739         fprintf( stderr, "Invalid function name '%s'.\n", profile );
1740         exit(1);
1741     }
1742
1743     /* Function header */
1744
1745     fprintf( outfile, "\n\t.align 4\n" );
1746 #ifdef USE_STABS
1747     fprintf( outfile, ".stabs \"CallTo16_%s:F1\",36,0,0," PREFIX "CallTo16_%s\n", 
1748              profile, profile);
1749 #endif
1750     fprintf( outfile, "\t.globl " PREFIX "CallTo16_%s\n", profile );
1751     fprintf( outfile, PREFIX "CallTo16_%s:\n", profile );
1752
1753     /* Entry code */
1754
1755     fprintf( outfile, "\tpushl %%ebp\n" );
1756     fprintf( outfile, "\tmovl %%esp,%%ebp\n" );
1757
1758     /* Call the actual CallTo16 routine (simulate a lcall) */
1759
1760     fprintf( outfile, "\tpushl %%cs\n" );
1761     fprintf( outfile, "\tcall do_callto16_%s\n", profile );
1762
1763     /* Exit code */
1764
1765     /* FIXME: this is a hack because of task.c */
1766     if (!strcmp( profile, "word_" ))
1767     {
1768         fprintf( outfile, ".globl " PREFIX "CALLTO16_Restore\n" );
1769         fprintf( outfile, PREFIX "CALLTO16_Restore:\n" );
1770     }
1771     fprintf( outfile, "\tpopl %%ebp\n" );
1772     fprintf( outfile, "\tret $%d\n", 4 * strlen(args) + 4 );
1773
1774     /* Start of the actual CallTo16 routine */
1775
1776     /* Save the 32-bit registers */
1777
1778     fprintf( outfile, "do_callto16_%s:\n", profile );
1779     fprintf( outfile, "\tpushl %%ebx\n" );
1780     fprintf( outfile, "\tpushl %%ecx\n" );
1781     fprintf( outfile, "\tpushl %%edx\n" );
1782     fprintf( outfile, "\tpushl %%esi\n" );
1783     fprintf( outfile, "\tpushl %%edi\n" );
1784
1785     /* Save the 32-bit stack */
1786
1787     fprintf( outfile, "\tmovl %%esp," PREFIX "CALLTO16_Saved32_esp\n" );
1788     fprintf( outfile, "\tmovl %%ebp,%%ebx\n" );
1789
1790     /* Print debugging info */
1791
1792     if (debugging)
1793     {
1794         /* Push the address of the first argument */
1795         fprintf( outfile, "\tleal 8(%%ebp),%%eax\n" );
1796         fprintf( outfile, "\tpushl $%d\n", reg_func ? -1 : strlen(args) );
1797         fprintf( outfile, "\tpushl %%eax\n" );
1798         fprintf( outfile, "\tcall " PREFIX "RELAY_DebugCallTo16\n" );
1799         fprintf( outfile, "\tpopl %%eax\n" );
1800         fprintf( outfile, "\tpopl %%eax\n" );
1801     }
1802
1803     if (reg_func)
1804     {
1805         /* Switch to the 16-bit stack, saving the current %%esp, */
1806         /* and adding the specified offset to the new sp */
1807         fprintf( outfile, "\tmovzwl " PREFIX "IF1632_Saved16_ss_sp,%%edx\n" );
1808         fprintf( outfile, "\tleal -4(%%edx),%%edx\n" );
1809         fprintf( outfile, "\tmovl 12(%%ebx),%%eax\n" ); /* Get the offset */
1810         fprintf( outfile, "\taddl %%edx,%%eax\n" );
1811 #ifdef __svr4__
1812         fprintf( outfile,"\tdata16\n");
1813 #endif
1814         fprintf( outfile, "\tmovw " PREFIX "IF1632_Saved16_ss_sp+2,%%ss\n" );
1815         fprintf( outfile, "\txchgl %%esp,%%eax\n" );
1816         fprintf( outfile, "\t.byte 0x36\n" /* %ss: */ );
1817         fprintf( outfile, "\tmovl %%eax,0(%%edx)\n" );
1818
1819         /* Get the registers. ebx is handled later on. */
1820
1821         fprintf( outfile, "\tmovl 8(%%ebx),%%ebx\n" );
1822         fprintf( outfile, "\tmovl %d(%%ebx),%%eax\n", CONTEXTOFFSET(SegEs) );
1823         fprintf( outfile, "\tmovw %%ax,%%es\n" );
1824         fprintf( outfile, "\tmovl %d(%%ebx),%%ebp\n", CONTEXTOFFSET(Ebp) );
1825         fprintf( outfile, "\tmovl %d(%%ebx),%%eax\n", CONTEXTOFFSET(Eax) );
1826         fprintf( outfile, "\tmovl %d(%%ebx),%%ecx\n", CONTEXTOFFSET(Ecx) );
1827         fprintf( outfile, "\tmovl %d(%%ebx),%%edx\n", CONTEXTOFFSET(Edx) );
1828         fprintf( outfile, "\tmovl %d(%%ebx),%%esi\n", CONTEXTOFFSET(Esi) );
1829         fprintf( outfile, "\tmovl %d(%%ebx),%%edi\n", CONTEXTOFFSET(Edi) );
1830
1831         /* Push the return address 
1832          * With sreg suffix, we push 16:16 address (normal lret)
1833          * With lreg suffix, we push 16:32 address (0x66 lret, for KERNEL32_45)
1834          */
1835         if (reg_func == 1)
1836             fprintf( outfile, "\tpushl " PREFIX "CALLTO16_RetAddr_regs\n" );
1837         else 
1838         {
1839             fprintf( outfile, "\tpushw $0\n" );
1840             fprintf( outfile, "\tpushw " PREFIX "CALLTO16_RetAddr_regs+2\n" );
1841             fprintf( outfile, "\tpushw $0\n" );
1842             fprintf( outfile, "\tpushw " PREFIX "CALLTO16_RetAddr_regs\n" );
1843         }
1844
1845         /* Push the called routine address */
1846
1847         fprintf( outfile, "\tpushw %d(%%ebx)\n", CONTEXTOFFSET(SegCs) );
1848         fprintf( outfile, "\tpushw %d(%%ebx)\n", CONTEXTOFFSET(Eip) );
1849
1850         /* Get the 16-bit ds */
1851
1852         fprintf( outfile, "\tpushl %d(%%ebx)\n", CONTEXTOFFSET(SegDs) );
1853         /* Get ebx from the 32-bit stack */
1854         fprintf( outfile, "\tmovl %d(%%ebx),%%ebx\n", CONTEXTOFFSET(Ebx) );
1855         fprintf( outfile, "\tpopl %%ds\n" );
1856     }
1857     else  /* not a register function */
1858     {
1859         int pos = 12;  /* first argument position */
1860
1861         /* Switch to the 16-bit stack, saving the current %%esp */
1862         fprintf( outfile, "\tmovl %%esp,%%eax\n" );
1863 #ifdef __svr4__
1864         fprintf( outfile,"\tdata16\n");
1865 #endif
1866         fprintf( outfile, "\tmovw " PREFIX "IF1632_Saved16_ss_sp+2,%%ss\n" );
1867         fprintf( outfile, "\tmovw " PREFIX "IF1632_Saved16_ss_sp,%%sp\n" );
1868         fprintf( outfile, "\tpushl %%eax\n" );
1869
1870         /* Make %bp point to the previous stackframe (built by CallFrom16) */
1871         fprintf( outfile, "\tmovzwl %%sp,%%ebp\n" );
1872         fprintf( outfile, "\tleal %d(%%ebp),%%ebp\n",
1873                  STRUCTOFFSET(STACK16FRAME,bp) + 4 /* for saved %%esp */ );
1874
1875         /* Transfer the arguments */
1876
1877         while (*args)
1878         {
1879             switch(*args++)
1880             {
1881             case 'w': /* word */
1882                 fprintf( outfile, "\tpushw %d(%%ebx)\n", pos );
1883                 break;
1884             case 'l': /* long */
1885                 fprintf( outfile, "\tpushl %d(%%ebx)\n", pos );
1886                 break;
1887             default:
1888                 fprintf( stderr, "Unexpected case '%c' in BuildCallTo16Func\n",
1889                         args[-1] );
1890             }
1891             pos += 4;
1892         }
1893
1894         /* Push the return address */
1895
1896         fprintf( outfile, "\tpushl " PREFIX "CALLTO16_RetAddr_%s\n",
1897                  short_ret ? "word" : "long" );
1898
1899         /* Push the called routine address */
1900
1901         fprintf( outfile, "\tpushl 8(%%ebx)\n" );
1902
1903         /* Set %ds and %es (and %ax just in case) equal to %ss */
1904
1905         fprintf( outfile, "\tmovw %%ss,%%ax\n" );
1906         fprintf( outfile, "\tmovw %%ax,%%ds\n" );
1907         fprintf( outfile, "\tmovw %%ax,%%es\n" );
1908     }
1909
1910     /* Jump to the called routine */
1911
1912     fprintf( outfile, "\t.byte 0x66\n" );
1913     fprintf( outfile, "\tlret\n" );
1914 }
1915
1916
1917 /*******************************************************************
1918  *         BuildRet16Func
1919  *
1920  * Build the return code for 16-bit callbacks
1921  */
1922 static void BuildRet16Func( FILE *outfile )
1923 {
1924     fprintf( outfile, "\t.globl " PREFIX "CALLTO16_Ret_word\n" );
1925     fprintf( outfile, "\t.globl " PREFIX "CALLTO16_Ret_long\n" );
1926     fprintf( outfile, "\t.globl " PREFIX "CALLTO16_Ret_regs\n" );
1927
1928     fprintf( outfile, PREFIX "CALLTO16_Ret_word:\n" );
1929     fprintf( outfile, "\txorl %%edx,%%edx\n" );
1930
1931     /* Remove the arguments just in case */
1932
1933     fprintf( outfile, PREFIX "CALLTO16_Ret_long:\n" );
1934     fprintf( outfile, "\tleal -%d(%%ebp),%%esp\n",
1935                  STRUCTOFFSET(STACK16FRAME,bp) + 4 /* for saved %%esp */ );
1936
1937     /* Put return value into %eax */
1938
1939     fprintf( outfile, PREFIX "CALLTO16_Ret_regs:\n" );
1940     fprintf( outfile, "\tshll $16,%%edx\n" );
1941     fprintf( outfile, "\tmovw %%ax,%%dx\n" );
1942     fprintf( outfile, "\tmovl %%edx,%%eax\n" );
1943
1944     /* Restore 32-bit segment registers */
1945
1946     fprintf( outfile, "\tpopl %%ecx\n" );  /* Get the saved %%esp */
1947     fprintf( outfile, "\tmovw $0x%04x,%%bx\n", Data_Selector );
1948 #ifdef __svr4__
1949     fprintf( outfile, "\tdata16\n");
1950 #endif
1951     fprintf( outfile, "\tmovw %%bx,%%ds\n" );
1952 #ifdef __svr4__
1953     fprintf( outfile, "\tdata16\n");
1954 #endif
1955     fprintf( outfile, "\tmovw %%bx,%%es\n" );
1956
1957     /* Restore the 32-bit stack */
1958
1959 #ifdef __svr4__
1960     fprintf( outfile, "\tdata16\n");
1961 #endif
1962     fprintf( outfile, "\tmovw %%bx,%%ss\n" );
1963     fprintf( outfile, "\tmovl %%ecx,%%esp\n" );
1964
1965     /* Restore the 32-bit registers */
1966
1967     fprintf( outfile, "\tpopl %%edi\n" );
1968     fprintf( outfile, "\tpopl %%esi\n" );
1969     fprintf( outfile, "\tpopl %%edx\n" );
1970     fprintf( outfile, "\tpopl %%ecx\n" );
1971     fprintf( outfile, "\tpopl %%ebx\n" );
1972
1973     /* Return to caller */
1974
1975     fprintf( outfile, "\tlret\n" );
1976
1977     /* Declare the return address variables */
1978
1979     fprintf( outfile, "\t.data\n" );
1980     fprintf( outfile, "\t.globl " PREFIX "CALLTO16_RetAddr_word\n" );
1981     fprintf( outfile, "\t.globl " PREFIX "CALLTO16_RetAddr_long\n" );
1982     fprintf( outfile, "\t.globl " PREFIX "CALLTO16_RetAddr_regs\n" );
1983     fprintf( outfile, "\t.globl " PREFIX "CALLTO16_Saved32_esp\n" );
1984     fprintf( outfile, PREFIX "CALLTO16_RetAddr_word:\t.long 0\n" );
1985     fprintf( outfile, PREFIX "CALLTO16_RetAddr_long:\t.long 0\n" );
1986     fprintf( outfile, PREFIX "CALLTO16_RetAddr_regs:\t.long 0\n" );
1987     fprintf( outfile, PREFIX "CALLTO16_Saved32_esp:\t.long 0\n" );
1988     fprintf( outfile, "\t.text\n" );
1989 }
1990
1991
1992 /*******************************************************************
1993  *         BuildCallTo32LargeStack
1994  *
1995  * Build the function used to switch to the original 32-bit stack
1996  * before calling a 32-bit function from 32-bit code. This is used for
1997  * functions that need a large stack, like X bitmaps functions.
1998  *
1999  * The generated function has the following prototype:
2000  *   int xxx( int (*func)(), void *arg );
2001  *
2002  * The pointer to the function can be retrieved by calling CALL32_Init,
2003  * which also takes care of saving the current 32-bit stack pointer.
2004  *
2005  * Stack layout:
2006  *   ...     ...
2007  * (ebp+12)  arg
2008  * (ebp+8)   func
2009  * (ebp+4)   ret addr
2010  * (ebp)     ebp
2011  */
2012 static void BuildCallTo32LargeStack( FILE *outfile )
2013 {
2014     /* Initialization function */
2015
2016     fprintf( outfile, "\n\t.align 4\n" );
2017 #ifdef USE_STABS
2018     fprintf( outfile, ".stabs \"CALL32_Init:F1\",36,0,0," PREFIX "CALL32_Init\n");
2019 #endif
2020     fprintf( outfile, "\t.globl " PREFIX "CALL32_Init\n" );
2021     fprintf( outfile, "\t.type " PREFIX "CALL32_Init,@function\n" );
2022     fprintf( outfile, PREFIX "CALL32_Init:\n" );
2023     fprintf( outfile, "\tleal -256(%%esp),%%eax\n" );
2024     fprintf( outfile, "\tmovl %%eax,CALL32_Original32_esp\n" );
2025     fprintf( outfile, "\tmovl $CALL32_LargeStack,%%eax\n" );
2026     fprintf( outfile, "\tret\n" );
2027
2028     /* Function header */
2029
2030     fprintf( outfile, "\n\t.align 4\n" );
2031 #ifdef USE_STABS
2032     fprintf( outfile, ".stabs \"CALL32_LargeStack:F1\",36,0,0,CALL32_LargeStack\n");
2033 #endif
2034     fprintf( outfile, "CALL32_LargeStack:\n" );
2035     
2036     /* Entry code */
2037
2038     fprintf( outfile, "\tpushl %%ebp\n" );
2039     fprintf( outfile, "\tmovl %%esp,%%ebp\n" );
2040
2041     /* Switch to the original 32-bit stack pointer */
2042
2043     fprintf( outfile, "\tmovl CALL32_Original32_esp, %%esp\n" );
2044
2045     /* Transfer the argument and call the function */
2046
2047     fprintf( outfile, "\tpushl 12(%%ebp)\n" );
2048     fprintf( outfile, "\tcall *8(%%ebp)\n" );
2049
2050     /* Restore registers and return */
2051
2052     fprintf( outfile, "\tmovl %%ebp,%%esp\n" );
2053     fprintf( outfile, "\tpopl %%ebp\n" );
2054     fprintf( outfile, "\tret\n" );
2055
2056     /* Data */
2057
2058     fprintf( outfile, "\t.data\n" );
2059     fprintf( outfile, "CALL32_Original32_esp:\t.long 0\n" );
2060     fprintf( outfile, "\t.text\n" );
2061 }
2062
2063
2064 /*******************************************************************
2065  *         BuildCallFrom32Regs
2066  *
2067  * Build a 32-bit-to-Wine call-back function for a 'register' function.
2068  * 'args' is the number of dword arguments.
2069  *
2070  * Stack layout:
2071  *   ...     ...
2072  * (esp+208) ret addr (or relay addr when debugging_relay is on)
2073  * (esp+204) entry point
2074  * (esp+0)   CONTEXT struct
2075  */
2076 static void BuildCallFrom32Regs( FILE *outfile )
2077 {
2078     /* Function header */
2079
2080     fprintf( outfile, "\n\t.align 4\n" );
2081 #ifdef USE_STABS
2082     fprintf( outfile, ".stabs \"CALL32_Regs:F1\",36,0,0," PREFIX "CALL32_Regs\n" );
2083 #endif
2084     fprintf( outfile, "\t.globl " PREFIX "CALL32_Regs\n" );
2085     fprintf( outfile, PREFIX "CALL32_Regs:\n" );
2086
2087     /* Build the context structure */
2088
2089     fprintf( outfile, "\tpushw $0\n" );
2090     fprintf( outfile, "\t.byte 0x66\n\tpushl %%ss\n" );
2091     fprintf( outfile, "\tpushl %%eax\n" );  /* %esp place holder */
2092     fprintf( outfile, "\tpushfl\n" );
2093     fprintf( outfile, "\tpushw $0\n" );
2094     fprintf( outfile, "\t.byte 0x66\n\tpushl %%cs\n" );
2095     fprintf( outfile, "\tpushl 20(%%esp)\n" );  /* %eip at time of call */
2096     fprintf( outfile, "\tpushl %%ebp\n" );
2097
2098     fprintf( outfile, "\tpushl %%eax\n" );
2099     fprintf( outfile, "\tpushl %%ecx\n" );
2100     fprintf( outfile, "\tpushl %%edx\n" );
2101     fprintf( outfile, "\tpushl %%ebx\n" );
2102     fprintf( outfile, "\tpushl %%esi\n" );
2103     fprintf( outfile, "\tpushl %%edi\n" );
2104
2105     fprintf( outfile, "\txorl %%eax,%%eax\n" );
2106     fprintf( outfile, "\tmovw %%ds,%%ax\n" );
2107     fprintf( outfile, "\tpushl %%eax\n" );
2108     fprintf( outfile, "\tmovw %%es,%%ax\n" );
2109     fprintf( outfile, "\tpushl %%eax\n" );
2110     fprintf( outfile, "\tmovw %%fs,%%ax\n" );
2111     fprintf( outfile, "\tpushl %%eax\n" );
2112     fprintf( outfile, "\tmovw %%gs,%%ax\n" );
2113     fprintf( outfile, "\tpushl %%eax\n" );
2114
2115     fprintf( outfile, "\tleal -%d(%%esp),%%esp\n",
2116              sizeof(FLOATING_SAVE_AREA) + 6 * sizeof(DWORD) /* DR regs */ );
2117     fprintf( outfile, "\tpushl $0x0001001f\n" );  /* ContextFlags */
2118
2119     fprintf( outfile, "\tfsave %d(%%esp)\n", CONTEXTOFFSET(FloatSave) );
2120
2121     fprintf( outfile, "\tleal %d(%%esp),%%eax\n",
2122              sizeof(CONTEXT) + 4 ); /* %esp at time of call */
2123     fprintf( outfile, "\tmovl %%eax,%d(%%esp)\n", CONTEXTOFFSET(Esp) );
2124
2125     fprintf( outfile, "\tcall " PREFIX "RELAY_CallFrom32Regs\n" );
2126
2127     /* Restore the context structure */
2128
2129     fprintf( outfile, "\tfrstor %d(%%esp)\n", CONTEXTOFFSET(FloatSave) );
2130
2131     /* Store %eip value onto the new stack */
2132
2133     fprintf( outfile, "\tmovl %d(%%esp),%%eax\n", CONTEXTOFFSET(Eip) );
2134     fprintf( outfile, "\tmovl %d(%%esp),%%ebx\n", CONTEXTOFFSET(Esp) );
2135     fprintf( outfile, "\tmovl %%eax,0(%%ebx)\n" );
2136
2137     /* Restore all registers */
2138
2139     fprintf( outfile, "\tleal %d(%%esp),%%esp\n",
2140              sizeof(FLOATING_SAVE_AREA) + 7 * sizeof(DWORD) );
2141     fprintf( outfile, "\tpopl %%eax\n" );
2142     fprintf( outfile, "\tmovw %%ax,%%gs\n" );
2143     fprintf( outfile, "\tpopl %%eax\n" );
2144     fprintf( outfile, "\tmovw %%ax,%%fs\n" );
2145     fprintf( outfile, "\tpopl %%eax\n" );
2146     fprintf( outfile, "\tmovw %%ax,%%es\n" );
2147     fprintf( outfile, "\tpopl %%eax\n" );
2148     fprintf( outfile, "\tmovw %%ax,%%ds\n" );
2149
2150     fprintf( outfile, "\tpopl %%edi\n" );
2151     fprintf( outfile, "\tpopl %%esi\n" );
2152     fprintf( outfile, "\tpopl %%ebx\n" );
2153     fprintf( outfile, "\tpopl %%edx\n" );
2154     fprintf( outfile, "\tpopl %%ecx\n" );
2155     fprintf( outfile, "\tpopl %%eax\n" );
2156     fprintf( outfile, "\tpopl %%ebp\n" );
2157     fprintf( outfile, "\tleal 8(%%esp),%%esp\n" );  /* skip %eip and %cs */
2158     fprintf( outfile, "\tpopfl\n" );
2159     fprintf( outfile, "\tpopl %%esp\n" );
2160     fprintf( outfile, "\tret\n" );
2161 }
2162
2163
2164 /*******************************************************************
2165  *         BuildSpec
2166  *
2167  * Build the spec files
2168  */
2169 static int BuildSpec( FILE *outfile, int argc, char *argv[] )
2170 {
2171     int i;
2172     for (i = 2; i < argc; i++)
2173         if (BuildSpecFile( outfile, argv[i] ) < 0) return -1;
2174     return 0;
2175 }
2176
2177
2178 /*******************************************************************
2179  *         BuildCallFrom16
2180  *
2181  * Build the 16-bit-to-Wine callbacks
2182  */
2183 static int BuildCallFrom16( FILE *outfile, char * outname, int argc, char *argv[] )
2184 {
2185     int i;
2186     char buffer[1024];
2187
2188     /* File header */
2189
2190     fprintf( outfile, "/* File generated automatically. Do not edit! */\n\n" );
2191     fprintf( outfile, "\t.text\n" );
2192
2193 #ifdef USE_STABS
2194     fprintf( outfile, "\t.file\t\"%s\"\n", outname );
2195     getcwd(buffer, sizeof(buffer));
2196
2197     /*
2198      * The stabs help the internal debugger as they are an indication that it
2199      * is sensible to step into a thunk/trampoline.
2200      */
2201     fprintf( outfile, ".stabs \"%s/\",100,0,0,Code_Start\n", buffer);
2202     fprintf( outfile, ".stabs \"%s\",100,0,0,Code_Start\n", outname);
2203     fprintf( outfile, "\t.text\n" );
2204     fprintf( outfile, "\t.align 4\n" );
2205     fprintf( outfile, "Code_Start:\n\n" );
2206 #endif
2207
2208     /* Build the callback functions */
2209
2210     for (i = 2; i < argc; i++) BuildCallFrom16Func( outfile, argv[i] );
2211
2212     /* Output the argument debugging strings */
2213
2214     if (debugging)
2215     {
2216         fprintf( outfile, "/* Argument strings */\n" );
2217         for (i = 2; i < argc; i++)
2218         {
2219             fprintf( outfile, "Profile_%s:\n", argv[i] );
2220             fprintf( outfile, "\t.string \"%s\\0\"\n", argv[i] + 5 );
2221         }
2222     }
2223
2224 #ifdef USE_STABS
2225     fprintf( outfile, "\t.text\n");
2226     fprintf( outfile, "\t.stabs \"\",100,0,0,.Letext\n");
2227     fprintf( outfile, ".Letext:\n");
2228 #endif
2229
2230     return 0;
2231 }
2232
2233
2234 /*******************************************************************
2235  *         BuildCallTo16
2236  *
2237  * Build the Wine-to-16-bit callbacks
2238  */
2239 static int BuildCallTo16( FILE *outfile, char * outname, int argc, char *argv[] )
2240 {
2241     char buffer[1024];
2242     FILE *infile;
2243
2244     if (argc > 2)
2245     {
2246         infile = fopen( argv[2], "r" );
2247         if (!infile)
2248         {
2249             perror( argv[2] );
2250             exit( 1 );
2251         }
2252     }
2253     else infile = stdin;
2254
2255     /* File header */
2256
2257     fprintf( outfile, "/* File generated automatically. Do not edit! */\n\n" );
2258     fprintf( outfile, "\t.text\n" );
2259
2260 #ifdef USE_STABS
2261     fprintf( outfile, "\t.file\t\"%s\"\n", outname );
2262     getcwd(buffer, sizeof(buffer));
2263
2264     /*
2265      * The stabs help the internal debugger as they are an indication that it
2266      * is sensible to step into a thunk/trampoline.
2267      */
2268     fprintf( outfile, ".stabs \"%s/\",100,0,0,Code_Start\n", buffer);
2269     fprintf( outfile, ".stabs \"%s\",100,0,0,Code_Start\n", outname);
2270     fprintf( outfile, "\t.text\n" );
2271     fprintf( outfile, "\t.align 4\n" );
2272     fprintf( outfile, "Code_Start:\n\n" );
2273 #endif
2274
2275     fprintf( outfile, "\t.globl " PREFIX "CALLTO16_Start\n" );
2276     fprintf( outfile, PREFIX "CALLTO16_Start:\n" );
2277
2278     /* Build the callback functions */
2279
2280     while (fgets( buffer, sizeof(buffer), infile ))
2281     {
2282         if (strstr( buffer, "### start build ###" )) break;
2283     }
2284     while (fgets( buffer, sizeof(buffer), infile ))
2285     {
2286         char *p = strstr( buffer, "CallTo16_" );
2287         if (p)
2288         {
2289             char *profile = p + strlen( "CallTo16_" );
2290             p = profile;
2291             while ((*p == '_') || isalpha(*p)) p++;
2292             *p = '\0';
2293             BuildCallTo16Func( outfile, profile );
2294         }
2295         if (strstr( buffer, "### stop build ###" )) break;
2296     }
2297
2298     /* Output the 16-bit return code */
2299
2300     BuildRet16Func( outfile );
2301
2302     fprintf( outfile, "\t.globl " PREFIX "CALLTO16_End\n" );
2303     fprintf( outfile, PREFIX "CALLTO16_End:\n" );
2304
2305 #ifdef USE_STABS
2306     fprintf( outfile, "\t.text\n");
2307     fprintf( outfile, "\t.stabs \"\",100,0,0,.Letext\n");
2308     fprintf( outfile, ".Letext:\n");
2309 #endif
2310
2311     fclose( infile );
2312     return 0;
2313 }
2314
2315
2316 /*******************************************************************
2317  *         BuildCall32
2318  *
2319  * Build the 32-bit callbacks
2320  */
2321 static int BuildCall32( FILE *outfile, char * outname )
2322 {
2323     char buffer[1024];
2324
2325     /* File header */
2326
2327     fprintf( outfile, "/* File generated automatically. Do not edit! */\n\n" );
2328     fprintf( outfile, "\t.text\n" );
2329
2330 #ifdef __i386__
2331
2332 #ifdef USE_STABS
2333     fprintf( outfile, "\t.file\t\"%s\"\n", outname );
2334     getcwd(buffer, sizeof(buffer));
2335
2336     /*
2337      * The stabs help the internal debugger as they are an indication that it
2338      * is sensible to step into a thunk/trampoline.
2339      */
2340     fprintf( outfile, ".stabs \"%s/\",100,0,0,Code_Start\n", buffer);
2341     fprintf( outfile, ".stabs \"%s\",100,0,0,Code_Start\n", outname);
2342     fprintf( outfile, "\t.text\n" );
2343     fprintf( outfile, "\t.align 4\n" );
2344     fprintf( outfile, "Code_Start:\n" );
2345 #endif
2346
2347     /* Build the 32-bit large stack callback */
2348
2349     BuildCallTo32LargeStack( outfile );
2350
2351     /* Build the register callback function */
2352
2353     BuildCallFrom32Regs( outfile );
2354
2355 #ifdef USE_STABS
2356     fprintf( outfile, "\t.text\n");
2357     fprintf( outfile, "\t.stabs \"\",100,0,0,.Letext\n");
2358     fprintf( outfile, ".Letext:\n");
2359 #endif
2360
2361 #else  /* __i386__ */
2362
2363     /* Just to avoid an empty file */
2364     fprintf( outfile, "\t.long 0\n" );
2365
2366 #endif  /* __i386__ */
2367     return 0;
2368 }
2369
2370
2371 /*******************************************************************
2372  *         usage
2373  */
2374 static void usage(void)
2375 {
2376     fprintf( stderr,
2377              "usage: build [-o outfile] -spec SPECNAMES\n"
2378              "       build [-o outfile] -callfrom16 FUNCTION_PROFILES\n"
2379              "       build [-o outfile] -callto16 FUNCTION_PROFILES\n"
2380              "       build [-o outfile] -call32\n" );
2381     exit(1);
2382 }
2383
2384
2385 /*******************************************************************
2386  *         main
2387  */
2388 int main(int argc, char **argv)
2389 {
2390     char *outname = NULL;
2391     FILE *outfile = stdout;
2392     int res = -1;
2393
2394     if (argc < 2) usage();
2395
2396     if (!strcmp( argv[1], "-o" ))
2397     {
2398         outname = argv[2];
2399         argv += 2;
2400         argc -= 2;
2401         if (argc < 2) usage();
2402         if (!(outfile = fopen( outname, "w" )))
2403         {
2404             fprintf( stderr, "Unable to create output file '%s'\n", outname );
2405             exit(1);
2406         }
2407     }
2408
2409     /* Retrieve the selector values; this assumes that we are building
2410      * the asm files on the platform that will also run them. Probably
2411      * a safe assumption to make.
2412      */
2413     GET_CS( Code_Selector );
2414     GET_DS( Data_Selector );
2415
2416     if (!strcmp( argv[1], "-spec" ))
2417         res = BuildSpec( outfile, argc, argv );
2418     else if (!strcmp( argv[1], "-callfrom16" ))
2419         res = BuildCallFrom16( outfile, outname, argc, argv );
2420     else if (!strcmp( argv[1], "-callto16" ))
2421         res = BuildCallTo16( outfile, outname, argc, argv );
2422     else if (!strcmp( argv[1], "-call32" ))
2423         res = BuildCall32( outfile, outname );
2424     else
2425     {
2426         fclose( outfile );
2427         unlink( outname );
2428         usage();
2429     }
2430
2431     fclose( outfile );
2432     if (res < 0)
2433     {
2434         unlink( outname );
2435         return 1;
2436     }
2437     return 0;
2438 }