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