Release 960623
[wine] / tools / build.c
1 /*
2  * Copyright 1993 Robert J. Amstadt
3  * Copyright 1995 Martin von Loewis
4  * Copyright 1995, 1996 Alexandre Julliard
5  */
6
7 #ifndef WINELIB
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <ctype.h>
13 #include "registers.h"
14 #include "winerror.h"  /* for ERROR_CALL_NOT_IMPLEMENTED */
15 #include "module.h"
16 #include "neexe.h"
17 #include "windows.h"
18
19 /* ELF symbols do not have an underscore in front */
20 #if defined (__ELF__) || defined (__svr4__) || defined(_SCO_DS)
21 #define PREFIX
22 #else
23 #define PREFIX "_"
24 #endif
25
26 #define TYPE_INVALID     0
27 #define TYPE_BYTE        1
28 #define TYPE_WORD        2
29 #define TYPE_LONG        3
30 #define TYPE_PASCAL_16   4
31 #define TYPE_PASCAL      5
32 #define TYPE_REGISTER    6
33 #define TYPE_ABS         7
34 #define TYPE_RETURN      8
35 #define TYPE_STUB        9
36 #define TYPE_STDCALL    10
37
38 #define MAX_ORDINALS    1299
39
40   /* Callback function used for stub functions */
41 #define STUB_CALLBACK \
42   ((SpecType == SPEC_WIN16) ? "RELAY_Unimplemented16": "RELAY_Unimplemented32")
43
44 enum SPEC_TYPE
45 {
46     SPEC_INVALID,
47     SPEC_WIN16,
48     SPEC_WIN32
49 };
50
51 typedef struct ordinal_definition_s
52 {
53     int type;
54     int offset;
55     char export_name[80];
56     void *additional_data;
57 } ORDDEF;
58
59 typedef struct ordinal_variable_definition_s
60 {
61     int n_values;
62     int *values;
63 } ORDVARDEF;
64
65 typedef struct ordinal_function_definition_s
66 {
67     int  n_args;
68     char arg_types[32];
69     char internal_name[80];
70 } ORDFUNCDEF;
71
72 typedef struct ordinal_return_definition_s
73 {
74     int arg_size;
75     int ret_value;
76 } ORDRETDEF;
77
78 static ORDDEF OrdinalDefinitions[MAX_ORDINALS];
79
80 static enum SPEC_TYPE SpecType = SPEC_INVALID;
81 char DLLName[80];
82 int Limit = 0;
83 int Base = 0;
84 int HeapSize = 0;
85 FILE *SpecFp;
86
87 char *ParseBuffer = NULL;
88 char *ParseNext;
89 char ParseSaveChar;
90 int Line;
91
92 static int debugging = 1;
93
94   /* Offset of register relative to the end of the context struct */
95 #define CONTEXTOFFSET(reg) \
96   ((int)&reg##_reg((struct sigcontext_struct *)0) \
97    - sizeof(struct sigcontext_struct))
98
99 static void *xmalloc (size_t size)
100 {
101     void *res;
102
103     res = malloc (size ? size : 1);
104     if (res == NULL)
105     {
106         fprintf (stderr, "Virtual memory exhausted.\n");
107         exit (1);
108     }
109     return res;
110 }
111
112
113 static void *xrealloc (void *ptr, size_t size)
114 {
115     void *res = realloc (ptr, size);
116     if (res == NULL)
117     {
118         fprintf (stderr, "Virtual memory exhausted.\n");
119         exit (1);
120     }
121     return res;
122 }
123
124
125 static int IsNumberString(char *s)
126 {
127     while (*s != '\0')
128         if (!isdigit(*s++))
129             return 0;
130
131     return 1;
132 }
133
134 static char *strupper(char *s)
135 {
136     char *p;
137     
138     for(p = s; *p != '\0'; p++)
139         *p = toupper(*p);
140
141     return s;
142 }
143
144 static char * GetTokenInLine(void)
145 {
146     char *p;
147     char *token;
148
149     if (ParseNext != ParseBuffer)
150     {
151         if (ParseSaveChar == '\0')
152             return NULL;
153         *ParseNext = ParseSaveChar;
154     }
155     
156     /*
157      * Remove initial white space.
158      */
159     for (p = ParseNext; isspace(*p); p++)
160         ;
161     
162     if ((*p == '\0') || (*p == '#'))
163         return NULL;
164     
165     /*
166      * Find end of token.
167      */
168     token = p++;
169     if (*token != '(' && *token != ')')
170         while (*p != '\0' && *p != '(' && *p != ')' && !isspace(*p))
171             p++;
172     
173     ParseSaveChar = *p;
174     ParseNext = p;
175     *p = '\0';
176
177     return token;
178 }
179
180 static char * GetToken(void)
181 {
182     char *token;
183
184     if (ParseBuffer == NULL)
185     {
186         ParseBuffer = xmalloc(512);
187         ParseNext = ParseBuffer;
188         Line++;
189         while (1)
190         {
191             if (fgets(ParseBuffer, 511, SpecFp) == NULL)
192                 return NULL;
193             if (ParseBuffer[0] != '#')
194                 break;
195         }
196     }
197
198     while ((token = GetTokenInLine()) == NULL)
199     {
200         ParseNext = ParseBuffer;
201         Line++;
202         while (1)
203         {
204             if (fgets(ParseBuffer, 511, SpecFp) == NULL)
205                 return NULL;
206             if (ParseBuffer[0] != '#')
207                 break;
208         }
209     }
210
211     return token;
212 }
213
214 static int ParseVariable(int ordinal, int type)
215 {
216     ORDDEF *odp;
217     ORDVARDEF *vdp;
218     char export_name[80];
219     char *token;
220     char *endptr;
221     int *value_array;
222     int n_values;
223     int value_array_size;
224     
225     strcpy(export_name, GetToken());
226
227     token = GetToken();
228     if (*token != '(')
229     {
230         fprintf(stderr, "%d: Expected '(' got '%s'\n", Line, token);
231         exit(1);
232     }
233
234     n_values = 0;
235     value_array_size = 25;
236     value_array = xmalloc(sizeof(*value_array) * value_array_size);
237     
238     while ((token = GetToken()) != NULL)
239     {
240         if (*token == ')')
241             break;
242
243         value_array[n_values++] = strtol(token, &endptr, 0);
244         if (n_values == value_array_size)
245         {
246             value_array_size += 25;
247             value_array = xrealloc(value_array, 
248                                    sizeof(*value_array) * value_array_size);
249         }
250         
251         if (endptr == NULL || *endptr != '\0')
252         {
253             fprintf(stderr, "%d: Expected number value, got '%s'\n", Line,
254                     token);
255             exit(1);
256         }
257     }
258     
259     if (token == NULL)
260     {
261         fprintf(stderr, "%d: End of file in variable declaration\n", Line);
262         exit(1);
263     }
264
265     if (ordinal >= MAX_ORDINALS)
266     {
267         fprintf(stderr, "%d: Ordinal number too large\n", Line);
268         exit(1);
269     }
270     
271     odp = &OrdinalDefinitions[ordinal];
272     odp->type = type;
273     strcpy(odp->export_name, export_name);
274
275     vdp = xmalloc(sizeof(*vdp));
276     odp->additional_data = vdp;
277     
278     vdp->n_values = n_values;
279     vdp->values = xrealloc(value_array, sizeof(*value_array) * n_values);
280
281     return 0;
282 }
283
284 static int ParseExportFunction(int ordinal, int type)
285 {
286     char *token;
287     ORDDEF *odp;
288     ORDFUNCDEF *fdp;
289     int i;
290
291     switch(SpecType)
292     {
293     case SPEC_WIN16:
294         if (type == TYPE_STDCALL)
295         {
296             fprintf( stderr, "%d: 'stdcall' not supported for Win16\n", Line );
297             exit(1);
298         }
299         break;
300     case SPEC_WIN32:
301         if ((type == TYPE_PASCAL) || (type == TYPE_PASCAL_16))
302         {
303             fprintf( stderr, "%d: 'pascal' not supported for Win32\n", Line );
304             exit(1);
305         }
306         break;
307     default:
308         break;
309     }
310     odp = &OrdinalDefinitions[ordinal];
311     strcpy(odp->export_name, GetToken());
312     odp->type = type;
313     fdp = xmalloc(sizeof(*fdp));
314     odp->additional_data = fdp;
315
316     token = GetToken();
317     if (*token != '(')
318     {
319         fprintf(stderr, "%d: Expected '(' got '%s'\n", Line, token);
320         exit(1);
321     }
322
323     for (i = 0; i < sizeof(fdp->arg_types)-1; i++)
324     {
325         token = GetToken();
326         if (*token == ')')
327             break;
328
329         if (!strcmp(token, "byte") || !strcmp(token, "word"))
330             fdp->arg_types[i] = 'w';
331         else if (!strcmp(token, "s_byte") || !strcmp(token, "s_word"))
332             fdp->arg_types[i] = 's';
333         else if (!strcmp(token, "long") || !strcmp(token, "segptr"))
334             fdp->arg_types[i] = 'l';
335         else if (!strcmp(token, "ptr"))
336             fdp->arg_types[i] = 'p';
337         else
338         {
339             fprintf(stderr, "%d: Unknown variable type '%s'\n", Line, token);
340             exit(1);
341         }
342         if (SpecType == SPEC_WIN32)
343         {
344             if (strcmp(token, "long") && strcmp(token, "ptr"))
345             {
346                 fprintf( stderr, "%d: Type '%s' not supported for Win32\n",
347                          Line, token );
348                 exit(1);
349             }
350         }
351     }
352     if (*token != ')')
353     {
354         fprintf( stderr, "%d: Too many arguments\n", Line );
355         exit(1);
356     }
357     fdp->arg_types[i] = '\0';
358
359     strcpy(fdp->internal_name, GetToken());
360     return 0;
361 }
362
363 static int ParseEquate(int ordinal)
364 {
365     ORDDEF *odp;
366     char *token;
367     char *endptr;
368     int value;
369     
370     odp = &OrdinalDefinitions[ordinal];
371     strcpy(odp->export_name, GetToken());
372
373     token = GetToken();
374     value = strtol(token, &endptr, 0);
375     if (endptr == NULL || *endptr != '\0')
376     {
377         fprintf(stderr, "%d: Expected number value, got '%s'\n", Line,
378                 token);
379         exit(1);
380     }
381
382     odp->type = TYPE_ABS;
383     odp->additional_data = (void *) value;
384
385     return 0;
386 }
387
388 static int ParseReturn(int ordinal)
389 {
390     ORDDEF *odp;
391     ORDRETDEF *rdp;
392     char *token;
393     char *endptr;
394     
395     rdp = xmalloc(sizeof(*rdp));
396     
397     odp = &OrdinalDefinitions[ordinal];
398     strcpy(odp->export_name, GetToken());
399     odp->type = TYPE_RETURN;
400     odp->additional_data = rdp;
401
402     token = GetToken();
403     rdp->arg_size = strtol(token, &endptr, 0);
404     if (endptr == NULL || *endptr != '\0')
405     {
406         fprintf(stderr, "%d: Expected number value, got '%s'\n", Line,
407                 token);
408         exit(1);
409     }
410
411     token = GetToken();
412     rdp->ret_value = strtol(token, &endptr, 0);
413     if (endptr == NULL || *endptr != '\0')
414     {
415         fprintf(stderr, "%d: Expected number value, got '%s'\n", Line,
416                 token);
417         exit(1);
418     }
419
420     return 0;
421 }
422
423
424 static int ParseStub( int ordinal )
425 {
426     ORDDEF *odp;
427     ORDFUNCDEF *fdp;
428     
429     odp = &OrdinalDefinitions[ordinal];
430     strcpy( odp->export_name, GetToken() );
431     odp->type = TYPE_STUB;
432     fdp = xmalloc(sizeof(*fdp));
433     odp->additional_data = fdp;
434     fdp->arg_types[0] = '\0';
435     strcpy( fdp->internal_name, STUB_CALLBACK );
436     return 0;
437 }
438
439
440 static int ParseOrdinal(int ordinal)
441 {
442     char *token;
443     
444     if (ordinal >= MAX_ORDINALS)
445     {
446         fprintf(stderr, "%d: Ordinal number too large\n", Line);
447         exit(1);
448     }
449     if (ordinal > Limit) Limit = ordinal;
450
451     token = GetToken();
452     if (token == NULL)
453     {
454         fprintf(stderr, "%d: Expected type after ordinal\n", Line);
455         exit(1);
456     }
457
458     if (strcmp(token, "byte") == 0)
459         return ParseVariable(ordinal, TYPE_BYTE);
460     if (strcmp(token, "word") == 0)
461         return ParseVariable(ordinal, TYPE_WORD);
462     if (strcmp(token, "long") == 0)
463         return ParseVariable(ordinal, TYPE_LONG);
464     if (strcmp(token, "pascal") == 0)
465         return ParseExportFunction(ordinal, TYPE_PASCAL);
466     if (strcmp(token, "pascal16") == 0)
467         return ParseExportFunction(ordinal, TYPE_PASCAL_16);
468     if (strcmp(token, "register") == 0)
469         return ParseExportFunction(ordinal, TYPE_REGISTER);
470     if (strcmp(token, "stdcall") == 0)
471         return ParseExportFunction(ordinal, TYPE_STDCALL);
472     if (strcmp(token, "equate") == 0)
473         return ParseEquate(ordinal);
474     if (strcmp(token, "return") == 0)
475         return ParseReturn(ordinal);
476     if (strcmp(token, "stub") == 0)
477         return ParseStub(ordinal);
478     fprintf(stderr, 
479             "%d: Expected type after ordinal, found '%s' instead\n",
480             Line, token);
481     exit(1);
482 }
483
484 static int ParseTopLevel(void)
485 {
486     char *token;
487     
488     while ((token = GetToken()) != NULL)
489     {
490         if (strcmp(token, "name") == 0)
491         {
492             strcpy(DLLName, GetToken());
493             strupper(DLLName);
494         }
495         else if (strcmp(token, "type") == 0)
496         {
497             token = GetToken();
498             if (!strcmp(token, "win16" )) SpecType = SPEC_WIN16;
499             else if (!strcmp(token, "win32" )) SpecType = SPEC_WIN32;
500             else
501             {
502                 fprintf(stderr, "%d: Type must be 'win16' or 'win32'\n", Line);
503                 exit(1);
504             }
505         }
506         else if (strcmp(token, "base") == 0)
507         {
508             token = GetToken();
509             if (!IsNumberString(token))
510             {
511                 fprintf(stderr, "%d: Expected number after base\n", Line);
512                 exit(1);
513             }
514             Base = atoi(token);
515         }
516         else if (strcmp(token, "heap") == 0)
517         {
518             token = GetToken();
519             if (!IsNumberString(token))
520             {
521                 fprintf(stderr, "%d: Expected number after heap\n", Line);
522                 exit(1);
523             }
524             HeapSize = atoi(token);
525         }
526         else if (IsNumberString(token))
527         {
528             int ordinal;
529             int rv;
530             
531             ordinal = atoi(token);
532             if ((rv = ParseOrdinal(ordinal)) < 0)
533                 return rv;
534         }
535         else
536         {
537             fprintf(stderr, 
538                     "%d: Expected name, id, length or ordinal\n", Line);
539             exit(1);
540         }
541     }
542
543     return 0;
544 }
545
546
547 /*******************************************************************
548  *         StoreVariableCode
549  *
550  * Store a list of ints into a byte array.
551  */
552 static int StoreVariableCode( unsigned char *buffer, int size, ORDDEF *odp )
553 {
554     ORDVARDEF *vdp;
555     int i;
556
557     vdp = odp->additional_data;
558     switch(size)
559     {
560     case 1:
561         for (i = 0; i < vdp->n_values; i++)
562             buffer[i] = vdp->values[i];
563         break;
564     case 2:
565         for (i = 0; i < vdp->n_values; i++)
566             ((unsigned short *)buffer)[i] = vdp->values[i];
567         break;
568     case 4:
569         for (i = 0; i < vdp->n_values; i++)
570             ((unsigned int *)buffer)[i] = vdp->values[i];
571         break;
572     }
573     return vdp->n_values * size;
574 }
575
576
577 /*******************************************************************
578  *         DumpBytes
579  *
580  * Dump a byte stream into the assembly code.
581  */
582 static void DumpBytes( const unsigned char *data, int len,
583                        const char *section, const char *label_start )
584 {
585     int i;
586     if (section) printf( "\t%s\n", section );
587     if (label_start) printf( "%s:\n", label_start );
588     for (i = 0; i < len; i++)
589     {
590         if (!(i & 0x0f)) printf( "\t.byte " );
591         printf( "%d", *data++ );
592         if (i < len - 1) printf( "%c", ((i & 0x0f) != 0x0f) ? ',' : '\n' );
593     }
594     printf( "\n" );
595 }
596
597
598 /*******************************************************************
599  *         BuildModule16
600  *
601  * Build the in-memory representation of a 16-bit NE module, and dump it
602  * as a byte stream into the assembly code.
603  */
604 static int BuildModule16( int max_code_offset, int max_data_offset )
605 {
606     ORDDEF *odp;
607     int i;
608     char *buffer;
609     NE_MODULE *pModule;
610     SEGTABLEENTRY *pSegment;
611     OFSTRUCT *pFileInfo;
612     BYTE *pstr, *bundle;
613     WORD *pword;
614
615     /*   Module layout:
616      * NE_MODULE       Module
617      * OFSTRUCT        File information
618      * SEGTABLEENTRY   Segment 1 (code)
619      * SEGTABLEENTRY   Segment 2 (data)
620      * WORD[2]         Resource table (empty)
621      * BYTE[2]         Imported names (empty)
622      * BYTE[n]         Resident names table
623      * BYTE[n]         Entry table
624      */
625
626     buffer = xmalloc( 0x10000 );
627
628     pModule = (NE_MODULE *)buffer;
629     pModule->magic = NE_SIGNATURE;
630     pModule->count = 1;
631     pModule->next = 0;
632     pModule->flags = NE_FFLAGS_SINGLEDATA | NE_FFLAGS_BUILTIN | NE_FFLAGS_LIBMODULE;
633     pModule->dgroup = 2;
634     pModule->heap_size = HeapSize;
635     pModule->stack_size = 0;
636     pModule->ip = 0;
637     pModule->cs = 0;
638     pModule->sp = 0;
639     pModule->ss = 0;
640     pModule->seg_count = 2;
641     pModule->modref_count = 0;
642     pModule->nrname_size = 0;
643     pModule->modref_table = 0;
644     pModule->nrname_fpos = 0;
645     pModule->moveable_entries = 0;
646     pModule->alignment = 0;
647     pModule->truetype = 0;
648     pModule->os_flags = NE_OSFLAGS_WINDOWS;
649     pModule->misc_flags = 0;
650     pModule->dlls_to_init  = 0;
651     pModule->nrname_handle = 0;
652     pModule->min_swap_area = 0;
653     pModule->expected_version = 0x030a;
654     pModule->pe_module = NULL;
655     pModule->self = 0;
656     pModule->self_loading_sel = 0;
657
658       /* File information */
659
660     pFileInfo = (OFSTRUCT *)(pModule + 1);
661     pModule->fileinfo = (int)pFileInfo - (int)pModule;
662     memset( pFileInfo, 0, sizeof(*pFileInfo) - sizeof(pFileInfo->szPathName) );
663     pFileInfo->cBytes = sizeof(*pFileInfo) - sizeof(pFileInfo->szPathName)
664                         + strlen(DLLName) + 4;
665     sprintf( pFileInfo->szPathName, "%s.DLL", DLLName );
666     pstr = (char *)pFileInfo + pFileInfo->cBytes + 1;
667         
668       /* Segment table */
669
670     pSegment = (SEGTABLEENTRY *)pstr;
671     pModule->seg_table = (int)pSegment - (int)pModule;
672     pSegment->filepos = 0;
673     pSegment->size = max_code_offset;
674     pSegment->flags = 0;
675     pSegment->minsize = max_code_offset;
676     pSegment->selector = 0;
677     pSegment++;
678
679     pModule->dgroup_entry = (int)pSegment - (int)pModule;
680     pSegment->filepos = 0;
681     pSegment->size = max_data_offset;
682     pSegment->flags = NE_SEGFLAGS_DATA;
683     pSegment->minsize = max_data_offset;
684     pSegment->selector = 0;
685     pSegment++;
686
687       /* Resource table */
688
689     pword = (WORD *)pSegment;
690     pModule->res_table = (int)pword - (int)pModule;
691     *pword++ = 0;
692     *pword++ = 0;
693
694       /* Imported names table */
695
696     pstr = (char *)pword;
697     pModule->import_table = (int)pstr - (int)pModule;
698     *pstr++ = 0;
699     *pstr++ = 0;
700
701       /* Resident names table */
702
703     pModule->name_table = (int)pstr - (int)pModule;
704     /* First entry is module name */
705     *pstr = strlen(DLLName );
706     strcpy( pstr + 1, DLLName );
707     pstr += *pstr + 1;
708     *(WORD *)pstr = 0;
709     pstr += sizeof(WORD);
710     /* Store all ordinals */
711     odp = OrdinalDefinitions + 1;
712     for (i = 1; i <= Limit; i++, odp++)
713     {
714         if (!odp->export_name[0]) continue;
715         *pstr = strlen( odp->export_name );
716         strcpy( pstr + 1, odp->export_name );
717         strupper( pstr + 1 );
718         pstr += *pstr + 1;
719         *(WORD *)pstr = i;
720         pstr += sizeof(WORD);
721     }
722     *pstr++ = 0;
723
724       /* Entry table */
725
726     pModule->entry_table = (int)pstr - (int)pModule;
727     bundle = NULL;
728     odp = OrdinalDefinitions + 1;
729     for (i = 1; i <= Limit; i++, odp++)
730     {
731         int selector = 0;
732
733         switch (odp->type)
734         {
735         case TYPE_INVALID:
736             selector = 0;  /* Invalid selector */
737             break;
738
739         case TYPE_PASCAL:
740         case TYPE_PASCAL_16:
741         case TYPE_REGISTER:
742         case TYPE_RETURN:
743         case TYPE_STUB:
744             selector = 1;  /* Code selector */
745             break;
746
747         case TYPE_BYTE:
748         case TYPE_WORD:
749         case TYPE_LONG:
750             selector = 2;  /* Data selector */
751             break;
752
753         case TYPE_ABS:
754             selector = 0xfe;  /* Constant selector */
755             break;
756         }
757
758           /* create a new bundle if necessary */
759         if (!bundle || (bundle[0] >= 254) || (bundle[1] != selector))
760         {
761             bundle = pstr;
762             bundle[0] = 0;
763             bundle[1] = selector;
764             pstr += 2;
765         }
766
767         (*bundle)++;
768         if (selector != 0)
769         {
770             *pstr++ = 1;
771             *(WORD *)pstr = odp->offset;
772             pstr += sizeof(WORD);
773         }
774     }
775     *pstr++ = 0;
776
777       /* Dump the module content */
778
779     DumpBytes( (char *)pModule, (int)pstr - (int)pModule,
780                ".data", "Module_Start" );
781     return (int)pstr - (int)pModule;
782 }
783
784
785 /*******************************************************************
786  *         BuildModule32
787  *
788  * Build the in-memory representation of a 32-bit pseudo-NE module, and dump it
789  * as a byte stream into the assembly code.
790  */
791 static int BuildModule32(void)
792 {
793     char *buffer;
794     NE_MODULE *pModule;
795     OFSTRUCT *pFileInfo;
796     BYTE *pstr;
797     WORD *pword;
798
799     /*   Module layout:
800      * NE_MODULE            Module
801      * OFSTRUCT             File information
802      * SEGTABLEENTRY        Segment table (empty)
803      * WORD[2]              Resource table (empty)
804      * BYTE[2]              Imported names (empty)
805      * BYTE[n]              Resident names table (1 entry)
806      * BYTE[n]              Entry table (empty)
807      */
808
809     buffer = xmalloc( 0x10000 );
810
811     pModule = (NE_MODULE *)buffer;
812     pModule->magic = NE_SIGNATURE;
813     pModule->count = 1;
814     pModule->next = 0;
815     pModule->flags = NE_FFLAGS_SINGLEDATA | NE_FFLAGS_BUILTIN |
816                      NE_FFLAGS_LIBMODULE | NE_FFLAGS_WIN32;
817     pModule->dgroup = 0;
818     pModule->heap_size = HeapSize;
819     pModule->stack_size = 0;
820     pModule->ip = 0;
821     pModule->cs = 0;
822     pModule->sp = 0;
823     pModule->ss = 0;
824     pModule->seg_count = 0;
825     pModule->modref_count = 0;
826     pModule->nrname_size = 0;
827     pModule->modref_table = 0;
828     pModule->nrname_fpos = 0;
829     pModule->moveable_entries = 0;
830     pModule->alignment = 0;
831     pModule->truetype = 0;
832     pModule->os_flags = NE_OSFLAGS_WINDOWS;
833     pModule->misc_flags = 0;
834     pModule->dlls_to_init  = 0;
835     pModule->nrname_handle = 0;
836     pModule->min_swap_area = 0;
837     pModule->expected_version = 0x030a;
838     pModule->pe_module = NULL;
839     pModule->self = 0;
840     pModule->self_loading_sel = 0;
841
842       /* File information */
843
844     pFileInfo = (OFSTRUCT *)(pModule + 1);
845     pModule->fileinfo = (int)pFileInfo - (int)pModule;
846     memset( pFileInfo, 0, sizeof(*pFileInfo) - sizeof(pFileInfo->szPathName) );
847     pFileInfo->cBytes = sizeof(*pFileInfo) - sizeof(pFileInfo->szPathName)
848                         + strlen(DLLName) + 4;
849     sprintf( pFileInfo->szPathName, "%s.DLL", DLLName );
850     pstr = (char *)pFileInfo + pFileInfo->cBytes + 1;
851         
852       /* Segment table */
853
854     pModule->seg_table = (int)pstr - (int)pModule;
855
856       /* Resource table */
857
858     pword = (WORD *)pstr;
859     pModule->res_table = (int)pword - (int)pModule;
860     *pword++ = 0;
861     *pword++ = 0;
862
863       /* Imported names table */
864
865     pstr = (char *)pword;
866     pModule->import_table = (int)pstr - (int)pModule;
867     *pstr++ = 0;
868     *pstr++ = 0;
869
870       /* Resident names table */
871
872     pModule->name_table = (int)pstr - (int)pModule;
873     /* First entry is module name */
874     *pstr = strlen(DLLName );
875     strcpy( pstr + 1, DLLName );
876     pstr += *pstr + 1;
877     *(WORD *)pstr = 0;
878     pstr += sizeof(WORD);
879     *pstr++ = 0;
880
881       /* Entry table */
882
883     pModule->entry_table = (int)pstr - (int)pModule;
884     *pstr++ = 0;
885
886       /* Dump the module content */
887
888     DumpBytes( (char *)pModule, (int)pstr - (int)pModule,
889                ".data", "Module_Start" );
890     return (int)pstr - (int)pModule;
891 }
892
893
894 /*******************************************************************
895  *         BuildSpec32Files
896  *
897  * Build a Win32 assembly file from a spec file.
898  */
899 static void BuildSpec32Files(void)
900 {
901     ORDDEF *odp;
902     ORDFUNCDEF *fdp;
903     ORDRETDEF *rdp;
904     int i, module_size;
905
906     printf( "/* File generated automatically; do not edit! */\n" );
907     printf( "\t.text\n" );
908     printf( "\t.align 4\n" );
909     printf( "Code_Start:\n\n" );
910
911     odp = OrdinalDefinitions;
912     for (i = 0; i <= Limit; i++, odp++)
913     {
914         fdp = odp->additional_data;
915         rdp = odp->additional_data;
916
917         switch (odp->type)
918         {
919         case TYPE_INVALID:
920             printf( "/* %s.%d */\n", DLLName, i );
921             printf( "\t.align 4\n" );
922             printf( "%s_%d:\n", DLLName, i );
923             printf( "\tpushl %%ebp\n" );
924             printf( "\tpushl $Name_%d\n", i );
925             printf( "\tpushl $" PREFIX "%s\n", STUB_CALLBACK );
926             printf( "\tjmp " PREFIX "CallFrom32_0\n" );
927             break;
928
929         case TYPE_STDCALL:
930         case TYPE_STUB:
931             printf( "/* %s.%d (%s) */\n",
932                      DLLName, i, odp->export_name);
933             printf( "\t.align 4\n" );
934             printf( "%s_%d:\n", DLLName, i );
935             printf( "\tpushl %%ebp\n" );
936             printf( "\tpushl $Name_%d\n", i );
937             printf( "\tpushl $" PREFIX "%s\n", fdp->internal_name );
938             printf( "\tjmp " PREFIX "CallFrom32_%d\n", strlen(fdp->arg_types));
939             break;
940
941         case TYPE_RETURN:
942             printf( "/* %s.%d (%s) */\n",
943                      DLLName, i, odp->export_name);
944             printf( "\t.align 4\n" );
945             printf( "%s_%d:\n", DLLName, i );
946             printf( "\tmovl $%d,%%eax\n", ERROR_CALL_NOT_IMPLEMENTED );
947             printf( "\tmovl %%eax," PREFIX "WIN32_LastError\n" );
948             printf( "\tmovl $%d,%%eax\n", rdp->ret_value );
949             if (rdp->arg_size) printf( "\tret $%d\n", rdp->arg_size );
950             else printf( "\tret\n" );
951             break;
952
953         default:
954             fprintf(stderr,"build: function type %d not available for Win32\n",
955                     odp->type);
956             exit(1);
957         }
958     }
959
960     module_size = BuildModule32();
961
962     /* Output the DLL functions table */
963
964     printf( "\t.text\n" );
965     printf( "\t.align 4\n" );
966     printf( "Functions:\n" );
967     odp = OrdinalDefinitions;
968     for (i = 0; i <= Limit; i++, odp++) printf("\t.long %s_%d\n", DLLName, i);
969
970     /* Output the DLL names table */
971
972     printf( "FuncNames:\n" );
973     odp = OrdinalDefinitions;
974     for (i = 0; i <= Limit; i++, odp++)
975     {
976         if (odp->type == TYPE_INVALID) printf( "\t.long 0\n" );
977         else printf( "\t.long Name_%d\n", i );
978     }
979
980     /* Output the DLL names */
981
982     for (i = 0, odp = OrdinalDefinitions; i <= Limit; i++, odp++)
983     {
984         printf( "Name_%d:\t", i );
985         if (odp->type == TYPE_INVALID)
986             printf( ".ascii \"%s.%d\\0\"\n", DLLName, i );
987         else
988             printf( ".ascii \"%s\\0\"\n", odp->export_name );
989     }
990
991     /* Output the DLL descriptor */
992
993     printf( "DLLName:\t.ascii \"%s\\0\"\n", DLLName );
994     printf( "\t.align 4\n" );
995     printf( "\t.globl " PREFIX "%s_Descriptor\n", DLLName );
996     printf( PREFIX "%s_Descriptor:\n", DLLName );
997     printf( "\t.long DLLName\n" );          /* Name */
998     printf( "\t.long Module_Start\n" );     /* Module start */
999     printf( "\t.long %d\n", module_size );  /* Module size */
1000     printf( "\t.long %d\n", Base );         /* Base */
1001     printf( "\t.long %d\n", Limit );        /* Limit */
1002     printf( "\t.long Functions\n" );        /* Functions */
1003     printf( "\t.long FuncNames\n" );        /* Function names */
1004 }
1005
1006
1007 /*******************************************************************
1008  *         BuildSpec16Files
1009  *
1010  * Build a Win16 assembly file from a spec file.
1011  */
1012 static void BuildSpec16Files(void)
1013 {
1014     ORDDEF *odp;
1015     ORDFUNCDEF *fdp;
1016     ORDRETDEF *rdp;
1017     int i;
1018     int code_offset, data_offset, module_size;
1019     unsigned char *data;
1020
1021     data = (unsigned char *)xmalloc( 0x10000 );
1022     memset( data, 0, 16 );
1023     data_offset = 16;
1024
1025     printf( "/* File generated automatically; do not edit! */\n" );
1026     printf( "\t.text\n" );
1027     printf( "Code_Start:\n" );
1028     code_offset = 0;
1029
1030     odp = OrdinalDefinitions;
1031     for (i = 0; i <= Limit; i++, odp++)
1032     {
1033         fdp = odp->additional_data;
1034         rdp = odp->additional_data;
1035             
1036         switch (odp->type)
1037         {
1038           case TYPE_INVALID:
1039             odp->offset = 0xffff;
1040             break;
1041
1042           case TYPE_ABS:
1043             odp->offset = (int)odp->additional_data & 0xffff;
1044             break;
1045
1046           case TYPE_BYTE:
1047             odp->offset = data_offset;
1048             data_offset += StoreVariableCode( data + data_offset, 1, odp);
1049             break;
1050
1051           case TYPE_WORD:
1052             odp->offset = data_offset;
1053             data_offset += StoreVariableCode( data + data_offset, 2, odp);
1054             break;
1055
1056           case TYPE_LONG:
1057             odp->offset = data_offset;
1058             data_offset += StoreVariableCode( data + data_offset, 4, odp);
1059             break;
1060
1061           case TYPE_RETURN:
1062             printf( "/* %s.%d */\n", DLLName, i);
1063             printf( "\tmovw $%d,%%ax\n", rdp->ret_value & 0xffff );
1064             printf( "\tmovw $%d,%%dx\n", (rdp->ret_value >> 16) & 0xffff);
1065             printf( "\t.byte 0x66\n");
1066             if (rdp->arg_size != 0)
1067                 printf( "\tlret $%d\n\n", rdp->arg_size);
1068             else
1069             {
1070                 printf( "\tlret\n");
1071                 printf( "\tnop\n");
1072                 printf( "\tnop\n\n");
1073             }
1074             odp->offset = code_offset;
1075             code_offset += 12;  /* Assembly code is 12 bytes long */
1076             break;
1077
1078           case TYPE_REGISTER:
1079           case TYPE_PASCAL:
1080           case TYPE_PASCAL_16:
1081           case TYPE_STUB:
1082             printf( "/* %s.%d */\n", DLLName, i);
1083             printf( "\tpushw %%bp\n" );
1084             printf( "\tpushl $" PREFIX "%s\n", fdp->internal_name );
1085             /* FreeBSD does not understand lcall, so do it the hard way */
1086             printf( "\t.byte 0x9a /*lcall*/\n" );
1087             printf( "\t.long " PREFIX "CallFrom16_%s_%s\n",
1088                     (odp->type == TYPE_REGISTER) ? "regs" :
1089                     (odp->type == TYPE_PASCAL) ? "long" : "word",
1090                     fdp->arg_types );
1091             printf( "\t.byte 0x%02x,0x%02x\n", /* Some asms don't have .word */
1092                     LOBYTE(WINE_CODE_SELECTOR), HIBYTE(WINE_CODE_SELECTOR) );
1093             printf( "\tnop\n" );
1094             printf( "\tnop\n\n" );
1095             odp->offset = code_offset;
1096             code_offset += 16;  /* Assembly code is 16 bytes long */
1097             break;
1098                 
1099           default:
1100             fprintf(stderr,"build: function type %d not available for Win16\n",
1101                     odp->type);
1102             exit(1);
1103         }
1104     }
1105
1106     if (!code_offset)  /* Make sure the code segment is not empty */
1107     {
1108         printf( "\t.byte 0\n" );
1109         code_offset++;
1110     }
1111
1112     /* Output data segment */
1113
1114     DumpBytes( data, data_offset, NULL, "Data_Start" );
1115
1116     /* Build the module */
1117
1118     module_size = BuildModule16( code_offset, data_offset );
1119
1120     /* Output the DLL descriptor */
1121
1122     printf( "\t.text\n" );
1123     printf( "DLLName:\t.ascii \"%s\\0\"\n", DLLName );
1124     printf( "\t.align 4\n" );
1125     printf( "\t.globl " PREFIX "%s_Descriptor\n", DLLName );
1126     printf( PREFIX "%s_Descriptor:\n", DLLName );
1127     printf( "\t.long DLLName\n" );          /* Name */
1128     printf( "\t.long Module_Start\n" );     /* Module start */
1129     printf( "\t.long %d\n", module_size );  /* Module size */
1130     printf( "\t.long Code_Start\n" );       /* Code start */
1131     printf( "\t.long Data_Start\n" );       /* Data start */
1132 }
1133
1134
1135 /*******************************************************************
1136  *         BuildSpecFiles
1137  *
1138  * Build an assembly file from a spec file.
1139  */
1140 static void BuildSpecFiles( char *specname )
1141 {
1142     SpecFp = fopen( specname, "r");
1143     if (SpecFp == NULL)
1144     {
1145         fprintf(stderr, "Could not open specification file, '%s'\n", specname);
1146         exit(1);
1147     }
1148
1149     ParseTopLevel();
1150     switch(SpecType)
1151     {
1152     case SPEC_INVALID:
1153         fprintf( stderr, "%s: Missing 'type' declaration\n", specname );
1154         exit(1);
1155     case SPEC_WIN16:
1156         BuildSpec16Files();
1157         break;
1158     case SPEC_WIN32:
1159         BuildSpec32Files();
1160         break;
1161     }
1162 }
1163
1164
1165 /*******************************************************************
1166  *         BuildCall32LargeStack
1167  *
1168  * Build the function used to switch to the original 32-bit stack
1169  * before calling a 32-bit function from 32-bit code. This is used for
1170  * functions that need a large stack, like X bitmaps functions.
1171  *
1172  * The generated function has the following prototype:
1173  *   int CallTo32_LargeStack( int (*func)(), int nbargs, ... )
1174  *
1175  * Stack layout:
1176  *   ...     ...
1177  * (ebp+20)  arg2
1178  * (ebp+16)  arg1
1179  * (ebp+12)  nbargs
1180  * (ebp+8)   func
1181  * (ebp+4)   ret addr
1182  * (ebp)     ebp
1183  */
1184 static void BuildCall32LargeStack(void)
1185 {
1186     /* Function header */
1187
1188     printf( "/**********\n" );
1189     printf( " * " PREFIX "CallTo32_LargeStack\n" );
1190     printf( " **********/\n" );
1191     printf( "\t.align 4\n" );
1192     printf( "\t.globl " PREFIX "CallTo32_LargeStack\n\n" );
1193     printf( PREFIX "CallTo32_LargeStack:\n" );
1194     
1195     /* Entry code */
1196
1197     printf( "\tpushl %%ebp\n" );
1198     printf( "\tmovl %%esp,%%ebp\n" );
1199
1200     /* Save registers */
1201
1202     printf( "\tpushl %%ecx\n" );
1203     printf( "\tpushl %%esi\n" );
1204     printf( "\tpushl %%edi\n" );
1205
1206     /* Retrieve the original 32-bit stack pointer and switch to it if any */
1207
1208     printf( "\tmovl " PREFIX "IF1632_Original32_esp, %%eax\n" );
1209     printf( "\torl %%eax,%%eax\n" );
1210     printf( "\tje no_orig_esp\n" );
1211     printf( "\tmovl %%eax,%%esp\n" );
1212     printf( "no_orig_esp:\n" );
1213
1214     /* Transfer the arguments */
1215
1216     printf( "\tmovl 12(%%ebp),%%ecx\n" );
1217     printf( "\torl %%ecx,%%ecx\n" );
1218     printf( "\tje no_args\n" );
1219     printf( "\tleal 16(%%ebp),%%esi\n" );
1220     printf( "\tshll $2,%%ecx\n" );
1221     printf( "\tsubl %%ecx,%%esp\n" );
1222     printf( "\tmovl %%esp,%%edi\n" );
1223     printf( "\tshrl $2,%%ecx\n" );
1224     printf( "\tcld\n" );
1225     printf( "\trep; movsl\n" );
1226     printf( "no_args:\n" );
1227
1228     /* Call the function */
1229
1230     printf( "\tcall 8(%%ebp)\n" );
1231
1232     /* Switch back to the normal stack */
1233
1234     printf( "\tleal -12(%%ebp),%%esp\n" );
1235
1236     /* Restore registers and return */
1237
1238     printf( "\tpopl %%edi\n" );
1239     printf( "\tpopl %%esi\n" );
1240     printf( "\tpopl %%ecx\n" );
1241     printf( "\tpopl %%ebp\n" );
1242     printf( "\tret\n" );
1243 }
1244
1245
1246 /*******************************************************************
1247  *         TransferArgs16To32
1248  *
1249  * Get the arguments from the 16-bit stack and push them on the 32-bit stack.
1250  * The 16-bit stack layout is:
1251  *   ...     ...
1252  *  (bp+8)    arg2
1253  *  (bp+6)    arg1
1254  *  (bp+4)    cs
1255  *  (bp+2)    ip
1256  *  (bp)      bp
1257  */
1258 static int TransferArgs16To32( char *args )
1259 {
1260     int i, pos16, pos32;
1261
1262     /* Save ebx first */
1263
1264     printf( "\tpushl %%ebx\n" );
1265
1266     /* Get the 32-bit stack pointer */
1267
1268     printf( "\tmovl " PREFIX "IF1632_Saved32_esp,%%ebx\n" );
1269
1270     /* Copy the arguments */
1271
1272     pos16 = 6;  /* skip bp and return address */
1273     pos32 = 0;
1274
1275     for (i = strlen(args); i > 0; i--)
1276     {
1277         pos32 -= 4;
1278         switch(args[i-1])
1279         {
1280         case 'w':  /* word */
1281             printf( "\tmovzwl %d(%%ebp),%%eax\n", pos16 );
1282             printf( "\tmovl %%eax,%d(%%ebx)\n", pos32 );
1283             pos16 += 2;
1284             break;
1285
1286         case 's':  /* s_word */
1287             printf( "\tmovswl %d(%%ebp),%%eax\n", pos16 );
1288             printf( "\tmovl %%eax,%d(%%ebx)\n", pos32 );
1289             pos16 += 2;
1290             break;
1291
1292         case 'l':  /* long */
1293             printf( "\tmovl %d(%%ebp),%%eax\n", pos16 );
1294             printf( "\tmovl %%eax,%d(%%ebx)\n", pos32 );
1295             pos16 += 4;
1296             break;
1297
1298         case 'p':  /* ptr */
1299             /* Get the selector */
1300             printf( "\tmovw %d(%%ebp),%%ax\n", pos16 + 2 );
1301             /* Get the selector base */
1302             printf( "\tandl $0xfff8,%%eax\n" );
1303             printf( "\tmovl " PREFIX "ldt_copy(%%eax),%%eax\n" );
1304             printf( "\tmovl %%eax,%d(%%ebx)\n", pos32 );
1305             /* Add the offset */
1306             printf( "\tmovzwl %d(%%ebp),%%eax\n", pos16 );
1307             printf( "\taddl %%eax,%d(%%ebx)\n", pos32 );
1308             pos16 += 4;
1309             break;
1310
1311         default:
1312             fprintf( stderr, "Unknown arg type '%c'\n", args[i-1] );
1313         }
1314     }
1315
1316     /* Restore ebx */
1317     
1318     printf( "\tpopl %%ebx\n" );
1319
1320     return pos16 - 6;  /* Return the size of the 16-bit args */
1321 }
1322
1323
1324 /*******************************************************************
1325  *         BuildContext
1326  *
1327  * Build the context structure on the 32-bit stack.
1328  * The only valid registers in the context structure are:
1329  *   eax, ebx, ecx, edx, esi, edi, ds, es, (some of the) flags
1330  */
1331 static void BuildContext(void)
1332 {
1333     /* Save ebx first */
1334
1335     printf( "\tpushl %%ebx\n" );
1336
1337     /* Get the 32-bit stack pointer */
1338
1339     printf( "\tmovl " PREFIX "IF1632_Saved32_esp,%%ebx\n" );
1340
1341     /* Store the registers */
1342
1343     printf( "\tpopl %d(%%ebx)\n", CONTEXTOFFSET(EBX) ); /* Get ebx from stack*/
1344     printf( "\tmovl %%eax,%d(%%ebx)\n", CONTEXTOFFSET(EAX) );
1345     printf( "\tmovl %%ecx,%d(%%ebx)\n", CONTEXTOFFSET(ECX) );
1346     printf( "\tmovl %%edx,%d(%%ebx)\n", CONTEXTOFFSET(EDX) );
1347     printf( "\tmovl %%esi,%d(%%ebx)\n", CONTEXTOFFSET(ESI) );
1348     printf( "\tmovl %%edi,%d(%%ebx)\n", CONTEXTOFFSET(EDI) );
1349     printf( "\tmovw -10(%%ebp),%%ax\n" );  /* Get saved ds from stack */
1350     printf( "\tmovw %%ax,%d(%%ebx)\n", CONTEXTOFFSET(DS) );
1351     printf( "\tmovw -6(%%ebp),%%ax\n" );  /* Get saved es from stack */
1352     printf( "\tmovw %%ax,%d(%%ebx)\n", CONTEXTOFFSET(ES) );
1353     printf( "\tpushfl\n" );
1354     printf( "\tpopl %d(%%ebx)\n", CONTEXTOFFSET(EFL) );
1355 }
1356
1357
1358 /*******************************************************************
1359  *         RestoreContext
1360  *
1361  * Restore the registers from the context structure
1362  */
1363 static void RestoreContext(void)
1364 {
1365     /* Get the 32-bit stack pointer */
1366
1367     printf( "\tmovl " PREFIX "IF1632_Saved32_esp,%%ebx\n" );
1368
1369     /* Restore the registers */
1370
1371     printf( "\tmovl %d(%%ebx),%%ecx\n", CONTEXTOFFSET(ECX) );
1372     printf( "\tmovl %d(%%ebx),%%edx\n", CONTEXTOFFSET(EDX) );
1373     printf( "\tmovl %d(%%ebx),%%esi\n", CONTEXTOFFSET(ESI) );
1374     printf( "\tmovl %d(%%ebx),%%edi\n", CONTEXTOFFSET(EDI) );
1375     printf( "\tpopl %%eax\n" );  /* Remove old ds and ip from stack */
1376     printf( "\tpopl %%eax\n" );  /* Remove old cs and es from stack */
1377     printf( "\tpushw %d(%%ebx)\n", CONTEXTOFFSET(DS) ); /* Push new ds */
1378     printf( "\tpushw %d(%%ebx)\n", CONTEXTOFFSET(ES) ); /* Push new es */
1379     printf( "\tpushl %d(%%ebx)\n", CONTEXTOFFSET(EFL) );
1380     printf( "\tpopfl\n" );
1381     printf( "\tmovl %d(%%ebx),%%eax\n", CONTEXTOFFSET(EAX) );
1382     printf( "\tmovl %d(%%ebx),%%ebx\n", CONTEXTOFFSET(EBX) );
1383 }
1384
1385
1386 /*******************************************************************
1387  *         BuildCallFrom16Func
1388  *
1389  * Build a 16-bit-to-Wine callback function. The syntax of the function
1390  * profile is: type_xxxxx, where 'type' is one of 'regs', 'word' or
1391  * 'long' and each 'x' is an argument ('w'=word, 's'=signed word,
1392  * 'l'=long, 'p'=pointer).
1393  * For register functions, the arguments are ignored, but they are still
1394  * removed from the stack upon return.
1395  *
1396  * Stack layout upon entry to the callback function:
1397  *  ...           ...
1398  * (sp+18) word   first 16-bit arg
1399  * (sp+16) word   cs
1400  * (sp+14) word   ip
1401  * (sp+12) word   bp
1402  * (sp+8)  long   32-bit entry point
1403  * (sp+6)  word   high word of cs (always 0, used to store es)
1404  * (sp+4)  word   low word of cs of 16-bit entry point
1405  * (sp+2)  word   high word of ip (always 0, used to store ds)
1406  * (sp)    word   low word of ip of 16-bit entry point
1407  *
1408  */
1409 static void BuildCallFrom16Func( char *profile )
1410 {
1411     int argsize = 0;
1412     int short_ret = 0;
1413     int reg_func = 0;
1414     char *args = profile + 5;
1415
1416     /* Parse function type */
1417
1418     if (!strncmp( "word_", profile, 5 )) short_ret = 1;
1419     else if (!strncmp( "regs_", profile, 5 )) reg_func = 1;
1420     else if (strncmp( "long_", profile, 5 ))
1421     {
1422         fprintf( stderr, "Invalid function name '%s', ignored\n", profile );
1423         return;
1424     }
1425
1426     /* Function header */
1427
1428     printf( "/**********\n" );
1429     printf( " * " PREFIX "CallFrom16_%s\n", profile );
1430     printf( " **********/\n" );
1431     printf( "\t.align 4\n" );
1432     printf( "\t.globl " PREFIX "CallFrom16_%s\n\n", profile );
1433     printf( PREFIX "CallFrom16_%s:\n", profile );
1434
1435     /* Setup bp to point to its copy on the stack */
1436
1437     printf( "\tmovzwl %%sp,%%ebp\n" );
1438     printf( "\taddw $12,%%bp\n" );
1439
1440     /* Save 16-bit ds and es */
1441
1442     /* Stupid FreeBSD assembler doesn't know these either */
1443     /* printf( "\tmovw %%ds,-10(%%ebp)\n" ); */
1444     printf( "\t.byte 0x66,0x8c,0x5d,0xf6\n" );
1445     /* printf( "\tmovw %%es,-6(%%ebp)\n" ); */
1446     printf( "\t.byte 0x66,0x8c,0x45,0xfa\n" );
1447
1448     /* Restore 32-bit ds and es */
1449
1450     printf( "\tpushl $0x%04x%04x\n", WINE_DATA_SELECTOR, WINE_DATA_SELECTOR );
1451     printf( "\tpopw %%ds\n" );
1452     printf( "\tpopw %%es\n" );
1453
1454
1455     /* Save the 16-bit stack */
1456
1457     printf( "\tpushw " PREFIX "IF1632_Saved16_sp\n" );
1458     printf( "\tpushw " PREFIX "IF1632_Saved16_ss\n" );
1459 #ifdef __svr4__
1460     printf("\tdata16\n");
1461 #endif
1462     printf( "\tmovw %%ss," PREFIX "IF1632_Saved16_ss\n" );
1463     printf( "\tmovw %%sp," PREFIX "IF1632_Saved16_sp\n" );
1464
1465     /* Transfer the arguments */
1466
1467     if (reg_func) BuildContext();
1468     else if (*args) argsize = TransferArgs16To32( args );
1469
1470     /* Get the address of the API function */
1471
1472     printf( "\tmovl -4(%%ebp),%%eax\n" );
1473
1474     /* If necessary, save %edx over the API function address */
1475
1476     if (!reg_func && short_ret)
1477         printf( "\tmovl %%edx,-4(%%ebp)\n" );
1478
1479     /* Switch to the 32-bit stack */
1480
1481     printf( "\tmovl " PREFIX "IF1632_Saved32_esp,%%ebp\n" );
1482     printf( "\tpushw %%ds\n" );
1483     printf( "\tpopw %%ss\n" );
1484     printf( "\tleal -%d(%%ebp),%%esp\n",
1485             reg_func ? sizeof(struct sigcontext_struct) : 4 * strlen(args) );
1486
1487     /* Setup %ebp to point to the previous stack frame (built by CallTo16) */
1488
1489     printf( "\taddl $24,%%ebp\n" );
1490
1491     /* Print the debug information before the call */
1492
1493     if (debugging)
1494     {
1495         printf( "\tpushl %%eax\n" );
1496         printf( "\tpushl $Profile_%s\n", profile );
1497         printf( "\tpushl $%d\n", reg_func ? 2 : (short_ret ? 1 : 0) );
1498         printf( "\tcall " PREFIX "RELAY_DebugCallFrom16\n" );
1499         printf( "\tpopl %%eax\n" );
1500         printf( "\tpopl %%eax\n" );
1501         printf( "\tpopl %%eax\n" );
1502     }
1503
1504     /* Call the entry point */
1505
1506     printf( "\tcall %%eax\n" );
1507
1508     /* Print the debug information after the call */
1509
1510     if (debugging)
1511     {
1512         printf( "\tpushl %%eax\n" );
1513         printf( "\tpushl $%d\n", reg_func ? 2 : (short_ret ? 1 : 0) );
1514         printf( "\tcall " PREFIX "RELAY_DebugCallFrom16Ret\n" );
1515         printf( "\tpopl %%eax\n" );
1516         printf( "\tpopl %%eax\n" );
1517     }
1518
1519     /* Restore the 16-bit stack */
1520
1521 #ifdef __svr4__
1522     printf( "\tdata16\n");
1523 #endif
1524     printf( "\tmovw " PREFIX "IF1632_Saved16_ss,%%ss\n" );
1525     printf( "\tmovw " PREFIX "IF1632_Saved16_sp,%%sp\n" );
1526 #ifdef __svr4__
1527     printf( "\tdata16\n");
1528 #endif
1529     printf( "\tpopw " PREFIX "IF1632_Saved16_ss\n" );
1530 #ifdef __svr4__
1531     printf( "\tdata16\n");
1532 #endif
1533     printf( "\tpopw " PREFIX "IF1632_Saved16_sp\n" );
1534
1535     if (reg_func)
1536     {
1537         /* Restore registers from the context structure */
1538         RestoreContext();
1539         
1540         /* Calc the arguments size */
1541         while (*args)
1542         {
1543             switch(*args)
1544             {
1545             case 'w':
1546             case 's':
1547                 argsize += 2;
1548                 break;
1549             case 'p':
1550             case 'l':
1551                 argsize += 4;
1552                 break;
1553             default:
1554                 fprintf( stderr, "Unknown arg type '%c'\n", *args );
1555             }
1556             args++;
1557         }
1558
1559         /* Restore ds and es */
1560         printf( "\tpopw %%es\n" );
1561         printf( "\tpopw %%ds\n" );
1562
1563         /* Remove the entry point from the stack */
1564         /* (we don't use add to avoid modifying the carry flag) */
1565         printf( "\tpopl %%ebp\n" );
1566     }
1567     else
1568     {
1569         /* Restore ds and es */
1570         printf( "\tpopw %%bp\n" );       /* Remove ip */
1571         printf( "\tpopl %%ebp\n" );      /* Remove ds and cs */
1572         printf( "\tmovw %%bp,%%ds\n" );  /* Restore ds */
1573         printf( "\tpopw %%es\n" );       /* Restore es */
1574
1575         if (short_ret) printf( "\tpopl %%edx\n" );     /* Restore edx */
1576         else
1577         {
1578             /* Get the return value into dx:ax */
1579             printf( "\tpushl %%eax\n" );
1580             printf( "\tpopw %%ax\n" );
1581             printf( "\tpopw %%dx\n" );
1582             /* Remove API entry point */
1583             printf( "\taddl $4,%%esp\n" );
1584         }
1585     }
1586
1587     /* Restore bp */
1588
1589     printf( "\tpopw %%bp\n" );
1590
1591     /* Remove the arguments and return */
1592
1593     if (argsize)
1594     {
1595         printf( "\t.byte 0x66\n" );
1596         printf( "\tlret $%d\n", argsize );
1597     }
1598     else
1599     {
1600         printf( "\t.byte 0x66\n" );
1601         printf( "\tlret\n" );
1602     }
1603 }
1604
1605
1606 /*******************************************************************
1607  *         BuildCallTo16Func
1608  *
1609  * Build a Wine-to-16-bit callback function.
1610  *
1611  * Stack frame of the callback function:
1612  *  ...      ...
1613  * (ebp+24) arg2
1614  * (ebp+20) arg1
1615  * (ebp+16) 16-bit ds
1616  * (ebp+12) func to call
1617  * (ebp+8)  code selector
1618  * (ebp+4)  return address
1619  * (ebp)    previous ebp
1620  *
1621  * Prototypes for the CallTo16 functions:
1622  *   extern WORD CallTo16_word_xxx( FARPROC func, WORD ds, args... );
1623  *   extern LONG CallTo16_long_xxx( FARPROC func, WORD ds, args... );
1624  *   extern void CallTo16_regs_( FARPROC func, WORD ds, WORD es, WORD bp,
1625  *                               WORD ax, WORD bx, WORD cx, WORD dx,
1626  *                               WORD si, WORD di );
1627  */
1628 static void BuildCallTo16Func( char *profile )
1629 {
1630     int short_ret = 0;
1631     int reg_func = 0;
1632     char *args = profile + 5;
1633
1634     if (!strncmp( "word_", profile, 5 )) short_ret = 1;
1635     else if (!strncmp( "regs_", profile, 5 )) reg_func = short_ret = 1;
1636     else if (strncmp( "long_", profile, 5 ))
1637     {
1638         fprintf( stderr, "Invalid function name '%s', ignored\n", profile );
1639         return;
1640     }
1641
1642     /* Function header */
1643
1644     printf( "/**********\n" );
1645     printf( " * " PREFIX "CallTo16_%s\n", profile );
1646     printf( " **********/\n" );
1647     printf( "\t.align 4\n" );
1648     printf( "\t.globl " PREFIX "CallTo16_%s\n\n", profile );
1649     printf( PREFIX "CallTo16_%s:\n", profile );
1650
1651     /* Push code selector before return address to simulate a lcall */
1652
1653     printf( "\tpopl %%eax\n" );
1654     printf( "\tpushl $0x%04x\n", WINE_CODE_SELECTOR );
1655     printf( "\tpushl %%eax\n" );
1656
1657     /* Entry code */
1658
1659     printf( "\tpushl %%ebp\n" );
1660     printf( "\tmovl %%esp,%%ebp\n" );
1661
1662     /* Save the 32-bit registers */
1663
1664     printf( "\tpushl %%ebx\n" );
1665     printf( "\tpushl %%ecx\n" );
1666     printf( "\tpushl %%edx\n" );
1667     printf( "\tpushl %%esi\n" );
1668     printf( "\tpushl %%edi\n" );
1669
1670     /* Save the 32-bit stack */
1671
1672     printf( "\tpushl " PREFIX "IF1632_Saved32_esp\n" );
1673     printf( "\tmovl %%esp," PREFIX "IF1632_Saved32_esp\n" );
1674     printf( "\tmovl %%ebp,%%ebx\n" );
1675
1676     /* Print debugging info */
1677
1678     if (debugging)
1679     {
1680         /* Push the address of the first argument */
1681         printf( "\tmovl %%ebx,%%eax\n" );
1682         printf( "\taddl $12,%%eax\n" );
1683         printf( "\tpushl $%d\n", reg_func ? 8 : strlen(args) );
1684         printf( "\tpushl %%eax\n" );
1685         printf( "\tcall " PREFIX "RELAY_DebugCallTo16\n" );
1686         printf( "\tpopl %%eax\n" );
1687         printf( "\tpopl %%eax\n" );
1688     }
1689
1690     /* Switch to the 16-bit stack */
1691
1692 #ifdef __svr4__
1693     printf("\tdata16\n");
1694 #endif
1695     printf( "\tmovw " PREFIX "IF1632_Saved16_ss,%%ss\n" );
1696     printf( "\tmovw " PREFIX "IF1632_Saved16_sp,%%sp\n" );
1697
1698     /* Transfer the arguments */
1699
1700     if (reg_func)
1701     {
1702         /* Get the registers. ebx is handled later on. */
1703         printf( "\tpushw 20(%%ebx)\n" );
1704         printf( "\tpopw %%es\n" );
1705         printf( "\tmovl 24(%%ebx),%%ebp\n" );
1706         printf( "\tmovl 28(%%ebx),%%eax\n" );
1707         printf( "\tmovl 36(%%ebx),%%ecx\n" );
1708         printf( "\tmovl 40(%%ebx),%%edx\n" );
1709         printf( "\tmovl 44(%%ebx),%%esi\n" );
1710         printf( "\tmovl 48(%%ebx),%%edi\n" );
1711     }
1712     else  /* not a register function */
1713     {
1714         int pos = 20;  /* first argument position */
1715
1716         /* Make %bp point to the previous stackframe (built by CallFrom16) */
1717         printf( "\tmovw %%sp,%%bp\n" );
1718         printf( "\taddw $16,%%bp\n" );
1719
1720         while (*args)
1721         {
1722             switch(*args++)
1723             {
1724             case 'w': /* word */
1725                 printf( "\tpushw %d(%%ebx)\n", pos );
1726                 break;
1727             case 'l': /* long */
1728                 printf( "\tpushl %d(%%ebx)\n", pos );
1729                 break;
1730             }
1731             pos += 4;
1732         }
1733     }
1734
1735     /* Push the return address */
1736
1737     printf( "\tpushl " PREFIX "CALLTO16_RetAddr_%s\n",
1738             short_ret ? "word" : "long" );
1739
1740     /* Push the called routine address */
1741
1742     printf( "\tpushl 12(%%ebx)\n" );
1743
1744     /* Get the 16-bit ds */
1745
1746     if (reg_func)
1747     {
1748         printf( "\tpushw 16(%%ebx)\n" );
1749         printf( "\tmovl 32(%%ebx),%%ebx\n" ); /*Get ebx from the 32-bit stack*/
1750         printf( "\tpopw %%ds\n" );
1751     }
1752     else
1753     {
1754         /* Set ax equal to ds for window procedures */
1755         printf( "\tmovw 16(%%ebx),%%ax\n" );
1756 #ifdef __svr4__
1757         printf( "\tdata16\n");
1758 #endif
1759         printf( "\tmovw %%ax,%%ds\n" );
1760     }
1761
1762     /* Jump to the called routine */
1763
1764     printf( "\t.byte 0x66\n" );
1765     printf( "\tlret\n" );
1766 }
1767
1768
1769 /*******************************************************************
1770  *         BuildRet16Func
1771  *
1772  * Build the return code for 16-bit callbacks
1773  */
1774 static void BuildRet16Func()
1775 {
1776     printf( "\t.globl " PREFIX "CALLTO16_Ret_word\n" );
1777     printf( "\t.globl " PREFIX "CALLTO16_Ret_long\n" );
1778
1779     /* Put return value into eax */
1780
1781     printf( PREFIX "CALLTO16_Ret_long:\n" );
1782     printf( "\tpushw %%dx\n" );
1783     printf( "\tpushw %%ax\n" );
1784     printf( "\tpopl %%eax\n" );
1785     printf( PREFIX "CALLTO16_Ret_word:\n" );
1786
1787     /* Restore 32-bit segment registers */
1788
1789     printf( "\tmovw $0x%04x,%%bx\n", WINE_DATA_SELECTOR );
1790 #ifdef __svr4__
1791     printf( "\tdata16\n");
1792 #endif
1793     printf( "\tmovw %%bx,%%ds\n" );
1794 #ifdef __svr4__
1795     printf( "\tdata16\n");
1796 #endif
1797     printf( "\tmovw %%bx,%%es\n" );
1798 #ifdef __svr4__
1799     printf( "\tdata16\n");
1800 #endif
1801     printf( "\tmovw %%bx,%%ss\n" );
1802
1803     /* Restore the 32-bit stack */
1804
1805     printf( "\tmovl " PREFIX "IF1632_Saved32_esp,%%esp\n" );
1806     printf( "\tpopl " PREFIX "IF1632_Saved32_esp\n" );
1807
1808     /* Restore the 32-bit registers */
1809
1810     printf( "\tpopl %%edi\n" );
1811     printf( "\tpopl %%esi\n" );
1812     printf( "\tpopl %%edx\n" );
1813     printf( "\tpopl %%ecx\n" );
1814     printf( "\tpopl %%ebx\n" );
1815
1816     /* Return to caller */
1817
1818     printf( "\tpopl %%ebp\n" );
1819     printf( "\tlret\n" );
1820
1821     /* Declare the return address variables */
1822
1823     printf( "\t.data\n" );
1824     printf( "\t.globl " PREFIX "CALLTO16_RetAddr_word\n" );
1825     printf( "\t.globl " PREFIX "CALLTO16_RetAddr_long\n" );
1826     printf( PREFIX "CALLTO16_RetAddr_word:\t.long 0\n" );
1827     printf( PREFIX "CALLTO16_RetAddr_long:\t.long 0\n" );
1828     printf( "\t.text\n" );
1829 }
1830
1831
1832 /*******************************************************************
1833  *         BuildCallFrom32Func
1834  *
1835  * Build a 32-bit-to-Wine call-back function.
1836  * 'args' is the number of dword arguments.
1837  *
1838  * Stack layout:
1839  *   ...     ...
1840  * (ebp+12)  arg2
1841  * (ebp+8)   arg1
1842  * (ebp+4)   ret addr
1843  * (ebp)     ebp
1844  * (ebp-4)   func name
1845  * (ebp-8)   entry point
1846  */
1847 static void BuildCallFrom32Func( int args )
1848 {
1849     /* Function header */
1850
1851     printf( "/**********\n" );
1852     printf( " * " PREFIX "CallFrom32_%d\n", args );
1853     printf( " **********/\n" );
1854     printf( "\t.align 4\n" );
1855     printf( "\t.globl " PREFIX "CallFrom32_%d\n\n", args );
1856     printf( PREFIX "CallFrom32_%d:\n", args );
1857
1858     /* Entry code */
1859
1860     printf( "\tleal 8(%%esp),%%ebp\n" );
1861
1862     /* Print the debugging info */
1863
1864     if (debugging)
1865     {
1866         printf( "\tpushl $%d\n", args );
1867         printf( "\tcall " PREFIX "RELAY_DebugCallFrom32\n" );
1868         printf( "\tadd $4, %%esp\n" );
1869     }
1870
1871     /* Transfer the arguments */
1872
1873     if (args)
1874     {
1875         int i;
1876         for (i = args; i > 0; i--) printf( "\tpushl %d(%%ebp)\n", 4 * i + 4 );
1877     }
1878     else
1879     {
1880         /* Push the address of the arguments. The called function will */
1881         /* ignore this if it really takes no arguments. */
1882         printf( "\tleal 8(%%ebp),%%eax\n" );
1883         printf( "\tpushl %%eax\n" );
1884     }
1885
1886     /* Call the function */
1887
1888     printf( "\tcall -8(%%ebp)\n" );
1889
1890     /* Print the debugging info */
1891
1892     if (debugging)
1893     {
1894         printf( "\tadd $%d,%%esp\n", args ? (args * 4) : 4 );
1895         printf( "\tpushl %%eax\n" );
1896         printf( "\tcall " PREFIX "RELAY_DebugCallFrom32Ret\n" );
1897         printf( "\tpopl %%eax\n" );
1898     }
1899
1900     printf( "\tmovl %%ebp,%%esp\n" );
1901     printf( "\tpopl %%ebp\n" );
1902
1903     /* Return, removing arguments */
1904
1905     if (args) printf( "\tret $%d\n", args * 4 );
1906     else printf( "\tret\n" );
1907 }
1908
1909
1910 /*******************************************************************
1911  *         BuildCallTo32Func
1912  *
1913  * Build a Wine-to-32-bit callback function.
1914  *
1915  * Stack frame of the callback function:
1916  *  ...      ...
1917  * (ebp+16) arg2
1918  * (ebp+12) arg1
1919  * (ebp+8)  func to call
1920  * (ebp+4)  return address
1921  * (ebp)    previous ebp
1922  *
1923  * Prototype for the CallTo32 functions:
1924  *   extern LONG CallTo32_nn( FARPROC func, args... );
1925  */
1926 static void BuildCallTo32Func( int args )
1927 {
1928     /* Function header */
1929
1930     printf( "/**********\n" );
1931     printf( " * " PREFIX "CallTo32_%d\n", args );
1932     printf( " **********/\n" );
1933     printf( "\t.align 4\n" );
1934     printf( "\t.globl " PREFIX "CallTo32_%d\n\n", args );
1935     printf( PREFIX "CallTo32_%d:\n", args );
1936
1937     /* Entry code */
1938
1939     printf( "\tpushl %%ebp\n" );
1940     printf( "\tmovl %%esp,%%ebp\n" );
1941
1942     /* Transfer arguments */
1943
1944     if (args)
1945     {
1946         int i;
1947         for (i = args; i > 0; i--) printf( "\tpushl %d(%%ebp)\n", 4 * i + 8 );
1948     }
1949
1950     /* Print the debugging output */
1951
1952     if (debugging)
1953     {
1954         printf( "\tpushl $%d\n", args );
1955         printf( "\tpushl 8(%%ebp)\n" );
1956         printf( "\tcall " PREFIX "RELAY_DebugCallTo32\n" );
1957         printf( "\taddl $8,%%esp\n" );
1958     }
1959
1960     /* Call the function */
1961
1962     printf( "\tcall 8(%%ebp)\n" );
1963
1964     /* Return to Wine */
1965
1966     printf( "\tmovl %%ebp,%%esp\n" );
1967     printf( "\tpopl %%ebp\n" );
1968     printf( "\tret\n" );
1969 }
1970
1971
1972 static void usage(void)
1973 {
1974     fprintf(stderr, "usage: build -spec SPECNAMES\n"
1975                     "       build -callfrom16 FUNCTION_PROFILES\n"
1976                     "       build -callto16 FUNCTION_PROFILES\n"
1977                     "       build -callfrom32 FUNCTION_PROFILES\n"
1978                     "       build -callto32 FUNCTION_PROFILES\n" );
1979     exit(1);
1980 }
1981
1982
1983 int main(int argc, char **argv)
1984 {
1985     int i;
1986
1987     if (argc <= 2) usage();
1988
1989     if (!strcmp( argv[1], "-spec" ))
1990     {
1991         for (i = 2; i < argc; i++) BuildSpecFiles( argv[i] );
1992     }
1993     else if (!strcmp( argv[1], "-callfrom16" ))  /* 16-bit-to-Wine callbacks */
1994     {
1995         /* File header */
1996
1997         printf( "/* File generated automatically. Do not edit! */\n\n" );
1998         printf( "\t.text\n" );
1999
2000         /* Build the 32-bit large stack callback */
2001
2002         BuildCall32LargeStack();
2003
2004         /* Build the callback functions */
2005
2006         for (i = 2; i < argc; i++) BuildCallFrom16Func( argv[i] );
2007
2008         /* Output the argument debugging strings */
2009
2010         if (debugging)
2011         {
2012             printf( "/* Argument strings */\n" );
2013             for (i = 2; i < argc; i++)
2014             {
2015                 printf( "Profile_%s:\n", argv[i] );
2016                 printf( "\t.ascii \"%s\\0\"\n", argv[i] + 5 );
2017             }
2018         }
2019     }
2020     else if (!strcmp( argv[1], "-callto16" ))  /* Wine-to-16-bit callbacks */
2021     {
2022         /* File header */
2023
2024         printf( "/* File generated automatically. Do not edit! */\n\n" );
2025         printf( "\t.text\n" );
2026         printf( "\t.globl " PREFIX "CALLTO16_Start\n" );
2027         printf( PREFIX "CALLTO16_Start:\n" );
2028
2029         /* Build the callback functions */
2030
2031         for (i = 2; i < argc; i++) BuildCallTo16Func( argv[i] );
2032
2033         /* Output the 16-bit return code */
2034
2035         BuildRet16Func();
2036
2037         printf( "\t.globl " PREFIX "CALLTO16_End\n" );
2038         printf( PREFIX "CALLTO16_End:\n" );
2039     }
2040     else if (!strcmp( argv[1], "-callfrom32" ))  /* 32-bit-to-Wine callbacks */
2041     {
2042         /* File header */
2043
2044         printf( "/* File generated automatically. Do not edit! */\n\n" );
2045         printf( "\t.text\n" );
2046
2047         /* Build the callback functions */
2048
2049         for (i = 2; i < argc; i++) BuildCallFrom32Func( atoi(argv[i]) );
2050     }
2051     else if (!strcmp( argv[1], "-callto32" ))  /* Wine-to-32-bit callbacks */
2052     {
2053         /* File header */
2054
2055         printf( "/* File generated automatically. Do not edit! */\n\n" );
2056         printf( "\t.text\n" );
2057
2058         /* Build the callback functions */
2059
2060         for (i = 2; i < argc; i++) BuildCallTo32Func( atoi(argv[i]) );
2061     }
2062     else usage();
2063
2064     return 0;
2065 }
2066
2067 #endif  /* WINELIB */