parser.c 35.7 KB
Newer Older
1 2 3 4 5
/*
 * Spec file parser
 *
 * Copyright 1993 Robert J. Amstadt
 * Copyright 1995 Martin von Loewis
6
 * Copyright 1995, 1996, 1997, 2004 Alexandre Julliard
7 8
 * Copyright 1997 Eric Youngdale
 * Copyright 1999 Ulrich Weigand
9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
22
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 24
 */

25 26
#include "config.h"

27 28
#include <assert.h>
#include <ctype.h>
29
#include <stdarg.h>
30 31 32 33 34 35 36 37 38
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "build.h"

int current_line = 0;

static char ParseBuffer[512];
39
static char TokenBuffer[512];
40 41 42
static char *ParseNext = ParseBuffer;
static FILE *input_file;

43 44 45
static const char *separator_chars;
static const char *comment_chars;

46
/* valid characters in ordinal names */
47
static const char valid_ordname_chars[] = "/$:-_@?<>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
48

49 50
static const char * const TypeNames[TYPE_NBTYPES] =
{
51
    "variable",     /* TYPE_VARIABLE */
52 53 54 55 56 57
    "pascal",       /* TYPE_PASCAL */
    "equate",       /* TYPE_ABS */
    "stub",         /* TYPE_STUB */
    "stdcall",      /* TYPE_STDCALL */
    "cdecl",        /* TYPE_CDECL */
    "varargs",      /* TYPE_VARARGS */
58
    "extern"        /* TYPE_EXTERN */
59 60
};

61 62 63
static const char * const FlagNames[] =
{
    "norelay",     /* FLAG_NORELAY */
64
    "noname",      /* FLAG_NONAME */
65
    "ret16",       /* FLAG_RET16 */
66
    "ret64",       /* FLAG_RET64 */
67
    "register",    /* FLAG_REGISTER */
68
    "private",     /* FLAG_PRIVATE */
69
    "ordinal",     /* FLAG_ORDINAL */
70
    "thiscall",    /* FLAG_THISCALL */
71
    "fastcall",    /* FLAG_FASTCALL */
72
    "syscall",     /* FLAG_SYSCALL */
73
    "import",      /* FLAG_IMPORT */
74 75
    NULL
};
76

77 78 79 80 81 82 83 84 85 86
static const char * const ArgNames[ARG_MAXARG + 1] =
{
    "word",    /* ARG_WORD */
    "s_word",  /* ARG_SWORD */
    "segptr",  /* ARG_SEGPTR */
    "segstr",  /* ARG_SEGSTR */
    "long",    /* ARG_LONG */
    "ptr",     /* ARG_PTR */
    "str",     /* ARG_STR */
    "wstr",    /* ARG_WSTR */
87 88 89
    "int64",   /* ARG_INT64 */
    "int128",  /* ARG_INT128 */
    "float",   /* ARG_FLOAT */
90 91 92
    "double"   /* ARG_DOUBLE */
};

93
static int IsNumberString(const char *s)
94 95 96 97 98
{
    while (*s) if (!isdigit(*s++)) return 0;
    return 1;
}

99
static inline int is_token_separator( char ch )
100
{
101 102 103
    return strchr( separator_chars, ch ) != NULL;
}

104
static inline int is_token_comment( char ch )
105 106
{
    return strchr( comment_chars, ch ) != NULL;
107 108
}

109 110 111 112 113 114 115 116 117
/* get the next line from the input file, or return 0 if at eof */
static int get_next_line(void)
{
    ParseNext = ParseBuffer;
    current_line++;
    return (fgets(ParseBuffer, sizeof(ParseBuffer), input_file) != NULL);
}

static const char * GetToken( int allow_eol )
118
{
119
    char *p;
120
    char *token = TokenBuffer;
121

122 123 124 125 126
    for (;;)
    {
        /* remove initial white space */
        p = ParseNext;
        while (isspace(*p)) p++;
127

128 129 130 131 132 133 134 135 136 137 138
        if (*p == '\\' && p[1] == '\n')  /* line continuation */
        {
            if (!get_next_line())
            {
                if (!allow_eol) error( "Unexpected end of file\n" );
                return NULL;
            }
        }
        else break;
    }

139
    if ((*p == '\0') || is_token_comment(*p))
140 141 142 143
    {
        if (!allow_eol) error( "Declaration not terminated properly\n" );
        return NULL;
    }
144

145 146 147
    /*
     * Find end of token.
     */
148 149 150 151 152 153 154 155 156 157 158
    if (is_token_separator(*p))
    {
        /* a separator is always a complete token */
        *token++ = *p++;
    }
    else while (*p != '\0' && !is_token_separator(*p) && !isspace(*p))
    {
        if (*p == '\\') p++;
        if (*p) *token++ = *p++;
    }
    *token = '\0';
159
    ParseNext = p;
160
    return TokenBuffer;
161 162 163
}


164 165
static ORDDEF *add_entry_point( DLLSPEC *spec )
{
166 167
    ORDDEF *ret;

168 169 170 171 172 173
    if (spec->nb_entry_points == spec->alloc_entry_points)
    {
        spec->alloc_entry_points += 128;
        spec->entry_points = xrealloc( spec->entry_points,
                                       spec->alloc_entry_points * sizeof(*spec->entry_points) );
    }
174 175 176
    ret = &spec->entry_points[spec->nb_entry_points++];
    memset( ret, 0, sizeof(*ret) );
    return ret;
177 178
}

179
/*******************************************************************
180
 *         parse_spec_variable
181
 *
182
 * Parse a variable definition in a .spec file.
183
 */
184
static int parse_spec_variable( ORDDEF *odp, DLLSPEC *spec )
185 186
{
    char *endptr;
187
    unsigned int *value_array;
188 189
    int n_values;
    int value_array_size;
190
    const char *token;
191

192
    if (spec->type == SPEC_WIN32)
193 194 195 196
    {
        error( "'variable' not supported in Win32, use 'extern' instead\n" );
        return 0;
    }
197

198 199 200 201 202 203
    if (!(token = GetToken(0))) return 0;
    if (*token != '(')
    {
        error( "Expected '(' got '%s'\n", token );
        return 0;
    }
204 205 206 207

    n_values = 0;
    value_array_size = 25;
    value_array = xmalloc(sizeof(*value_array) * value_array_size);
208

209
    for (;;)
210
    {
211 212 213 214 215
        if (!(token = GetToken(0)))
        {
            free( value_array );
            return 0;
        }
216 217 218
	if (*token == ')')
	    break;

219
	value_array[n_values++] = strtoul(token, &endptr, 0);
220 221 222
	if (n_values == value_array_size)
	{
	    value_array_size += 25;
223
	    value_array = xrealloc(value_array,
224 225
				   sizeof(*value_array) * value_array_size);
	}
226

227
	if (endptr == NULL || *endptr != '\0')
228 229 230 231 232
        {
            error( "Expected number value, got '%s'\n", token );
            free( value_array );
            return 0;
        }
233 234 235 236
    }

    odp->u.var.n_values = n_values;
    odp->u.var.values = xrealloc(value_array, sizeof(*value_array) * n_values);
237
    return 1;
238 239 240 241
}


/*******************************************************************
242
 *         parse_spec_arguments
243
 *
244
 * Parse the arguments of an entry point.
245
 */
246
static int parse_spec_arguments( ORDDEF *odp, DLLSPEC *spec, int optional )
247
{
248
    const char *token;
249
    unsigned int i, arg;
250
    int is_win32 = (spec->type == SPEC_WIN32) || (odp->flags & FLAG_EXPORT32);
251

252
    if (!(token = GetToken( optional ))) return optional;
253 254 255 256 257
    if (*token != '(')
    {
        error( "Expected '(' got '%s'\n", token );
        return 0;
    }
258

259 260
    odp->u.func.nb_args = 0;
    for (i = 0; i < MAX_ARGUMENTS; i++)
261
    {
262
        if (!(token = GetToken(0))) return 0;
263 264 265
	if (*token == ')')
	    break;

266 267 268 269
        for (arg = 0; arg <= ARG_MAXARG; arg++)
            if (!strcmp( ArgNames[arg], token )) break;

        if (arg > ARG_MAXARG)
270 271 272 273
        {
            error( "Unknown argument type '%s'\n", token );
            return 0;
        }
274
        if (is_win32) switch (arg)
275
        {
276 277 278 279 280 281
        case ARG_WORD:
        case ARG_SWORD:
        case ARG_SEGPTR:
        case ARG_SEGSTR:
            error( "Argument type '%s' only allowed for Win16\n", token );
            return 0;
282
        }
283
        odp->u.func.args[i] = arg;
284
    }
285
    if (*token != ')')
286 287 288 289
    {
        error( "Too many arguments\n" );
        return 0;
    }
290

291
    odp->u.func.nb_args = i;
292
    if (odp->flags & FLAG_THISCALL)
293
    {
294 295 296 297 298 299 300 301 302 303
        if (odp->type != TYPE_STDCALL)
        {
            error( "A thiscall function must use the stdcall convention\n" );
            return 0;
        }
        if (!i || odp->u.func.args[0] != ARG_PTR)
        {
            error( "First argument of a thiscall function must be a pointer\n" );
            return 0;
        }
304
    }
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
    if (odp->flags & FLAG_FASTCALL)
    {
        if (odp->type != TYPE_STDCALL)
        {
            error( "A fastcall function must use the stdcall convention\n" );
            return 0;
        }
        if (!i || (odp->u.func.args[0] != ARG_PTR && odp->u.func.args[0] != ARG_LONG))
        {
            error( "First argument of a fastcall function must be a pointer or integer\n" );
            return 0;
        }
        if (i > 1 && odp->u.func.args[1] != ARG_PTR && odp->u.func.args[1] != ARG_LONG)
        {
            error( "Second argument of a fastcall function must be a pointer or integer\n" );
            return 0;
        }
    }
323 324
    if (odp->flags & FLAG_SYSCALL)
    {
325
        if (odp->type != TYPE_STDCALL && odp->type != TYPE_CDECL)
326
        {
327
            error( "A syscall function must use either the stdcall or the cdecl convention\n" );
328 329 330
            return 0;
        }
    }
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
    return 1;
}


/*******************************************************************
 *         parse_spec_export
 *
 * Parse an exported function definition in a .spec file.
 */
static int parse_spec_export( ORDDEF *odp, DLLSPEC *spec )
{
    const char *token;
    int is_win32 = (spec->type == SPEC_WIN32) || (odp->flags & FLAG_EXPORT32);

    if (!is_win32 && odp->type == TYPE_STDCALL)
    {
        error( "'stdcall' not supported for Win16\n" );
        return 0;
    }
    if (is_win32 && odp->type == TYPE_PASCAL)
    {
        error( "'pascal' not supported for Win32\n" );
        return 0;
    }

    if (!parse_spec_arguments( odp, spec, 0 )) return 0;

    if (odp->type == TYPE_VARARGS)
        odp->flags |= FLAG_NORELAY;  /* no relay debug possible for varags entry point */
360

361
    if (target.cpu != CPU_i386)
362
        odp->flags &= ~(FLAG_THISCALL | FLAG_FASTCALL);
363

364
    if (!(token = GetToken(1)))
365
    {
366 367 368 369 370 371
        if (!strcmp( odp->name, "@" ))
        {
            error( "Missing handler name for anonymous function\n" );
            return 0;
        }
        odp->link_name = xstrdup( odp->name );
372
    }
373 374 375 376 377
    else
    {
        odp->link_name = xstrdup( token );
        if (strchr( odp->link_name, '.' ))
        {
378
            if (!is_win32)
379 380 381 382 383 384 385 386
            {
                error( "Forwarded functions not supported for Win16\n" );
                return 0;
            }
            odp->flags |= FLAG_FORWARD;
        }
    }
    return 1;
387 388 389 390
}


/*******************************************************************
391
 *         parse_spec_equate
392
 *
393
 * Parse an 'equate' definition in a .spec file.
394
 */
395
static int parse_spec_equate( ORDDEF *odp, DLLSPEC *spec )
396 397
{
    char *endptr;
398 399
    int value;
    const char *token;
400

401
    if (spec->type == SPEC_WIN32)
402 403 404 405 406 407 408 409 410 411 412
    {
        error( "'equate' not supported for Win32\n" );
        return 0;
    }
    if (!(token = GetToken(0))) return 0;
    value = strtol(token, &endptr, 0);
    if (endptr == NULL || *endptr != '\0')
    {
        error( "Expected number value, got '%s'\n", token );
        return 0;
    }
413 414 415 416 417
    if (value < -0x8000 || value > 0xffff)
    {
        error( "Value %d for absolute symbol doesn't fit in 16 bits\n", value );
        value = 0;
    }
418
    odp->u.abs.value = value;
419
    return 1;
420 421 422 423
}


/*******************************************************************
424
 *         parse_spec_stub
425
 *
426
 * Parse a 'stub' definition in a .spec file
427
 */
428
static int parse_spec_stub( ORDDEF *odp, DLLSPEC *spec )
429
{
430
    odp->u.func.nb_args = -1;
431
    odp->link_name = xstrdup("");
432 433

    return parse_spec_arguments( odp, spec, 1 );
434 435 436 437
}


/*******************************************************************
438
 *         parse_spec_extern
439
 *
440
 * Parse an 'extern' definition in a .spec file.
441
 */
442
static int parse_spec_extern( ORDDEF *odp, DLLSPEC *spec )
443
{
444 445
    const char *token;

446
    if (spec->type == SPEC_WIN16)
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
    {
        error( "'extern' not supported for Win16, use 'variable' instead\n" );
        return 0;
    }
    if (!(token = GetToken(1)))
    {
        if (!strcmp( odp->name, "@" ))
        {
            error( "Missing handler name for anonymous extern\n" );
            return 0;
        }
        odp->link_name = xstrdup( odp->name );
    }
    else
    {
        odp->link_name = xstrdup( token );
        if (strchr( odp->link_name, '.' )) odp->flags |= FLAG_FORWARD;
    }
    return 1;
466 467 468
}


469
/*******************************************************************
470
 *         parse_spec_flags
471
 *
472
 * Parse the optional flags for an entry point in a .spec file.
473
 */
474
static const char *parse_spec_flags( DLLSPEC *spec, ORDDEF *odp, const char *token )
475
{
476
    unsigned int i, cpu_mask = 0;
477 478 479

    do
    {
480
        token++;
481
        if (!strncmp( token, "arch=", 5))
482
        {
483 484 485 486
            char *args = xstrdup( token + 5 );
            char *cpu_name = strtok( args, "," );
            while (cpu_name)
            {
487
                if (!strcmp( cpu_name, "win32" ))
488 489 490 491 492 493
                {
                    if (spec->type == SPEC_WIN32)
                        odp->flags |= FLAG_CPU_WIN32;
                    else
                        odp->flags |= FLAG_EXPORT32;
                }
494 495 496
                else if (!strcmp( cpu_name, "win64" ))
                    odp->flags |= FLAG_CPU_WIN64;
                else
497
                {
498
                    int cpu = get_cpu_from_name( cpu_name + (cpu_name[0] == '!') );
499 500 501 502 503
                    if (cpu == -1)
                    {
                        error( "Unknown architecture '%s'\n", cpu_name );
                        return NULL;
                    }
504 505
                    if (cpu_name[0] == '!') cpu_mask |= FLAG_CPU( cpu );
                    else odp->flags |= FLAG_CPU( cpu );
506 507 508 509 510 511 512
                }
                cpu_name = strtok( NULL, "," );
            }
            free( args );
        }
        else if (!strcmp( token, "i386" ))  /* backwards compatibility */
        {
513
            odp->flags |= FLAG_CPU(CPU_i386);
514 515 516 517 518 519 520 521 522 523
        }
        else
        {
            for (i = 0; FlagNames[i]; i++)
                if (!strcmp( FlagNames[i], token )) break;
            if (!FlagNames[i])
            {
                error( "Unknown flag '%s'\n", token );
                return NULL;
            }
524 525 526 527 528 529 530 531
            switch (1 << i)
            {
            case FLAG_RET16:
            case FLAG_REGISTER:
                if (spec->type == SPEC_WIN32)
                    error( "Flag '%s' is not supported in Win32\n", FlagNames[i] );
                break;
            case FLAG_RET64:
532
            case FLAG_THISCALL:
533
            case FLAG_FASTCALL:
534 535 536 537
                if (spec->type == SPEC_WIN16)
                    error( "Flag '%s' is not supported in Win16\n", FlagNames[i] );
                break;
            }
538
            odp->flags |= 1 << i;
539
        }
540
        token = GetToken(0);
541
    } while (token && *token == '-');
542

543
    if (cpu_mask) odp->flags |= FLAG_CPU_MASK & ~cpu_mask;
544 545 546
    return token;
}

547

548
/*******************************************************************
549
 *         parse_spec_ordinal
550
 *
551
 * Parse an ordinal definition in a .spec file.
552
 */
553
static int parse_spec_ordinal( int ordinal, DLLSPEC *spec )
554
{
555
    const char *token;
556
    size_t len;
557
    ORDDEF *odp = add_entry_point( spec );
558

559
    if (!(token = GetToken(0))) goto error;
560 561 562 563 564 565

    for (odp->type = 0; odp->type < TYPE_NBTYPES; odp->type++)
        if (TypeNames[odp->type] && !strcmp( token, TypeNames[odp->type] ))
            break;

    if (odp->type >= TYPE_NBTYPES)
566
    {
567 568 569 570 571 572 573 574 575 576
        if (!strcmp( token, "thiscall" )) /* for backwards compatibility */
        {
            odp->type = TYPE_STDCALL;
            odp->flags |= FLAG_THISCALL;
        }
        else
        {
            error( "Expected type after ordinal, found '%s' instead\n", token );
            goto error;
        }
577
    }
578

579
    if (!(token = GetToken(0))) goto error;
580
    if (*token == '-' && !(token = parse_spec_flags( spec, odp, token ))) goto error;
581 582 583 584 585 586

    if (ordinal == -1 && spec->type != SPEC_WIN32 && !(odp->flags & FLAG_EXPORT32))
    {
        error( "'@' ordinals not supported for Win16\n" );
        goto error;
    }
587

588
    odp->name = xstrdup( token );
589 590 591
    odp->lineno = current_line;
    odp->ordinal = ordinal;

592 593 594 595 596 597 598
    len = strspn( odp->name, valid_ordname_chars );
    if (len < strlen( odp->name ))
    {
        error( "Character '%c' is not allowed in exported name '%s'\n", odp->name[len], odp->name );
        goto error;
    }

599 600
    switch(odp->type)
    {
601
    case TYPE_VARIABLE:
602
        if (!parse_spec_variable( odp, spec )) goto error;
603 604 605 606 607
        break;
    case TYPE_PASCAL:
    case TYPE_STDCALL:
    case TYPE_VARARGS:
    case TYPE_CDECL:
608
        if (!parse_spec_export( odp, spec )) goto error;
609 610
        break;
    case TYPE_ABS:
611
        if (!parse_spec_equate( odp, spec )) goto error;
612 613
        break;
    case TYPE_STUB:
614
        if (!parse_spec_stub( odp, spec )) goto error;
615 616
        break;
    case TYPE_EXTERN:
617
        if (!parse_spec_extern( odp, spec )) goto error;
618 619 620 621 622
        break;
    default:
        assert( 0 );
    }

623
    if ((odp->flags & FLAG_CPU_MASK) && !(odp->flags & FLAG_CPU(target.cpu)))
624
    {
625
        /* ignore this entry point */
626
        spec->nb_entry_points--;
627
        return 1;
628 629
    }

630 631 632 633 634 635
    if (data_only && !(odp->flags & FLAG_FORWARD))
    {
        error( "Only forwarded entry points are allowed in data-only mode\n" );
        goto error;
    }

636 637
    if (ordinal != -1)
    {
638 639 640 641 642 643 644 645 646 647
        if (!ordinal)
        {
            error( "Ordinal 0 is not valid\n" );
            goto error;
        }
        if (ordinal >= MAX_ORDINALS)
        {
            error( "Ordinal number %d too large\n", ordinal );
            goto error;
        }
648 649
        if (ordinal > spec->limit) spec->limit = ordinal;
        if (ordinal < spec->base) spec->base = ordinal;
650 651 652
        odp->ordinal = ordinal;
    }

653 654 655 656
    if (odp->type == TYPE_STDCALL && !(odp->flags & FLAG_PRIVATE))
    {
        if (!strcmp( odp->name, "DllRegisterServer" ) ||
            !strcmp( odp->name, "DllUnregisterServer" ) ||
657
            !strcmp( odp->name, "DllMain" ) ||
658
            !strcmp( odp->name, "DllGetClassObject" ) ||
659 660
            !strcmp( odp->name, "DllGetVersion" ) ||
            !strcmp( odp->name, "DllInstall" ) ||
661 662 663
            !strcmp( odp->name, "DllCanUnloadNow" ))
        {
            warning( "Function %s should be marked private\n", odp->name );
664 665 666
            if (strcmp( odp->name, odp->link_name ))
                warning( "Function %s should not use a different internal name (%s)\n",
                         odp->name, odp->link_name );
667 668 669
        }
    }

670
    if (!strcmp( odp->name, "@" ) || odp->flags & (FLAG_NONAME | FLAG_ORDINAL))
671 672
    {
        if (ordinal == -1)
673
        {
674 675 676 677
            if (!strcmp( odp->name, "@" ))
                error( "Nameless function needs an explicit ordinal number\n" );
            else
                error( "Function imported by ordinal needs an explicit ordinal number\n" );
678 679
            goto error;
        }
680
        if (spec->type != SPEC_WIN32)
681 682 683 684
        {
            error( "Nameless functions not supported for Win16\n" );
            goto error;
        }
685 686 687 688 689 690 691 692 693 694
        if (!strcmp( odp->name, "@" ))
        {
            free( odp->name );
            odp->name = NULL;
        }
        else if (!(odp->flags & FLAG_ORDINAL))  /* -ordinal only affects the import library */
        {
            odp->export_name = odp->name;
            odp->name = NULL;
        }
695
    }
696 697 698
    return 1;

error:
699
    spec->nb_entry_points--;
700 701
    free( odp->name );
    return 0;
702 703 704
}


705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
static unsigned int apiset_hash_len( const char *str )
{
    return strrchr( str, '-' ) - str;
}

static unsigned int apiset_hash( const char *str )
{
    unsigned int ret = 0, len = apiset_hash_len( str );
    while (len--) ret = ret * apiset_hash_factor + *str++;
    return ret;
}

static unsigned int apiset_add_str( struct apiset *apiset, const char *str, unsigned int len )
{
    char *ret;

    if (!apiset->strings || !(ret = strstr( apiset->strings, str )))
    {
        if (apiset->str_pos + len >= apiset->str_size)
        {
            apiset->str_size = max( apiset->str_size * 2, 1024 );
            apiset->strings = xrealloc( apiset->strings, apiset->str_size );
        }
        ret = apiset->strings + apiset->str_pos;
        memcpy( ret, str, len );
        ret[len] = 0;
        apiset->str_pos += len;
    }
    return ret - apiset->strings;
}

static void add_apiset( struct apiset *apiset, const char *api )
{
    struct apiset_entry *entry;

    if (apiset->count == apiset->size)
    {
        apiset->size = max( apiset->size * 2, 64 );
        apiset->entries = xrealloc( apiset->entries, apiset->size * sizeof(*apiset->entries) );
    }
    entry = &apiset->entries[apiset->count++];
    entry->name_len = strlen( api );
    entry->name_off = apiset_add_str( apiset, api, entry->name_len );
    entry->hash = apiset_hash( api );
    entry->hash_len = apiset_hash_len( api );
    entry->val_count = 0;
}

static void add_apiset_value( struct apiset *apiset, const char *value )
{
    struct apiset_entry *entry = &apiset->entries[apiset->count - 1];

    if (entry->val_count < ARRAY_SIZE(entry->values) - 1)
    {
        struct apiset_value *val = &entry->values[entry->val_count++];
        char *sep = strchr( value, ':' );

        if (sep)
        {
            val->name_len = sep - value;
            val->name_off = apiset_add_str( apiset, value, val->name_len );
            val->val_len = strlen( sep + 1 );
            val->val_off = apiset_add_str( apiset, sep + 1, val->val_len );
        }
        else
        {
            val->name_len = val->name_off = 0;
            val->val_len = strlen( value );
            val->val_off = apiset_add_str( apiset, value, val->val_len );
        }
    }
    else error( "Too many values for api '%.*s'\n", entry->name_len, apiset->strings + entry->name_off );
}

/*******************************************************************
 *         parse_spec_apiset
 */
static int parse_spec_apiset( DLLSPEC *spec )
{
    struct apiset_entry *entry;
    const char *token;
    unsigned int i, hash;

    if (!data_only)
    {
        error( "Apiset definitions are only allowed in data-only mode\n" );
        return 0;
    }

    if (!(token = GetToken(0))) return 0;

    if (!strncmp( token, "api-", 4 ) && !strncmp( token, "ext-", 4 ))
    {
        error( "Unrecognized API set name '%s'\n", token );
        return 0;
    }

    hash = apiset_hash( token );
    for (i = 0, entry = spec->apiset.entries; i < spec->apiset.count; i++, entry++)
    {
        if (entry->name_len == strlen( token ) &&
            !strncmp( spec->apiset.strings + entry->name_off, token, entry->name_len ))
        {
            error( "Duplicate API set '%s'\n", token );
            return 0;
        }
        if (entry->hash == hash)
        {
            error( "Duplicate hash code '%.*s' and '%s'\n",
                   entry->name_len, spec->apiset.strings + entry->name_off, token );
            return 0;
        }
    }
    add_apiset( &spec->apiset, token );

    if (!(token = GetToken(0)) || strcmp( token, "=" ))
    {
        error( "Syntax error near '%s'\n", token );
        return 0;
    }

    while ((token = GetToken(1))) add_apiset_value( &spec->apiset, token );
    return 1;
}


831
static int name_compare( const void *ptr1, const void *ptr2 )
832
{
833 834 835 836 837
    const ORDDEF *odp1 = *(const ORDDEF * const *)ptr1;
    const ORDDEF *odp2 = *(const ORDDEF * const *)ptr2;
    const char *name1 = odp1->name ? odp1->name : odp1->export_name;
    const char *name2 = odp2->name ? odp2->name : odp2->export_name;
    return strcmp( name1, name2 );
838 839 840
}

/*******************************************************************
841
 *         assign_names
842
 *
843
 * Build the name array and catch duplicates.
844
 */
845
static void assign_names( DLLSPEC *spec )
846
{
847 848
    int i, j, nb_exp_names = 0;
    ORDDEF **all_names;
849 850 851 852

    spec->nb_names = 0;
    for (i = 0; i < spec->nb_entry_points; i++)
        if (spec->entry_points[i].name) spec->nb_names++;
853
        else if (spec->entry_points[i].export_name) nb_exp_names++;
854

855 856 857 858 859
    if (!spec->nb_names && !nb_exp_names) return;

    /* check for duplicates */

    all_names = xmalloc( (spec->nb_names + nb_exp_names) * sizeof(all_names[0]) );
860
    for (i = j = 0; i < spec->nb_entry_points; i++)
861 862
        if (spec->entry_points[i].name || spec->entry_points[i].export_name)
            all_names[j++] = &spec->entry_points[i];
863

864
    qsort( all_names, j, sizeof(all_names[0]), name_compare );
865

866
    for (i = 0; i < j - 1; i++)
867
    {
868 869
        const char *name1 = all_names[i]->name ? all_names[i]->name : all_names[i]->export_name;
        const char *name2 = all_names[i+1]->name ? all_names[i+1]->name : all_names[i+1]->export_name;
870 871
        if (!strcmp( name1, name2 ) &&
            !((all_names[i]->flags ^ all_names[i+1]->flags) & FLAG_EXPORT32))
872
        {
873
            current_line = max( all_names[i]->lineno, all_names[i+1]->lineno );
874
            error( "'%s' redefined\n%s:%d: First defined here\n",
875 876
                   name1, input_file_name,
                   min( all_names[i]->lineno, all_names[i+1]->lineno ) );
877 878
        }
    }
879 880 881 882 883 884 885 886 887 888
    free( all_names );

    if (spec->nb_names)
    {
        spec->names = xmalloc( spec->nb_names * sizeof(spec->names[0]) );
        for (i = j = 0; i < spec->nb_entry_points; i++)
            if (spec->entry_points[i].name) spec->names[j++] = &spec->entry_points[i];

        /* sort the list of names */
        qsort( spec->names, spec->nb_names, sizeof(spec->names[0]), name_compare );
889
        for (i = 0; i < spec->nb_names; i++) spec->names[i]->hint = i;
890
    }
891 892 893 894 895 896 897 898 899 900 901 902
}

/*******************************************************************
 *         assign_ordinals
 *
 * Build the ordinal array.
 */
static void assign_ordinals( DLLSPEC *spec )
{
    int i, count, ordinal;

    /* start assigning from base, or from 1 if no ordinal defined yet */
903 904 905 906 907 908 909 910 911 912

    spec->base = MAX_ORDINALS;
    spec->limit = 0;
    for (i = 0; i < spec->nb_entry_points; i++)
    {
        ordinal = spec->entry_points[i].ordinal;
        if (ordinal == -1) continue;
        if (ordinal > spec->limit) spec->limit = ordinal;
        if (ordinal < spec->base) spec->base = ordinal;
    }
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
    if (spec->base == MAX_ORDINALS) spec->base = 1;
    if (spec->limit < spec->base) spec->limit = spec->base;

    count = max( spec->limit + 1, spec->base + spec->nb_entry_points );
    spec->ordinals = xmalloc( count * sizeof(spec->ordinals[0]) );
    memset( spec->ordinals, 0, count * sizeof(spec->ordinals[0]) );

    /* fill in all explicitly specified ordinals */
    for (i = 0; i < spec->nb_entry_points; i++)
    {
        ordinal = spec->entry_points[i].ordinal;
        if (ordinal == -1) continue;
        if (spec->ordinals[ordinal])
        {
            current_line = max( spec->entry_points[i].lineno, spec->ordinals[ordinal]->lineno );
            error( "ordinal %d redefined\n%s:%d: First defined here\n",
                   ordinal, input_file_name,
                   min( spec->entry_points[i].lineno, spec->ordinals[ordinal]->lineno ) );
        }
        else spec->ordinals[ordinal] = &spec->entry_points[i];
    }

    /* now assign ordinals to the rest */
936
    for (i = 0, ordinal = spec->base; i < spec->nb_entry_points; i++)
937
    {
938
        if (spec->entry_points[i].ordinal != -1) continue;
939 940 941
        while (spec->ordinals[ordinal]) ordinal++;
        if (ordinal >= MAX_ORDINALS)
        {
942
            current_line = spec->entry_points[i].lineno;
943
            fatal_error( "Too many functions defined (max %d)\n", MAX_ORDINALS );
944
        }
945 946
        spec->entry_points[i].ordinal = ordinal;
        spec->ordinals[ordinal] = &spec->entry_points[i];
947
    }
948
    if (ordinal > spec->limit) spec->limit = ordinal;
949 950 951
}


952 953 954 955 956 957 958
/*******************************************************************
 *         add_16bit_exports
 *
 * Add the necessary exports to the 32-bit counterpart of a 16-bit module.
 */
void add_16bit_exports( DLLSPEC *spec32, DLLSPEC *spec16 )
{
959
    int i;
960 961
    ORDDEF *odp;

962
    spec32->file_name = xstrdup( spec16->file_name );
963
    spec32->characteristics = IMAGE_FILE_DLL;
964
    spec32->init_func = xstrdup( "DllMain" );
965

966 967 968 969
    /* add an export for the NE module */

    odp = add_entry_point( spec32 );
    odp->type = TYPE_EXTERN;
970
    odp->flags = FLAG_PRIVATE;
971 972 973 974 975
    odp->name = xstrdup( "__wine_spec_dos_header" );
    odp->lineno = 0;
    odp->ordinal = 1;
    odp->link_name = xstrdup( ".L__wine_spec_dos_header" );

976 977 978 979
    if (spec16->main_module)
    {
        odp = add_entry_point( spec32 );
        odp->type = TYPE_EXTERN;
980
        odp->flags = FLAG_PRIVATE;
981 982 983 984 985 986
        odp->name = xstrdup( "__wine_spec_main_module" );
        odp->lineno = 0;
        odp->ordinal = 2;
        odp->link_name = xstrdup( ".L__wine_spec_main_module" );
    }

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
    /* add the explicit win32 exports */

    for (i = 1; i <= spec16->limit; i++)
    {
        ORDDEF *odp16 = spec16->ordinals[i];

        if (!odp16 || !odp16->name) continue;
        if (!(odp16->flags & FLAG_EXPORT32)) continue;

        odp = add_entry_point( spec32 );
        odp->flags = odp16->flags & ~FLAG_EXPORT32;
        odp->type = odp16->type;
        odp->name = xstrdup( odp16->name );
        odp->lineno = odp16->lineno;
        odp->ordinal = -1;
        odp->link_name = xstrdup( odp16->link_name );
1003
        odp->u.func.nb_args = odp16->u.func.nb_args;
1004 1005
        if (odp->u.func.nb_args > 0) memcpy( odp->u.func.args, odp16->u.func.args,
                                             odp->u.func.nb_args * sizeof(odp->u.func.args[0]) );
1006 1007
    }

1008 1009 1010 1011 1012
    assign_names( spec32 );
    assign_ordinals( spec32 );
}


1013
/*******************************************************************
1014
 *         parse_spec_file
1015
 *
1016
 * Parse a .spec file.
1017
 */
1018
int parse_spec_file( FILE *file, DLLSPEC *spec )
1019
{
1020
    const char *token;
1021 1022

    input_file = file;
1023
    current_line = 0;
1024

1025
    comment_chars = "#;";
1026
    separator_chars = "()";
1027

1028
    while (get_next_line())
1029
    {
1030
        if (!(token = GetToken(1))) continue;
1031
        if (strcmp(token, "@") == 0)
1032
        {
1033
            if (!parse_spec_ordinal( -1, spec )) continue;
1034 1035 1036
        }
        else if (IsNumberString(token))
        {
1037
            if (!parse_spec_ordinal( atoi(token), spec )) continue;
1038
        }
1039 1040 1041 1042
        else if (strcmp(token, "apiset") == 0)
        {
            if (!parse_spec_apiset( spec )) continue;
        }
1043 1044 1045 1046 1047 1048
        else
        {
            error( "Expected ordinal declaration, got '%s'\n", token );
            continue;
        }
        if ((token = GetToken(1))) error( "Syntax error near '%s'\n", token );
1049 1050 1051
    }

    current_line = 0;  /* no longer parsing the input file */
1052 1053
    assign_names( spec );
    assign_ordinals( spec );
1054
    return !nb_errors;
1055
}
1056 1057


1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
/*******************************************************************
 *         parse_def_library
 *
 * Parse a LIBRARY declaration in a .def file.
 */
static int parse_def_library( DLLSPEC *spec )
{
    const char *token = GetToken(1);

    if (!token) return 1;
    if (strcmp( token, "BASE" ))
    {
        free( spec->file_name );
        spec->file_name = xstrdup( token );
        if (!(token = GetToken(1))) return 1;
    }
    if (strcmp( token, "BASE" ))
    {
        error( "Expected library name or BASE= declaration, got '%s'\n", token );
        return 0;
    }
    if (!(token = GetToken(0))) return 0;
    if (strcmp( token, "=" ))
    {
        error( "Expected '=' after BASE, got '%s'\n", token );
        return 0;
    }
    if (!(token = GetToken(0))) return 0;
    /* FIXME: do something with base address */

    return 1;
}


/*******************************************************************
 *         parse_def_stack_heap_size
 *
 * Parse a STACKSIZE or HEAPSIZE declaration in a .def file.
 */
static int parse_def_stack_heap_size( int is_stack, DLLSPEC *spec )
{
    const char *token = GetToken(0);
    char *end;
    unsigned long size;

    if (!token) return 0;
    size = strtoul( token, &end, 0 );
    if (*end)
    {
        error( "Invalid number '%s'\n", token );
        return 0;
    }
    if (is_stack) spec->stack_size = size / 1024;
    else spec->heap_size = size / 1024;
    if (!(token = GetToken(1))) return 1;
    if (strcmp( token, "," ))
    {
        error( "Expected ',' after size, got '%s'\n", token );
        return 0;
    }
    if (!(token = GetToken(0))) return 0;
    /* FIXME: do something with reserve size */
    return 1;
}


/*******************************************************************
 *         parse_def_export
 *
 * Parse an export declaration in a .def file.
 */
static int parse_def_export( char *name, DLLSPEC *spec )
{
    int i, args;
    const char *token = GetToken(1);
    ORDDEF *odp = add_entry_point( spec );

    odp->lineno = current_line;
    odp->ordinal = -1;
    odp->name = name;
    args = remove_stdcall_decoration( odp->name );
1139 1140 1141 1142 1143
    if (args == -1)
    {
        odp->type = TYPE_CDECL;
        args = 0;
    }
1144 1145 1146
    else
    {
        odp->type = TYPE_STDCALL;
1147
        args /= get_ptr_size();
1148
        if (args >= MAX_ARGUMENTS)
1149 1150 1151 1152
        {
            error( "Too many arguments in stdcall function '%s'\n", odp->name );
            return 0;
        }
1153
        for (i = 0; i < args; i++) odp->u.func.args[i] = ARG_LONG;
1154
    }
1155
    odp->u.func.nb_args = args;
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165

    /* check for optional internal name */

    if (token && !strcmp( token, "=" ))
    {
        if (!(token = GetToken(0))) goto error;
        odp->link_name = xstrdup( token );
        remove_stdcall_decoration( odp->link_name );
        token = GetToken(1);
    }
1166 1167 1168 1169
    else
    {
      odp->link_name = xstrdup( name );
    }
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198

    /* check for optional ordinal */

    if (token && token[0] == '@')
    {
        int ordinal;

        if (!IsNumberString( token+1 ))
        {
            error( "Expected number after '@', got '%s'\n", token+1 );
            goto error;
        }
        ordinal = atoi( token+1 );
        if (!ordinal)
        {
            error( "Ordinal 0 is not valid\n" );
            goto error;
        }
        if (ordinal >= MAX_ORDINALS)
        {
            error( "Ordinal number %d too large\n", ordinal );
            goto error;
        }
        odp->ordinal = ordinal;
        token = GetToken(1);
    }

    /* check for other optional keywords */

1199
    while (token)
1200
    {
1201
        if (!strcmp( token, "NONAME" ))
1202
        {
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
            if (odp->ordinal == -1)
            {
                error( "NONAME requires an ordinal\n" );
                goto error;
            }
            odp->export_name = odp->name;
            odp->name = NULL;
            odp->flags |= FLAG_NONAME;
        }
        else if (!strcmp( token, "PRIVATE" ))
        {
            odp->flags |= FLAG_PRIVATE;
        }
        else if (!strcmp( token, "DATA" ))
        {
            odp->type = TYPE_EXTERN;
        }
        else
        {
            error( "Garbage text '%s' found at end of export declaration\n", token );
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
            goto error;
        }
        token = GetToken(1);
    }
    return 1;

error:
    spec->nb_entry_points--;
    free( odp->name );
    return 0;
}


/*******************************************************************
 *         parse_def_file
 *
 * Parse a .def file.
 */
int parse_def_file( FILE *file, DLLSPEC *spec )
{
    const char *token;
    int in_exports = 0;

    input_file = file;
    current_line = 0;

    comment_chars = ";";
    separator_chars = ",=";

    while (get_next_line())
    {
        if (!(token = GetToken(1))) continue;

        if (!strcmp( token, "LIBRARY" ) || !strcmp( token, "NAME" ))
        {
            if (!parse_def_library( spec )) continue;
            goto end_of_line;
        }
        else if (!strcmp( token, "STACKSIZE" ))
        {
            if (!parse_def_stack_heap_size( 1, spec )) continue;
            goto end_of_line;
        }
        else if (!strcmp( token, "HEAPSIZE" ))
        {
            if (!parse_def_stack_heap_size( 0, spec )) continue;
            goto end_of_line;
        }
        else if (!strcmp( token, "EXPORTS" ))
        {
            in_exports = 1;
            if (!(token = GetToken(1))) continue;
        }
        else if (!strcmp( token, "IMPORTS" ))
        {
            in_exports = 0;
            if (!(token = GetToken(1))) continue;
        }
        else if (!strcmp( token, "SECTIONS" ))
        {
            in_exports = 0;
            if (!(token = GetToken(1))) continue;
        }

        if (!in_exports) continue;  /* ignore this line */
        if (!parse_def_export( xstrdup(token), spec )) continue;

    end_of_line:
        if ((token = GetToken(1))) error( "Syntax error near '%s'\n", token );
    }

    current_line = 0;  /* no longer parsing the input file */
    assign_names( spec );
    assign_ordinals( spec );
    return !nb_errors;
}