write_msft.c 93.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 *      Typelib v2 (MSFT) generation
 *
 *	Copyright 2004  Alastair Bridgewater
 *                2004, 2005 Huw Davies
 *
 * 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
19
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
 *
 * --------------------------------------------------------------------------------------
 *  Known problems:
 *
 *    Badly incomplete.
 *
 *    Only works on little-endian systems.
 *
 */

#include "config.h"

#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <ctype.h>
37
#include <time.h>
38 39 40

#define NONAMELESSUNION

41
#include "widl.h"
42 43 44 45 46 47 48
#include "winerror.h"
#include "windef.h"
#include "winbase.h"
#include "winnls.h"
#include "typelib.h"
#include "typelib_struct.h"
#include "utils.h"
49
#include "header.h"
50
#include "hash.h"
51
#include "typetree.h"
52
#include "parser.h"
53
#include "typegen.h"
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

enum MSFT_segment_index {
    MSFT_SEG_TYPEINFO = 0,  /* type information */
    MSFT_SEG_IMPORTINFO,    /* import information */
    MSFT_SEG_IMPORTFILES,   /* import filenames */
    MSFT_SEG_REFERENCES,    /* references (?) */
    MSFT_SEG_GUIDHASH,      /* hash table for guids? */
    MSFT_SEG_GUID,          /* guid storage */
    MSFT_SEG_NAMEHASH,      /* hash table for names */
    MSFT_SEG_NAME,          /* name storage */
    MSFT_SEG_STRING,        /* string storage */
    MSFT_SEG_TYPEDESC,      /* type descriptions */
    MSFT_SEG_ARRAYDESC,     /* array descriptions */
    MSFT_SEG_CUSTDATA,      /* custom data */
    MSFT_SEG_CUSTDATAGUID,  /* custom data guids */
    MSFT_SEG_UNKNOWN,       /* ??? */
    MSFT_SEG_UNKNOWN2,      /* ??? */
    MSFT_SEG_MAX            /* total number of segments */
};

typedef struct tagMSFT_ImpFile {
    int guid;
    LCID lcid;
    int version;
78
    char filename[0]; /* preceded by two bytes of encoded (length << 2) + flags in the low two bits. */
79 80 81 82 83 84 85
} MSFT_ImpFile;

typedef struct _msft_typelib_t
{
    typelib_t *typelib;
    MSFT_Header typelib_header;
    MSFT_pSeg typelib_segdir[MSFT_SEG_MAX];
86
    unsigned char *typelib_segment_data[MSFT_SEG_MAX];
87 88 89 90 91 92 93
    int typelib_segment_block_length[MSFT_SEG_MAX];

    INT typelib_typeinfo_offsets[0x200]; /* Hope that's enough. */

    INT *typelib_namehash_segment;
    INT *typelib_guidhash_segment;

94 95
    INT help_string_dll_offset;

96 97 98 99 100 101 102 103 104
    struct _msft_typeinfo_t *typeinfos;
    struct _msft_typeinfo_t *last_typeinfo;
} msft_typelib_t;

typedef struct _msft_typeinfo_t
{
    msft_typelib_t *typelib;
    MSFT_TypeInfoBase *typeinfo;

105 106
    int typekind;

107
    unsigned int var_data_allocated;
108 109
    int *var_data;

110
    unsigned int func_data_allocated;
111
    int *func_data;
112

113 114 115 116 117 118 119 120 121
    int vars_allocated;
    int *var_indices;
    int *var_names;
    int *var_offsets;

    int funcs_allocated;
    int *func_indices;
    int *func_names;
    int *func_offsets;
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142

    int datawidth;

    struct _msft_typeinfo_t *next_typeinfo;
} msft_typeinfo_t;



/*================== Internal functions ===================================*/

/****************************************************************************
 *	ctl2_init_header
 *
 *  Initializes the type library header of a new typelib.
 */
static void ctl2_init_header(
	msft_typelib_t *typelib) /* [I] The typelib to initialize. */
{
    typelib->typelib_header.magic1 = 0x5446534d;
    typelib->typelib_header.magic2 = 0x00010002;
    typelib->typelib_header.posguid = -1;
143
    typelib->typelib_header.lcid = 0x0409;
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
    typelib->typelib_header.lcid2 = 0x0;
    typelib->typelib_header.varflags = 0x40;
    typelib->typelib_header.version = 0;
    typelib->typelib_header.flags = 0;
    typelib->typelib_header.nrtypeinfos = 0;
    typelib->typelib_header.helpstring = -1;
    typelib->typelib_header.helpstringcontext = 0;
    typelib->typelib_header.helpcontext = 0;
    typelib->typelib_header.nametablecount = 0;
    typelib->typelib_header.nametablechars = 0;
    typelib->typelib_header.NameOffset = -1;
    typelib->typelib_header.helpfile = -1;
    typelib->typelib_header.CustomDataOffset = -1;
    typelib->typelib_header.res44 = 0x20;
    typelib->typelib_header.res48 = 0x80;
    typelib->typelib_header.dispatchpos = -1;
160
    typelib->typelib_header.nimpinfos = 0;
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
}

/****************************************************************************
 *	ctl2_init_segdir
 *
 *  Initializes the segment directory of a new typelib.
 */
static void ctl2_init_segdir(
	msft_typelib_t *typelib) /* [I] The typelib to initialize. */
{
    int i;
    MSFT_pSeg *segdir;

    segdir = &typelib->typelib_segdir[MSFT_SEG_TYPEINFO];

176
    for (i = 0; i < MSFT_SEG_MAX; i++) {
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
	segdir[i].offset = -1;
	segdir[i].length = 0;
	segdir[i].res08 = -1;
	segdir[i].res0c = 0x0f;
    }
}

/****************************************************************************
 *	ctl2_hash_guid
 *
 *  Generates a hash key from a GUID.
 *
 * RETURNS
 *
 *  The hash key for the GUID.
 */
static int ctl2_hash_guid(
Huw Davies's avatar
Huw Davies committed
194
	REFGUID guid)                /* [I] The guid to hash. */
195 196 197 198 199 200 201 202 203
{
    int hash;
    int i;

    hash = 0;
    for (i = 0; i < 8; i ++) {
	hash ^= ((const short *)guid)[i];
    }

Huw Davies's avatar
Huw Davies committed
204
    return hash & 0x1f;
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
}

/****************************************************************************
 *	ctl2_find_guid
 *
 *  Locates a guid in a type library.
 *
 * RETURNS
 *
 *  The offset into the GUID segment of the guid, or -1 if not found.
 */
static int ctl2_find_guid(
	msft_typelib_t *typelib,   /* [I] The typelib to operate against. */
	int hash_key,              /* [I] The hash key for the guid. */
	REFGUID guid)              /* [I] The guid to find. */
{
    int offset;
    MSFT_GuidEntry *guidentry;

    offset = typelib->typelib_guidhash_segment[hash_key];
    while (offset != -1) {
	guidentry = (MSFT_GuidEntry *)&typelib->typelib_segment_data[MSFT_SEG_GUID][offset];

	if (!memcmp(guidentry, guid, sizeof(GUID))) return offset;

	offset = guidentry->next_hash;
    }

    return offset;
}

/****************************************************************************
 *	ctl2_find_name
 *
 *  Locates a name in a type library.
 *
 * RETURNS
 *
 *  The offset into the NAME segment of the name, or -1 if not found.
 *
 * NOTES
 *
 *  The name must be encoded as with ctl2_encode_name().
 */
static int ctl2_find_name(
	msft_typelib_t *typelib,   /* [I] The typelib to operate against. */
	char *name)                /* [I] The encoded name to find. */
{
    int offset;
    int *namestruct;

    offset = typelib->typelib_namehash_segment[name[2] & 0x7f];
    while (offset != -1) {
	namestruct = (int *)&typelib->typelib_segment_data[MSFT_SEG_NAME][offset];

	if (!((namestruct[2] ^ *((int *)name)) & 0xffff00ff)) {
	    /* hash codes and lengths match, final test */
	    if (!strncasecmp(name+4, (void *)(namestruct+3), name[0])) break;
	}

	/* move to next item in hash bucket */
	offset = namestruct[1];
    }

    return offset;
}

/****************************************************************************
 *	ctl2_encode_name
 *
 *  Encodes a name string to a form suitable for storing into a type library
 *  or comparing to a name stored in a type library.
 *
 * RETURNS
 *
 *  The length of the encoded name, including padding and length+hash fields.
 *
 * NOTES
 *
 *  Will throw an exception if name or result are NULL. Is not multithread
 *  safe in the slightest.
 */
static int ctl2_encode_name(
	msft_typelib_t *typelib,   /* [I] The typelib to operate against (used for LCID only). */
	const char *name,          /* [I] The name string to encode. */
	char **result)             /* [O] A pointer to a pointer to receive the encoded name. */
{
292 293
    char *converted_name;
    size_t length, size;
294 295 296 297
    int offset;
    int value;

    length = strlen(name);
298 299
    size = (length + 7) & ~3;
    converted_name = xmalloc(size + 1);
300 301 302 303 304
    memcpy(converted_name + 4, name, length);
    converted_name[length + 4] = 0;

    value = lhash_val_of_name_sys(typelib->typelib_header.varflags & 0x0f, typelib->typelib_header.lcid, converted_name + 4);

305 306
#ifdef WORDS_BIGENDIAN
    converted_name[3] = length & 0xff;
307
    converted_name[2] = length >> 8;
308 309 310 311
    converted_name[1] = value;
    converted_name[0] = value >> 8;
#else
    converted_name[0] = length & 0xff;
312
    converted_name[1] = length >> 8;
313 314
    converted_name[2] = value;
    converted_name[3] = value >> 8;
315
#endif
316 317 318 319 320

    for (offset = (4 - length) & 3; offset; offset--) converted_name[length + offset + 3] = 0x57;

    *result = converted_name;

321
    return size;
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
}

/****************************************************************************
 *	ctl2_encode_string
 *
 *  Encodes a string to a form suitable for storing into a type library or
 *  comparing to a string stored in a type library.
 *
 * RETURNS
 *
 *  The length of the encoded string, including padding and length fields.
 *
 * NOTES
 *
 *  Will throw an exception if string or result are NULL. Is not multithread
 *  safe in the slightest.
 */
static int ctl2_encode_string(
	const char *string,        /* [I] The string to encode. */
	char **result)             /* [O] A pointer to a pointer to receive the encoded string. */
{
343 344
    char *converted_string;
    size_t length, size;
345 346 347
    int offset;

    length = strlen(string);
348 349 350
    size = (length + 5) & ~3;
    if (length < 3) size += 4;
    converted_string = xmalloc(size);
351
    memcpy(converted_string + 2, string, length);
352 353 354 355 356

#ifdef WORDS_BIGENDIAN
    converted_string[1] = length & 0xff;
    converted_string[0] = (length >> 8) & 0xff;
#else
357 358
    converted_string[0] = length & 0xff;
    converted_string[1] = (length >> 8) & 0xff;
359
#endif
360

361
    if(length < 3) { /* strings of this length are padded with up to 8 bytes incl the 2 byte length */
362 363 364 365
        for(offset = 0; offset < 4; offset++)
            converted_string[length + offset + 2] = 0x57;
        length += 4;
    }
366 367 368
    for (offset = (4 - (length + 2)) & 3; offset; offset--) converted_string[length + offset + 1] = 0x57;

    *result = converted_string;
369
    return size;
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
}

/****************************************************************************
 *	ctl2_alloc_segment
 *
 *  Allocates memory from a segment in a type library.
 *
 * RETURNS
 *
 *  Success: The offset within the segment of the new data area.
 *
 * BUGS
 *
 *  Does not (yet) handle the case where the allocated segment memory needs to grow.
 */
static int ctl2_alloc_segment(
	msft_typelib_t *typelib,         /* [I] The type library in which to allocate. */
	enum MSFT_segment_index segment, /* [I] The segment in which to allocate. */
	int size,                        /* [I] The amount to allocate. */
	int block_size)                  /* [I] Initial allocation block size, or 0 for default. */
{
    int offset;

    if(!typelib->typelib_segment_data[segment]) {
	if (!block_size) block_size = 0x2000;

	typelib->typelib_segment_block_length[segment] = block_size;
	typelib->typelib_segment_data[segment] = xmalloc(block_size);
	if (!typelib->typelib_segment_data[segment]) return -1;
	memset(typelib->typelib_segment_data[segment], 0x57, block_size);
    }

    while ((typelib->typelib_segdir[segment].length + size) > typelib->typelib_segment_block_length[segment]) {
403
	unsigned char *block;
404 405

	block_size = typelib->typelib_segment_block_length[segment];
406
	block = xrealloc(typelib->typelib_segment_data[segment], block_size << 1);
407 408 409 410 411 412

	if (segment == MSFT_SEG_TYPEINFO) {
	    /* TypeInfos have a direct pointer to their memory space, so we have to fix them up. */
	    msft_typeinfo_t *typeinfo;

	    for (typeinfo = typelib->typeinfos; typeinfo; typeinfo = typeinfo->next_typeinfo) {
413
		typeinfo->typeinfo = (void *)&block[((unsigned char *)typeinfo->typeinfo) - typelib->typelib_segment_data[segment]];
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
	    }
	}

	memset(block + block_size, 0x57, block_size);
	typelib->typelib_segment_block_length[segment] = block_size << 1;
	typelib->typelib_segment_data[segment] = block;
    }

    offset = typelib->typelib_segdir[segment].length;
    typelib->typelib_segdir[segment].length += size;

    return offset;
}

/****************************************************************************
 *	ctl2_alloc_typeinfo
 *
 *  Allocates and initializes a typeinfo structure in a type library.
 *
 * RETURNS
 *
 *  Success: The offset of the new typeinfo.
 *  Failure: -1 (this is invariably an out of memory condition).
 */
static int ctl2_alloc_typeinfo(
	msft_typelib_t *typelib,   /* [I] The type library to allocate in. */
	int nameoffset)            /* [I] The offset of the name for this typeinfo. */
{
    int offset;
    MSFT_TypeInfoBase *typeinfo;

    offset = ctl2_alloc_segment(typelib, MSFT_SEG_TYPEINFO, sizeof(MSFT_TypeInfoBase), 0);

    typelib->typelib_typeinfo_offsets[typelib->typelib_header.nrtypeinfos++] = offset;

    typeinfo = (void *)(typelib->typelib_segment_data[MSFT_SEG_TYPEINFO] + offset);

    typeinfo->typekind = (typelib->typelib_header.nrtypeinfos - 1) << 16;
    typeinfo->memoffset = -1; /* should be EOF if no elements */
    typeinfo->res2 = 0;
    typeinfo->res3 = -1;
    typeinfo->res4 = 3;
    typeinfo->res5 = 0;
    typeinfo->cElement = 0;
    typeinfo->res7 = 0;
    typeinfo->res8 = 0;
    typeinfo->res9 = 0;
    typeinfo->resA = 0;
    typeinfo->posguid = -1;
    typeinfo->flags = 0;
    typeinfo->NameOffset = nameoffset;
    typeinfo->version = 0;
    typeinfo->docstringoffs = -1;
    typeinfo->helpstringcontext = 0;
    typeinfo->helpcontext = 0;
    typeinfo->oCustData = -1;
    typeinfo->cbSizeVft = 0;
    typeinfo->cImplTypes = 0;
    typeinfo->size = 0;
    typeinfo->datatype1 = -1;
    typeinfo->datatype2 = 0;
    typeinfo->res18 = 0;
    typeinfo->res19 = -1;

    return offset;
}

/****************************************************************************
 *	ctl2_alloc_guid
 *
 *  Allocates and initializes a GUID structure in a type library. Also updates
 *  the GUID hash table as needed.
 *
 * RETURNS
 *
 *  Success: The offset of the new GUID.
 */
static int ctl2_alloc_guid(
	msft_typelib_t *typelib,   /* [I] The type library to allocate in. */
	MSFT_GuidEntry *guid)      /* [I] The GUID to store. */
{
    int offset;
    MSFT_GuidEntry *guid_space;
    int hash_key;

499 500 501 502 503
    chat("adding uuid {%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\n",
         guid->guid.Data1, guid->guid.Data2, guid->guid.Data3,
         guid->guid.Data4[0], guid->guid.Data4[1], guid->guid.Data4[2], guid->guid.Data4[3],
         guid->guid.Data4[4], guid->guid.Data4[5], guid->guid.Data4[6], guid->guid.Data4[7]);

504 505 506
    hash_key = ctl2_hash_guid(&guid->guid);

    offset = ctl2_find_guid(typelib, hash_key, &guid->guid);
507 508
    if (offset != -1)
    {
509
        if (is_warning_enabled(2368))
510 511 512 513
            warning("duplicate uuid {%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\n",
                    guid->guid.Data1, guid->guid.Data2, guid->guid.Data3,
                    guid->guid.Data4[0], guid->guid.Data4[1], guid->guid.Data4[2], guid->guid.Data4[3],
                    guid->guid.Data4[4], guid->guid.Data4[5], guid->guid.Data4[6], guid->guid.Data4[7]);
514 515
        return -1;
    }
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550

    offset = ctl2_alloc_segment(typelib, MSFT_SEG_GUID, sizeof(MSFT_GuidEntry), 0);

    guid_space = (void *)(typelib->typelib_segment_data[MSFT_SEG_GUID] + offset);
    *guid_space = *guid;

    guid_space->next_hash = typelib->typelib_guidhash_segment[hash_key];
    typelib->typelib_guidhash_segment[hash_key] = offset;

    return offset;
}

/****************************************************************************
 *	ctl2_alloc_name
 *
 *  Allocates and initializes a name within a type library. Also updates the
 *  name hash table as needed.
 *
 * RETURNS
 *
 *  Success: The offset within the segment of the new name.
 *  Failure: -1 (this is invariably an out of memory condition).
 */
static int ctl2_alloc_name(
	msft_typelib_t *typelib,  /* [I] The type library to allocate in. */
	const char *name)         /* [I] The name to store. */
{
    int length;
    int offset;
    MSFT_NameIntro *name_space;
    char *encoded_name;

    length = ctl2_encode_name(typelib, name, &encoded_name);

    offset = ctl2_find_name(typelib, encoded_name);
551 552 553 554 555
    if (offset != -1)
    {
        free(encoded_name);
        return offset;
    }
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571

    offset = ctl2_alloc_segment(typelib, MSFT_SEG_NAME, length + 8, 0);

    name_space = (void *)(typelib->typelib_segment_data[MSFT_SEG_NAME] + offset);
    name_space->hreftype = -1;
    name_space->next_hash = -1;
    memcpy(&name_space->namelen, encoded_name, length);

    if (typelib->typelib_namehash_segment[encoded_name[2] & 0x7f] != -1)
	name_space->next_hash = typelib->typelib_namehash_segment[encoded_name[2] & 0x7f];

    typelib->typelib_namehash_segment[encoded_name[2] & 0x7f] = offset;

    typelib->typelib_header.nametablecount += 1;
    typelib->typelib_header.nametablechars += *encoded_name;

572
    free(encoded_name);
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
    return offset;
}

/****************************************************************************
 *	ctl2_alloc_string
 *
 *  Allocates and initializes a string in a type library.
 *
 * RETURNS
 *
 *  Success: The offset within the segment of the new string.
 *  Failure: -1 (this is invariably an out of memory condition).
 */
static int ctl2_alloc_string(
	msft_typelib_t *typelib,  /* [I] The type library to allocate in. */
	const char *string)       /* [I] The string to store. */
{
    int length;
    int offset;
592
    unsigned char *string_space;
593 594
    char *encoded_string;

595
    length = ctl2_encode_string(string, &encoded_string);
596 597

    for (offset = 0; offset < typelib->typelib_segdir[MSFT_SEG_STRING].length;
598 599
	 offset += (((typelib->typelib_segment_data[MSFT_SEG_STRING][offset + 1] << 8) |
	      typelib->typelib_segment_data[MSFT_SEG_STRING][offset + 0]) + 5) & ~3) {
600 601 602 603 604 605 606
	if (!memcmp(encoded_string, typelib->typelib_segment_data[MSFT_SEG_STRING] + offset, length)) return offset;
    }

    offset = ctl2_alloc_segment(typelib, MSFT_SEG_STRING, length, 0);

    string_space = typelib->typelib_segment_data[MSFT_SEG_STRING] + offset;
    memcpy(string_space, encoded_string, length);
607
    free(encoded_string);
608 609 610 611 612

    return offset;
}

/****************************************************************************
613
 *	alloc_msft_importinfo
614 615 616 617 618 619 620 621
 *
 *  Allocates and initializes an import information structure in a type library.
 *
 * RETURNS
 *
 *  Success: The offset of the new importinfo.
 *  Failure: -1 (this is invariably an out of memory condition).
 */
622
static int alloc_msft_importinfo(
623
        msft_typelib_t *typelib,   /* [I] The type library to allocate in. */
624
        MSFT_ImpInfo *impinfo)     /* [I] The import information to store. */
625 626 627 628 629 630 631 632 633 634 635 636 637
{
    int offset;
    MSFT_ImpInfo *impinfo_space;

    for (offset = 0;
	 offset < typelib->typelib_segdir[MSFT_SEG_IMPORTINFO].length;
	 offset += sizeof(MSFT_ImpInfo)) {
	if (!memcmp(&(typelib->typelib_segment_data[MSFT_SEG_IMPORTINFO][offset]),
		    impinfo, sizeof(MSFT_ImpInfo))) {
	    return offset;
	}
    }

638 639
    impinfo->flags |= typelib->typelib_header.nimpinfos++;

640 641 642 643 644 645 646 647 648
    offset = ctl2_alloc_segment(typelib, MSFT_SEG_IMPORTINFO, sizeof(MSFT_ImpInfo), 0);

    impinfo_space = (void *)(typelib->typelib_segment_data[MSFT_SEG_IMPORTINFO] + offset);
    *impinfo_space = *impinfo;

    return offset;
}

/****************************************************************************
649
 *	alloc_importfile
650 651 652 653 654 655 656 657
 *
 *  Allocates and initializes an import file definition in a type library.
 *
 * RETURNS
 *
 *  Success: The offset of the new importinfo.
 *  Failure: -1 (this is invariably an out of memory condition).
 */
658 659 660 661 662 663
static int alloc_importfile(
        msft_typelib_t *typelib,   /* [I] The type library to allocate in. */
        int guidoffset,            /* [I] The offset to the GUID for the imported library. */
        int major_version,         /* [I] The major version number of the imported library. */
        int minor_version,         /* [I] The minor version number of the imported library. */
        const char *filename)      /* [I] The filename of the imported library. */
664 665 666 667 668 669
{
    int length;
    int offset;
    MSFT_ImpFile *importfile;
    char *encoded_string;

670
    length = ctl2_encode_string(filename, &encoded_string);
671 672 673 674 675

    encoded_string[0] <<= 2;
    encoded_string[0] |= 1;

    for (offset = 0; offset < typelib->typelib_segdir[MSFT_SEG_IMPORTFILES].length;
676 677
	 offset += (((typelib->typelib_segment_data[MSFT_SEG_IMPORTFILES][offset + 0xd] << 8) |
	              typelib->typelib_segment_data[MSFT_SEG_IMPORTFILES][offset + 0xc]) >> 2) + 0xc) {
678 679 680 681 682 683 684 685 686 687
	if (!memcmp(encoded_string, typelib->typelib_segment_data[MSFT_SEG_IMPORTFILES] + offset + 0xc, length)) return offset;
    }

    offset = ctl2_alloc_segment(typelib, MSFT_SEG_IMPORTFILES, length + 0xc, 0);

    importfile = (MSFT_ImpFile *)&typelib->typelib_segment_data[MSFT_SEG_IMPORTFILES][offset];
    importfile->guid = guidoffset;
    importfile->lcid = typelib->typelib_header.lcid2;
    importfile->version = major_version | (minor_version << 16);
    memcpy(&importfile->filename, encoded_string, length);
688
    free(encoded_string);
689 690 691 692

    return offset;
}

693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
static void alloc_importinfo(msft_typelib_t *typelib, importinfo_t *importinfo)
{
    importlib_t *importlib = importinfo->importlib;

    chat("alloc_importinfo: %s\n", importinfo->name);

    if(!importlib->allocated) {
        MSFT_GuidEntry guid;
        int guid_idx;

        chat("allocating importlib %s\n", importlib->name);

        importlib->allocated = -1;

        memcpy(&guid.guid, &importlib->guid, sizeof(GUID));
        guid.hreftype = 2;

        guid_idx = ctl2_alloc_guid(typelib, &guid);

712 713
        importlib->offset = alloc_importfile(typelib, guid_idx, importlib->version & 0xffff,
                importlib->version >> 16, importlib->name);
714 715 716 717 718 719
    }

    if(importinfo->offset == -1 || !(importinfo->flags & MSFT_IMPINFO_OFFSET_IS_GUID)) {
        MSFT_ImpInfo impinfo;

        impinfo.flags = importinfo->flags;
720
        impinfo.oImpFile = importlib->offset;
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

        if(importinfo->flags & MSFT_IMPINFO_OFFSET_IS_GUID) {
            MSFT_GuidEntry guid;

            guid.hreftype = 0;
            memcpy(&guid.guid, &importinfo->guid, sizeof(GUID));

            impinfo.oGuid = ctl2_alloc_guid(typelib, &guid);

            importinfo->offset = alloc_msft_importinfo(typelib, &impinfo);

            typelib->typelib_segment_data[MSFT_SEG_GUID][impinfo.oGuid+sizeof(GUID)]
                = importinfo->offset+1;

            if(!strcmp(importinfo->name, "IDispatch"))
                typelib->typelib_header.dispatchpos = importinfo->offset+1;
        }else {
            impinfo.oGuid = importinfo->id;
            importinfo->offset = alloc_msft_importinfo(typelib, &impinfo);
        }
    }
}

static importinfo_t *find_importinfo(msft_typelib_t *typelib, const char *name)
{
    importlib_t *importlib;
    int i;

    chat("search importlib %s\n", name);

    if(!name)
        return NULL;

754 755
    LIST_FOR_EACH_ENTRY( importlib, &typelib->typelib->importlibs, importlib_t, entry )
    {
756 757 758 759 760 761 762 763 764 765 766
        for(i=0; i < importlib->ntypeinfos; i++) {
            if(!strcmp(name, importlib->importinfos[i].name)) {
                chat("Found %s in importlib.\n", name);
                return importlib->importinfos+i;
            }
        }
    }

    return NULL;
}

767 768
static void add_structure_typeinfo(msft_typelib_t *typelib, type_t *structure);
static void add_interface_typeinfo(msft_typelib_t *typelib, type_t *interface);
769
static void add_enum_typeinfo(msft_typelib_t *typelib, type_t *enumeration);
770
static void add_union_typeinfo(msft_typelib_t *typelib, type_t *tunion);
771
static void add_coclass_typeinfo(msft_typelib_t *typelib, type_t *cls);
772
static void add_dispinterface_typeinfo(msft_typelib_t *typelib, type_t *dispinterface);
773
static void add_typedef_typeinfo(msft_typelib_t *typelib, type_t *dispinterface);
774

775 776

/****************************************************************************
777
 *	encode_type
778
 *
779
 *  Encodes a type, storing information in the TYPEDESC and ARRAYDESC
780 781 782 783 784 785 786
 *  segments as needed.
 *
 * RETURNS
 *
 *  Success: 0.
 *  Failure: -1.
 */
787
static int encode_type(
788
	msft_typelib_t *typelib,   /* [I] The type library in which to encode the TYPEDESC. */
789 790
        int vt,                    /* [I] vt to encode */
	type_t *type,              /* [I] type */
791 792 793 794 795 796 797 798
	int *encoded_type,         /* [O] The encoded type description. */
	int *decoded_size)         /* [O] The total size of the unencoded TYPEDESCs, including nested descs. */
{
    int default_type;
    int scratch;
    int typeoffset;
    int *typedata;
    int target_type;
Huw Davies's avatar
Huw Davies committed
799
    int child_size = 0;
800

801
    chat("encode_type vt %d type %p\n", vt, type);
802 803 804 805

    default_type = 0x80000000 | (vt << 16) | vt;
    if (!decoded_size) decoded_size = &scratch;

806
    *decoded_size = 0;
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835

    switch (vt) {
    case VT_I1:
    case VT_UI1:
	*encoded_type = default_type;
	break;

    case VT_INT:
	*encoded_type = 0x80000000 | (VT_I4 << 16) | VT_INT;
	break;

    case VT_UINT:
	*encoded_type = 0x80000000 | (VT_UI4 << 16) | VT_UINT;
	break;

    case VT_UI2:
    case VT_I2:
    case VT_BOOL:
	*encoded_type = default_type;
	break;

    case VT_I4:
    case VT_UI4:
    case VT_R4:
    case VT_ERROR:
    case VT_HRESULT:
	*encoded_type = default_type;
	break;

Huw Davies's avatar
Huw Davies committed
836
    case VT_R8:
837 838
    case VT_I8:
    case VT_UI8:
Huw Davies's avatar
Huw Davies committed
839 840 841
	*encoded_type = default_type;
	break;

842
    case VT_CY:
843
    case VT_DATE:
844 845 846
	*encoded_type = default_type;
	break;

847 848 849 850
    case VT_DECIMAL:
        *encoded_type = default_type;
        break;

851 852 853 854
    case VT_VOID:
	*encoded_type = 0x80000000 | (VT_EMPTY << 16) | vt;
	break;

855 856
    case VT_UNKNOWN:
    case VT_DISPATCH:
857
    case VT_BSTR:
858 859 860
        *encoded_type = default_type;
        break;

Huw Davies's avatar
Huw Davies committed
861 862 863 864
    case VT_VARIANT:
        *encoded_type = default_type;
        break;

865 866 867 868 869
    case VT_LPSTR:
    case VT_LPWSTR:
        *encoded_type = 0xfffe0000 | vt;
        break;

870 871 872
    case VT_PTR:
      {
        int next_vt;
873 874
        for(next_vt = 0; is_ptr(type); type = type_pointer_get_ref_type(type)) {
            next_vt = get_type_vt(type_pointer_get_ref_type(type));
875
            if (next_vt != 0)
Huw Davies's avatar
Huw Davies committed
876
                break;
877
        }
878 879 880
        /* if no type found then it must be void */
        if (next_vt == 0)
            next_vt = VT_VOID;
881

882
        encode_type(typelib, next_vt, type_pointer_get_ref_type(type),
883
                    &target_type, &child_size);
884 885 886
        /* these types already have an implicit pointer, so we don't need to
         * add another */
        if(next_vt == VT_DISPATCH || next_vt == VT_UNKNOWN) {
887 888 889 890 891
            chat("encode_type: skipping ptr\n");
            *encoded_type = target_type;
            *decoded_size = child_size;
            break;
        }
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919

	for (typeoffset = 0; typeoffset < typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length; typeoffset += 8) {
	    typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];
	    if (((typedata[0] & 0xffff) == VT_PTR) && (typedata[1] == target_type)) break;
	}

	if (typeoffset == typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length) {
	    int mix_field;
	    
	    if (target_type & 0x80000000) {
		mix_field = ((target_type >> 16) & 0x3fff) | VT_BYREF;
	    } else {
		typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][target_type];
		mix_field = ((typedata[0] >> 16) == 0x7fff)? 0x7fff: 0x7ffe;
	    }

	    typeoffset = ctl2_alloc_segment(typelib, MSFT_SEG_TYPEDESC, 8, 0);
	    typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];

	    typedata[0] = (mix_field << 16) | VT_PTR;
	    typedata[1] = target_type;
	}

	*encoded_type = typeoffset;

	*decoded_size = 8 /*sizeof(TYPEDESC)*/ + child_size;
        break;
    }
920 921

    case VT_SAFEARRAY:
922
	{
923
	type_t *element_type = type_alias_get_aliasee_type(type_array_get_element_type(type));
924
	int next_vt = get_type_vt(element_type);
925

926
	encode_type(typelib, next_vt, type_alias_get_aliasee_type(type_array_get_element_type(type)),
927
        &target_type, &child_size);
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950

	for (typeoffset = 0; typeoffset < typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length; typeoffset += 8) {
	    typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];
	    if (((typedata[0] & 0xffff) == VT_SAFEARRAY) && (typedata[1] == target_type)) break;
	}

	if (typeoffset == typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length) {
	    int mix_field;
	    
	    if (target_type & 0x80000000) {
		mix_field = ((target_type >> 16) & VT_TYPEMASK) | VT_ARRAY;
	    } else {
		typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][target_type];
		mix_field = ((typedata[0] >> 16) == 0x7fff)? 0x7fff: 0x7ffe;
	    }

	    typeoffset = ctl2_alloc_segment(typelib, MSFT_SEG_TYPEDESC, 8, 0);
	    typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];

	    typedata[0] = (mix_field << 16) | VT_SAFEARRAY;
	    typedata[1] = target_type;
	}

951
	*encoded_type = typeoffset;
952

953
	*decoded_size = 8 /*sizeof(TYPEDESC)*/ + child_size;
954
	break;
955
	}
956 957 958

    case VT_USERDEFINED:
      {
959
        importinfo_t *importinfo;
960
        int typeinfo_offset;
961

962 963 964 965 966 967 968
        if (type->typelib_idx > -1)
        {
            chat("encode_type: VT_USERDEFINED - found already defined type %s at %d\n",
                type->name, type->typelib_idx);
            typeinfo_offset = typelib->typelib_typeinfo_offsets[type->typelib_idx];
        }
        else if ((importinfo = find_importinfo(typelib, type->name)))
969 970 971 972 973
        {
            chat("encode_type: VT_USERDEFINED - found imported type %s in %s\n",
                type->name, importinfo->importlib->name);
            alloc_importinfo(typelib, importinfo);
            typeinfo_offset = importinfo->offset | 0x1;
974
        }
975 976
        else
        {
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
            /* Typedefs without the [public] attribute aren't included in the
             * typelib, unless the aliasee is an anonymous UDT or the typedef
             * is wire-marshalled. In the latter case the wire-marshal type,
             * which may be a non-public alias, is used instead. */
            while (type_is_alias(type))
            {
                if (is_attr(type->attrs, ATTR_WIREMARSHAL))
                {
                    type = get_attrp(type->attrs, ATTR_WIREMARSHAL);
                    break;
                }
                else if (!is_attr(type->attrs, ATTR_PUBLIC))
                    type = type_alias_get_aliasee_type(type);
                else
                    break;
            }
993

994 995
            chat("encode_type: VT_USERDEFINED - adding new type %s, real type %d\n",
                 type->name, type_get_type(type));
996

997
            switch (type_get_type_detect_alias(type))
998
            {
999
            case TYPE_STRUCT:
1000
            case TYPE_ENCAPSULATED_UNION:
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
                add_structure_typeinfo(typelib, type);
                break;
            case TYPE_INTERFACE:
                add_interface_typeinfo(typelib, type);
                break;
            case TYPE_ENUM:
                add_enum_typeinfo(typelib, type);
                break;
            case TYPE_UNION:
                add_union_typeinfo(typelib, type);
                break;
            case TYPE_COCLASS:
                add_coclass_typeinfo(typelib, type);
                break;
1015 1016 1017
            case TYPE_ALIAS:
                add_typedef_typeinfo(typelib, type);
                break;
1018 1019 1020
            default:
                error("encode_type: VT_USERDEFINED - unhandled type %d\n",
                      type_get_type(type));
1021
            }
1022

1023 1024
            typeinfo_offset = typelib->typelib_typeinfo_offsets[type->typelib_idx];
        }
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
	for (typeoffset = 0; typeoffset < typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length; typeoffset += 8) {
	    typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];
	    if ((typedata[0] == ((0x7fff << 16) | VT_USERDEFINED)) && (typedata[1] == typeinfo_offset)) break;
	}

	if (typeoffset == typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length) {
	    typeoffset = ctl2_alloc_segment(typelib, MSFT_SEG_TYPEDESC, 8, 0);
	    typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];

	    typedata[0] = (0x7fff << 16) | VT_USERDEFINED;
	    typedata[1] = typeinfo_offset;
	}

	*encoded_type = typeoffset;
1039
        break;
1040 1041 1042
      }

    default:
1043
	error("encode_type: unrecognized type %d.\n", vt);
1044 1045 1046 1047 1048 1049 1050
	*encoded_type = default_type;
	break;
    }

    return 0;
}

1051 1052
static void dump_type(type_t *t)
{
1053
    chat("dump_type: %p name %s type %d attrs %p\n", t, t->name, type_get_type(t), t->attrs);
1054 1055 1056 1057
}

static int encode_var(
	msft_typelib_t *typelib,   /* [I] The type library in which to encode the TYPEDESC. */
1058 1059
	type_t *type,              /* [I] The type description to encode. */
	var_t *var,                /* [I] The var to encode. */
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
	int *encoded_type,         /* [O] The encoded type description. */
	int *decoded_size)         /* [O] The total size of the unencoded TYPEDESCs, including nested descs. */
{
    int typeoffset;
    int *typedata;
    int target_type;
    int child_size;
    int vt;
    int scratch;

    if (!decoded_size) decoded_size = &scratch;
    *decoded_size = 0;

1073 1074
    chat("encode_var: var %p type %p type->name %s\n",
         var, type, type->name ? type->name : "NULL");
1075

1076
    if (is_array(type) && !type_array_is_decl_as_ptr(type)) {
1077 1078 1079 1080 1081
        int num_dims, elements = 1, arrayoffset;
        type_t *atype;
        int *arraydata;

        num_dims = 0;
1082 1083
        for (atype = type;
             is_array(atype) && !type_array_is_decl_as_ptr(atype);
1084
             atype = type_array_get_element_type(atype))
1085 1086 1087
            ++num_dims;

        chat("array with %d dimensions\n", num_dims);
1088
        encode_var(typelib, atype, var, &target_type, NULL);
1089
        arrayoffset = ctl2_alloc_segment(typelib, MSFT_SEG_ARRAYDESC, (2 + 2 * num_dims) * sizeof(int), 0);
1090 1091 1092 1093
        arraydata = (void *)&typelib->typelib_segment_data[MSFT_SEG_ARRAYDESC][arrayoffset];

        arraydata[0] = target_type;
        arraydata[1] = num_dims;
1094
        arraydata[1] |= ((num_dims * 2 * sizeof(int)) << 16);
1095 1096

        arraydata += 2;
1097 1098
        for (atype = type;
             is_array(atype) && !type_array_is_decl_as_ptr(atype);
1099
             atype = type_array_get_element_type(atype))
1100
        {
1101
            arraydata[0] = type_array_get_dim(atype);
1102 1103
            arraydata[1] = 0;
            arraydata += 2;
1104
            elements *= type_array_get_dim(atype);
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
        }

        typeoffset = ctl2_alloc_segment(typelib, MSFT_SEG_TYPEDESC, 8, 0);
        typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];

        typedata[0] = (0x7ffe << 16) | VT_CARRAY;
        typedata[1] = arrayoffset;

        *encoded_type = typeoffset;
        *decoded_size = 20 /*sizeof(ARRAYDESC)*/ + (num_dims - 1) * 8 /*sizeof(SAFEARRAYBOUND)*/;
        return 0;
    }

1118 1119
    vt = get_type_vt(type);
    if (vt == VT_PTR) {
1120
        type_t *ref = is_ptr(type) ?
1121
            type_pointer_get_ref_type(type) : type_array_get_element_type(type);
1122
        int skip_ptr = encode_var(typelib, ref, var, &target_type, &child_size);
1123

1124 1125 1126 1127 1128 1129 1130
        if(skip_ptr == 2) {
            chat("encode_var: skipping ptr\n");
            *encoded_type = target_type;
            *decoded_size = child_size;
            return 0;
        }

1131 1132 1133 1134 1135 1136 1137
	for (typeoffset = 0; typeoffset < typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length; typeoffset += 8) {
	    typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];
	    if (((typedata[0] & 0xffff) == VT_PTR) && (typedata[1] == target_type)) break;
	}

	if (typeoffset == typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length) {
	    int mix_field;
1138

1139 1140
	    if (target_type & 0x80000000) {
		mix_field = ((target_type >> 16) & 0x3fff) | VT_BYREF;
1141
	    } else if (get_type_vt(ref) == VT_SAFEARRAY) {
1142
		type_t *element_type = type_alias_get_aliasee_type(type_array_get_element_type(ref));
1143
		mix_field = get_type_vt(element_type) | VT_ARRAY | VT_BYREF;
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
	    } else {
		typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][target_type];
		mix_field = ((typedata[0] >> 16) == 0x7fff)? 0x7fff: 0x7ffe;
	    }

	    typeoffset = ctl2_alloc_segment(typelib, MSFT_SEG_TYPEDESC, 8, 0);
	    typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];

	    typedata[0] = (mix_field << 16) | VT_PTR;
	    typedata[1] = target_type;
	}

	*encoded_type = typeoffset;

	*decoded_size = 8 /*sizeof(TYPEDESC)*/ + child_size;
        return 0;
    }

1162
    dump_type(type);
1163

1164
    encode_type(typelib, vt, type, encoded_type, decoded_size);
1165 1166 1167
    /* these types already have an implicit pointer, so we don't need to
     * add another */
    if(vt == VT_DISPATCH || vt == VT_UNKNOWN) return 2;
1168
    return 0;
1169 1170
}

1171
static unsigned int get_ulong_val(unsigned int val, int vt)
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
{
    switch(vt) {
    case VT_I2:
    case VT_BOOL:
    case VT_UI2:
        return val & 0xffff;
    case VT_I1:
    case VT_UI1:
        return val & 0xff;
    }

    return val;
}
1185

1186
static void write_int_value(msft_typelib_t *typelib, int *out, int vt, int value)
1187
{
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
    const unsigned int lv = get_ulong_val(value, vt);
    if ((lv & 0x3ffffff) == lv) {
        *out = 0x80000000;
        *out |= vt << 26;
        *out |= lv;
    } else {
        int offset = ctl2_alloc_segment(typelib, MSFT_SEG_CUSTDATA, 8, 0);
        *((unsigned short *)&typelib->typelib_segment_data[MSFT_SEG_CUSTDATA][offset]) = vt;
        memcpy(&typelib->typelib_segment_data[MSFT_SEG_CUSTDATA][offset+2], &value, 4);
        *((unsigned short *)&typelib->typelib_segment_data[MSFT_SEG_CUSTDATA][offset+6]) = 0x5757;
        *out = offset;
1199
    }
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
}

static void write_string_value(msft_typelib_t *typelib, int *out, const char *value)
{
    int len = strlen(value), seg_len = (len + 6 + 3) & ~0x3;
    int offset = ctl2_alloc_segment(typelib, MSFT_SEG_CUSTDATA, seg_len, 0);
    *((unsigned short *)&typelib->typelib_segment_data[MSFT_SEG_CUSTDATA][offset]) = VT_BSTR;
    memcpy(&typelib->typelib_segment_data[MSFT_SEG_CUSTDATA][offset+2], &len, sizeof(len));
    memcpy(&typelib->typelib_segment_data[MSFT_SEG_CUSTDATA][offset+6], value, len);
    len += 6;
    while(len < seg_len) {
        *((char *)&typelib->typelib_segment_data[MSFT_SEG_CUSTDATA][offset+len]) = 0x57;
        len++;
    }
    *out = offset;
1215 1216
}

1217 1218 1219 1220 1221
static void write_default_value(msft_typelib_t *typelib, type_t *type, expr_t *expr, int *out)
{
    int vt;

    if (expr->type == EXPR_STRLIT || expr->type == EXPR_WSTRLIT) {
1222 1223
        vt = get_type_vt(type);
        if (vt != VT_BSTR && vt != VT_VARIANT)
1224 1225 1226 1227 1228 1229 1230 1231 1232
            error("string default value applied to non-string type\n");
        chat("default value '%s'\n", expr->u.sval);
        write_string_value(typelib, out, expr->u.sval);
        return;
    }

    if (type_get_type(type) == TYPE_ENUM) {
        vt = VT_I4;
    } else if (is_ptr(type)) {
1233
        vt = get_type_vt(type_pointer_get_ref_type(type));
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
        if (vt == VT_USERDEFINED)
            vt = VT_I4;
        if (expr->cval)
            warning("non-null pointer default value\n");
    } else {
        vt = get_type_vt(type);
        switch(vt) {
        case VT_I2:
        case VT_I4:
        case VT_R4:
        case VT_BOOL:
        case VT_I1:
        case VT_UI1:
        case VT_UI2:
        case VT_UI4:
        case VT_INT:
        case VT_UINT:
        case VT_HRESULT:
            break;
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
        case VT_VARIANT: {
            switch (expr->type) {
            case EXPR_DOUBLE:
                vt = VT_R4;
                break;
            case EXPR_NUM:
                vt = VT_I4;
                break;
            default:
                warning("can't write default VT_VARIANT value for expression type %d.\n", expr->type);
                return;
            }
            break;
        }
1267 1268 1269 1270 1271 1272 1273 1274 1275
        default:
            warning("can't write value of type %d yet\n", vt);
            return;
        }
    }

    write_int_value(typelib, out, vt, expr->cval);
}

1276
static HRESULT set_custdata(msft_typelib_t *typelib, REFGUID guid,
1277
                            int vt, const void *value, int *offset)
1278 1279 1280 1281 1282
{
    int guidoffset;
    int custoffset;
    int *custdata;
    int data_out;
1283 1284 1285 1286 1287 1288 1289 1290
    int hash_key;

    hash_key = ctl2_hash_guid(guid);
    guidoffset = ctl2_find_guid(typelib, hash_key, guid);
    if(guidoffset == -1) {
        /* add GUID that was not already present */
        MSFT_GuidEntry guidentry;
        guidentry.guid = *guid;
1291

1292 1293
        guidentry.hreftype = -1;
        guidentry.next_hash = -1;
1294

1295 1296
        guidoffset = ctl2_alloc_guid(typelib, &guidentry);
    }
1297

1298
    if(vt == VT_BSTR)
1299
        /* TODO midl appears to share a single reference if the same string is used as custdata in multiple places */
1300 1301 1302
        write_string_value(typelib, &data_out, value);
    else
        write_int_value(typelib, &data_out, vt, *(int*)value);
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314

    custoffset = ctl2_alloc_segment(typelib, MSFT_SEG_CUSTDATAGUID, 12, 0);

    custdata = (int *)&typelib->typelib_segment_data[MSFT_SEG_CUSTDATAGUID][custoffset];
    custdata[0] = guidoffset;
    custdata[1] = data_out;
    custdata[2] = *offset;
    *offset = custoffset;

    return S_OK;
}

1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
static HRESULT set_custdata_attr(msft_typelib_t *typelib, attr_custdata_t *custdata, int *offset)
{
    switch(custdata->pval->type) {
        case EXPR_STRLIT:
        case EXPR_WSTRLIT:
            set_custdata(typelib, &custdata->id, VT_BSTR, custdata->pval->u.sval, offset);
            break;
        case EXPR_HEXNUM:
        case EXPR_NUM:
            set_custdata(typelib, &custdata->id, VT_I4, &custdata->pval->u.lval, offset);
            break;
        default:
            error("custom() attribute with unknown type\n");
            break;
    }

    return S_OK;
}

1334
static HRESULT add_func_desc(msft_typeinfo_t* typeinfo, var_t *func, int index)
1335
{
Huw Davies's avatar
Huw Davies committed
1336
    int offset, name_offset;
1337
    int *typedata, typedata_size;
1338
    int i, id, next_idx;
1339
    int decoded_size, extra_attr = 0;
1340
    int num_params = 0, num_optional = 0, num_defaults = 0;
1341
    int has_arg_custdata = 0;
1342
    var_t *arg;
1343
    unsigned char *namedata;
1344
    const attr_t *attr;
1345
    unsigned int funcflags = 0, callconv = 4 /* CC_STDCALL */;
Huw Davies's avatar
Huw Davies committed
1346
    unsigned int funckind, invokekind = 1 /* INVOKE_FUNC */;
1347
    int help_context = 0, help_string_context = 0, help_string_offset = -1;
1348
    int func_custdata_offset = -1;
Huw Davies's avatar
Huw Davies committed
1349
    int entry = -1, entry_is_ord = 0;
1350
    int lcid_retval_count = 0;
Huw Davies's avatar
Huw Davies committed
1351 1352

    chat("add_func_desc(%p,%d)\n", typeinfo, index);
1353

1354
    id = ((0x6000 | (typeinfo->typeinfo->datatype2 & 0xffff)) << 16) | index;
1355

1356
    switch(typeinfo->typekind) {
Huw Davies's avatar
Huw Davies committed
1357
    case TKIND_DISPATCH:
1358
        funckind = 0x4; /* FUNC_DISPATCH */
Huw Davies's avatar
Huw Davies committed
1359 1360 1361 1362 1363 1364 1365 1366
        break;
    case TKIND_MODULE:
        funckind = 0x3; /* FUNC_STATIC */
        break;
    default:
        funckind = 0x1; /* FUNC_PUREVIRTUAL */
        break;
    }
1367

1368
    if (is_local( func->attrs )) {
1369 1370
        chat("add_func_desc: skipping local function\n");
        return S_FALSE;
1371 1372
    }

1373 1374
    if (type_function_get_args(func->declspec.type))
      LIST_FOR_EACH_ENTRY( arg, type_function_get_args(func->declspec.type), var_t, entry )
1375
      {
1376
        num_params++;
1377
        if (arg->attrs) LIST_FOR_EACH_ENTRY( attr, arg->attrs, const attr_t, entry ) {
1378
            if(attr->type == ATTR_DEFAULTVALUE)
1379
                num_defaults++;
1380 1381
            else if(attr->type == ATTR_OPTIONAL)
                num_optional++;
1382 1383
            else if(attr->type == ATTR_CUSTOM)
                has_arg_custdata = 1;
1384
        }
1385
      }
1386

1387
    chat("add_func_desc: num of params %d\n", num_params);
1388

1389
    name_offset = ctl2_alloc_name(typeinfo->typelib, func->name);
Huw Davies's avatar
Huw Davies committed
1390

1391
    if (func->attrs) LIST_FOR_EACH_ENTRY( attr, func->attrs, const attr_t, entry ) {
1392
        expr_t *expr = attr->u.pval;
1393
        switch(attr->type) {
1394
        case ATTR_BINDABLE:
1395 1396
            funcflags |= 0x4; /* FUNCFLAG_FBINDABLE */
            break;
1397 1398 1399
        case ATTR_CUSTOM:
            set_custdata_attr(typeinfo->typelib, attr->u.pval, &func_custdata_offset);
            break;
1400 1401 1402
        case ATTR_DEFAULTBIND:
            funcflags |= 0x20; /* FUNCFLAG_FDEFAULTBIND */
            break;
1403 1404
        case ATTR_DEFAULTCOLLELEM:
            funcflags |= 0x100; /* FUNCFLAG_FDEFAULTCOLLELEM */
1405
            break;
1406
        case ATTR_DISPLAYBIND:
1407
            funcflags |= 0x10; /* FUNCFLAG_FDISPLAYBIND */
1408
            break;
1409
        case ATTR_ENTRY:
Huw Davies's avatar
Huw Davies committed
1410
            extra_attr = max(extra_attr, 3);
1411 1412 1413 1414 1415 1416
            if (expr->type == EXPR_STRLIT || expr->type == EXPR_WSTRLIT)
              entry = ctl2_alloc_string(typeinfo->typelib, attr->u.pval);
            else {
              entry = expr->cval;
              entry_is_ord = 1;
            }
Huw Davies's avatar
Huw Davies committed
1417
            break;
1418
        case ATTR_HELPCONTEXT:
Huw Davies's avatar
Huw Davies committed
1419
            extra_attr = max(extra_attr, 1);
1420 1421 1422
            help_context = expr->u.lval;
            break;
        case ATTR_HELPSTRING:
Huw Davies's avatar
Huw Davies committed
1423
            extra_attr = max(extra_attr, 2);
1424 1425 1426
            help_string_offset = ctl2_alloc_string(typeinfo->typelib, attr->u.pval);
            break;
        case ATTR_HELPSTRINGCONTEXT:
Huw Davies's avatar
Huw Davies committed
1427
            extra_attr = max(extra_attr, 6);
1428 1429
            help_string_context = expr->u.lval;
            break;
1430 1431 1432 1433
        case ATTR_HIDDEN:
            funcflags |= 0x40; /* FUNCFLAG_FHIDDEN */
            break;
        case ATTR_ID:
Jacek Caban's avatar
Jacek Caban committed
1434
            id = expr->cval;
1435
            break;
1436 1437 1438
        case ATTR_IMMEDIATEBIND:
            funcflags |= 0x1000; /* FUNCFLAG_FIMMEDIATEBIND */
            break;
1439
        case ATTR_NONBROWSABLE:
1440
            funcflags |= 0x400; /* FUNCFLAG_FNONBROWSABLE */
1441
            break;
1442 1443
        case ATTR_OUT:
            break;
1444 1445 1446 1447 1448 1449
        case ATTR_PROPGET:
            invokekind = 0x2; /* INVOKE_PROPERTYGET */
            break;
        case ATTR_PROPPUT:
            invokekind = 0x4; /* INVOKE_PROPERTYPUT */
            break;
1450 1451 1452
        case ATTR_PROPPUTREF:
            invokekind = 0x8; /* INVOKE_PROPERTYPUTREF */
            break;
1453 1454 1455 1456
        /* FIXME: FUNCFLAG_FREPLACEABLE */
        case ATTR_REQUESTEDIT:
            funcflags |= 0x8; /* FUNCFLAG_FREQUESTEDIT */
            break;
1457 1458 1459
        case ATTR_RESTRICTED:
            funcflags |= 0x1; /* FUNCFLAG_FRESTRICTED */
            break;
1460 1461 1462
        case ATTR_SOURCE:
            funcflags |= 0x2; /* FUNCFLAG_FSOURCE */
            break;
1463 1464 1465 1466 1467 1468
        case ATTR_UIDEFAULT:
            funcflags |= 0x200; /* FUNCFLAG_FUIDEFAULT */
            break;
        case ATTR_USESGETLASTERROR:
            funcflags |= 0x80; /* FUNCFLAG_FUSESGETLASTERROR */
            break;
1469 1470 1471 1472 1473 1474
        case ATTR_VARARG:
            if (num_optional || num_defaults)
                warning("add_func_desc: ignoring vararg in function with optional or defaultvalue params\n");
            else
                num_optional = -1;
            break;
1475 1476 1477 1478
        default:
            break;
        }
    }
1479

1480 1481 1482 1483
    if(has_arg_custdata || func_custdata_offset != -1) {
        extra_attr = max(extra_attr, 7 + num_params);
    }

1484
    /* allocate type data space for us */
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
    typedata_size = 0x18 + extra_attr * sizeof(int) + (num_params * (num_defaults ? 16 : 12));

    if (!typeinfo->func_data) {
        typeinfo->func_data = xmalloc(0x100);
        typeinfo->func_data_allocated = 0x100;
        typeinfo->func_data[0] = 0;
    }

    if(typeinfo->func_data[0] + typedata_size + sizeof(int) > typeinfo->func_data_allocated) {
        typeinfo->func_data_allocated = max(typeinfo->func_data_allocated * 2,
                                            typeinfo->func_data[0] + typedata_size + sizeof(int));
        typeinfo->func_data = xrealloc(typeinfo->func_data, typeinfo->func_data_allocated);
    }

    offset = typeinfo->func_data[0];
    typeinfo->func_data[0] += typedata_size;
    typedata = typeinfo->func_data + (offset >> 2) + 1;
1502

Huw Davies's avatar
Huw Davies committed
1503 1504 1505 1506 1507 1508 1509 1510 1511

    /* find func with the same name - if it exists use its id */
    for(i = 0; i < (typeinfo->typeinfo->cElement & 0xffff); i++) {
        if(name_offset == typeinfo->func_names[i]) {
            id = typeinfo->func_indices[i];
            break;
        }
    }

1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
    /* find the first func with the same id and link via the hiword of typedata[4] */
    next_idx = index;
    for(i = 0; i < (typeinfo->typeinfo->cElement & 0xffff); i++) {
        if(id == typeinfo->func_indices[i]) {
            next_idx = typeinfo->func_data[(typeinfo->func_offsets[i] >> 2) + 1 + 4] >> 16;
            typeinfo->func_data[(typeinfo->func_offsets[i] >> 2) + 1 + 4] &= 0xffff;
            typeinfo->func_data[(typeinfo->func_offsets[i] >> 2) + 1 + 4] |= (index << 16);
            break;
        }
    }

1523
    /* fill out the basic type information */
1524
    typedata[0] = typedata_size | (index << 16);
1525
    encode_var(typeinfo->typelib, type_function_get_rettype(func->declspec.type), func,
1526
        &typedata[1], &decoded_size);
1527 1528
    typedata[2] = funcflags;
    typedata[3] = ((52 /*sizeof(FUNCDESC)*/ + decoded_size) << 16) | typeinfo->typeinfo->cbSizeVft;
1529
    typedata[4] = (next_idx << 16) | (callconv << 8) | (invokekind << 3) | funckind;
1530
    if(has_arg_custdata || func_custdata_offset != -1) typedata[4] |= 0x0080;
1531
    if(num_defaults) typedata[4] |= 0x1000;
Huw Davies's avatar
Huw Davies committed
1532
    if(entry_is_ord) typedata[4] |= 0x2000;
1533
    typedata[5] = (num_optional << 16) | num_params;
1534 1535 1536 1537

    /* NOTE: High word of typedata[3] is total size of FUNCDESC + size of all ELEMDESCs for params + TYPEDESCs for pointer params and return types. */
    /* That is, total memory allocation required to reconstitute the FUNCDESC in its entirety. */
    typedata[3] += (16 /*sizeof(ELEMDESC)*/ * num_params) << 16;
1538
    typedata[3] += (24 /*sizeof(PARAMDESCEX)*/ * num_defaults) << 16;
1539

1540
    switch(extra_attr) {
1541 1542 1543 1544
    default:
        if(extra_attr > 7 + num_params) warning("unknown number of optional attrs\n");
        /* typedata[13..+num_params] = arg_custdata_offset handled in below loop */
    case 7: typedata[12] = func_custdata_offset;
1545 1546 1547
    case 6: typedata[11] = help_string_context;
    case 5: typedata[10] = -1;
    case 4: typedata[9] = -1;
Huw Davies's avatar
Huw Davies committed
1548
    case 3: typedata[8] = entry;
1549 1550 1551 1552 1553 1554
    case 2: typedata[7] = help_string_offset;
    case 1: typedata[6] = help_context;
    case 0:
        break;
    }

1555
    if (type_function_get_args(func->declspec.type))
1556 1557
    {
      i = 0;
1558
      LIST_FOR_EACH_ENTRY( arg, type_function_get_args(func->declspec.type), var_t, entry )
1559
      {
1560
        int paramflags = 0;
1561 1562
        int *paramdata = typedata + 6 + extra_attr + (num_defaults ? num_params : 0) + i * 3;
        int *defaultdata = num_defaults ? typedata + 6 + extra_attr + i : NULL;
1563
        int arg_custdata_offset = -1;
1564

1565 1566
        if(defaultdata) *defaultdata = -1;

1567
	    encode_var(typeinfo->typelib, arg->declspec.type, arg, paramdata, &decoded_size);
1568
        if (arg->attrs) LIST_FOR_EACH_ENTRY( attr, arg->attrs, const attr_t, entry ) {
1569
            switch(attr->type) {
1570 1571 1572
            case ATTR_CUSTOM:
                set_custdata_attr(typeinfo->typelib, attr->u.pval, &arg_custdata_offset);
                break;
1573
            case ATTR_DEFAULTVALUE:
1574 1575
              {
                paramflags |= 0x30; /* PARAMFLAG_FHASDEFAULT | PARAMFLAG_FOPT */
1576
                write_default_value(typeinfo->typelib, arg->declspec.type, (expr_t *)attr->u.pval, defaultdata);
1577 1578
                break;
              }
1579 1580 1581
            case ATTR_IN:
                paramflags |= 0x01; /* PARAMFLAG_FIN */
                break;
1582 1583 1584
            case ATTR_OPTIONAL:
                paramflags |= 0x10; /* PARAMFLAG_FOPT */
                break;
1585 1586 1587
            case ATTR_OUT:
                paramflags |= 0x02; /* PARAMFLAG_FOUT */
                break;
1588 1589 1590 1591
            case ATTR_PARAMLCID:
                paramflags |= 0x04; /* PARAMFLAG_LCID */
                lcid_retval_count++;
                break;
1592 1593
            case ATTR_RETVAL:
                paramflags |= 0x08; /* PARAMFLAG_FRETVAL */
1594
                lcid_retval_count++;
1595 1596 1597 1598 1599
                break;
            default:
                chat("unhandled param attr %d\n", attr->type);
                break;
            }
1600 1601 1602
            if(extra_attr > 7 + i) {
                typedata[13+i] = arg_custdata_offset;
            }
1603
        }
1604 1605
	paramdata[1] = -1;
	paramdata[2] = paramflags;
1606
	typedata[3] += decoded_size << 16;
1607

1608 1609
        i++;
      }
1610 1611
    }

1612 1613 1614 1615 1616
    if(lcid_retval_count == 1)
        typedata[4] |= 0x4000;
    else if(lcid_retval_count == 2)
        typedata[4] |= 0x8000;

1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
    if(typeinfo->funcs_allocated == 0) {
        typeinfo->funcs_allocated = 10;
        typeinfo->func_indices = xmalloc(typeinfo->funcs_allocated * sizeof(int));
        typeinfo->func_names   = xmalloc(typeinfo->funcs_allocated * sizeof(int));
        typeinfo->func_offsets = xmalloc(typeinfo->funcs_allocated * sizeof(int));
    }
    if(typeinfo->funcs_allocated == (typeinfo->typeinfo->cElement & 0xffff)) {
        typeinfo->funcs_allocated *= 2;
        typeinfo->func_indices = xrealloc(typeinfo->func_indices, typeinfo->funcs_allocated * sizeof(int));
        typeinfo->func_names   = xrealloc(typeinfo->func_names,   typeinfo->funcs_allocated * sizeof(int));
        typeinfo->func_offsets = xrealloc(typeinfo->func_offsets, typeinfo->funcs_allocated * sizeof(int));
    }

1630
    /* update the index data */
1631 1632
    typeinfo->func_indices[typeinfo->typeinfo->cElement & 0xffff] = id; 
    typeinfo->func_offsets[typeinfo->typeinfo->cElement & 0xffff] = offset;
Huw Davies's avatar
Huw Davies committed
1633
    typeinfo->func_names[typeinfo->typeinfo->cElement & 0xffff] = name_offset;
1634 1635 1636 1637 1638 1639

    /* ??? */
    if (!typeinfo->typeinfo->res2) typeinfo->typeinfo->res2 = 0x20;
    typeinfo->typeinfo->res2 <<= 1;
    /* ??? */
    if (index < 2) typeinfo->typeinfo->res2 += num_params << 4;
1640 1641 1642 1643

    if (typeinfo->typeinfo->res3 == -1) typeinfo->typeinfo->res3 = 0;
    typeinfo->typeinfo->res3 += 0x38 + num_params * 0x10;
    if(num_defaults) typeinfo->typeinfo->res3 += num_params * 0x4;
1644 1645

    /* adjust size of VTBL */
Huw Davies's avatar
Huw Davies committed
1646
    if(funckind != 0x3 /* FUNC_STATIC */)
1647
        typeinfo->typeinfo->cbSizeVft += pointer_size;
1648 1649 1650 1651

    /* Increment the number of function elements */
    typeinfo->typeinfo->cElement += 1;

Huw Davies's avatar
Huw Davies committed
1652
    namedata = typeinfo->typelib->typelib_segment_data[MSFT_SEG_NAME] + name_offset;
1653 1654
    if (*((INT *)namedata) == -1) {
	*((INT *)namedata) = typeinfo->typelib->typelib_typeinfo_offsets[typeinfo->typeinfo->typekind >> 16];
1655
        if(typeinfo->typekind == TKIND_MODULE)
Huw Davies's avatar
Huw Davies committed
1656 1657
            namedata[9] |= 0x10;
    } else
Huw Davies's avatar
Huw Davies committed
1658
        namedata[9] &= ~0x10;
Huw Davies's avatar
Huw Davies committed
1659

1660
    if(typeinfo->typekind == TKIND_MODULE)
Huw Davies's avatar
Huw Davies committed
1661
        namedata[9] |= 0x20;
1662

1663
    if (type_function_get_args(func->declspec.type))
1664 1665
    {
        i = 0;
1666
        LIST_FOR_EACH_ENTRY( arg, type_function_get_args(func->declspec.type), var_t, entry )
1667
        {
1668 1669 1670 1671 1672 1673 1674
            /* don't give the last arg of a [propput*] func a name */
            if(i != num_params - 1 || (invokekind != 0x4 /* INVOKE_PROPERTYPUT */ && invokekind != 0x8 /* INVOKE_PROPERTYPUTREF */))
            {
                int *paramdata = typedata + 6 + extra_attr + (num_defaults ? num_params : 0) + i * 3;
                offset = ctl2_alloc_name(typeinfo->typelib, arg->name);
                paramdata[1] = offset;
            }
1675
            i++;
1676
        }
1677 1678 1679 1680 1681 1682
    }
    return S_OK;
}

static HRESULT add_var_desc(msft_typeinfo_t *typeinfo, UINT index, var_t* var)
{
1683 1684
    int offset, id;
    unsigned int typedata_size;
1685
    int extra_attr = 0;
1686
    INT *typedata;
1687
    unsigned int var_datawidth, var_alignment = 0;
Huw Davies's avatar
Huw Davies committed
1688
    int var_type_size, var_kind = 0 /* VAR_PERINSTANCE */; 
1689 1690
    int alignment;
    int varflags = 0;
1691
    const attr_t *attr;
1692
    unsigned char *namedata;
1693
    int var_num = (typeinfo->typeinfo->cElement >> 16) & 0xffff;
1694
    int var_custdata_offset = -1;
1695

1696 1697 1698
    if (!var->name)
        var->name = gen_name();

1699
    chat("add_var_desc(%d, %s)\n", index, var->name);
1700

1701
    id = 0x40000000 + index;
1702

1703 1704
    if (var->attrs) LIST_FOR_EACH_ENTRY( attr, var->attrs, const attr_t, entry ) {
        expr_t *expr = attr->u.pval;
1705
        switch(attr->type) {
1706 1707 1708
        case ATTR_BINDABLE:
            varflags |= 0x04; /* VARFLAG_FBINDABLE */
            break;
1709 1710 1711 1712
        case ATTR_CUSTOM:
            extra_attr = max(extra_attr,4);
            set_custdata_attr(typeinfo->typelib, attr->u.pval, &var_custdata_offset);
            break;
1713 1714 1715
        case ATTR_DEFAULTBIND:
            varflags |= 0x20; /* VARFLAG_FDEFAULTBIND */
            break;
1716 1717 1718 1719 1720 1721
        case ATTR_DEFAULTCOLLELEM:
            varflags |= 0x100; /* VARFLAG_FDEFAULTCOLLELEM */
            break;
        case ATTR_DISPLAYBIND:
            varflags |= 0x10; /* VARFLAG_FDISPLAYBIND */
            break;
1722 1723 1724
        case ATTR_HIDDEN:
            varflags |= 0x40; /* VARFLAG_FHIDDEN */
            break;
1725
        case ATTR_ID:
Jacek Caban's avatar
Jacek Caban committed
1726
            id = expr->cval;
1727
            break;
1728 1729 1730 1731 1732 1733
        case ATTR_IMMEDIATEBIND:
            varflags |= 0x1000; /* VARFLAG_FIMMEDIATEBIND */
            break;
        case ATTR_NONBROWSABLE:
            varflags |= 0x400; /* VARFLAG_FNONBROWSABLE */
            break;
1734 1735 1736
        case ATTR_READONLY:
            varflags |= 0x01; /* VARFLAG_FREADONLY */
            break;
1737 1738 1739 1740
        /* FIXME: VARFLAG_FREPLACEABLE */
        case ATTR_REQUESTEDIT:
            varflags |= 0x08; /* VARFLAG_FREQUESTEDIT */
            break;
1741 1742 1743 1744 1745 1746
        case ATTR_RESTRICTED:
            varflags |= 0x80; /* VARFLAG_FRESTRICTED */
            break;
        case ATTR_SOURCE:
            varflags |= 0x02; /* VARFLAG_FSOURCE */
            break;
1747 1748 1749
        case ATTR_UIDEFAULT:
            varflags |= 0x0200; /* VARFLAG_FUIDEFAULT */
            break;
1750 1751 1752 1753 1754
        default:
            break;
        }
    }

1755
    /* allocate type data space for us */
1756
    typedata_size = 0x14 + extra_attr * sizeof(int);
1757 1758 1759 1760 1761

    if (!typeinfo->var_data) {
        typeinfo->var_data = xmalloc(0x100);
        typeinfo->var_data_allocated = 0x100;
        typeinfo->var_data[0] = 0;
1762 1763
    }

1764 1765 1766 1767 1768 1769 1770 1771 1772
    if(typeinfo->var_data[0] + typedata_size + sizeof(int) > typeinfo->var_data_allocated) {
        typeinfo->var_data_allocated = max(typeinfo->var_data_allocated * 2,
                                            typeinfo->var_data[0] + typedata_size + sizeof(int));
        typeinfo->var_data = xrealloc(typeinfo->var_data, typeinfo->var_data_allocated);
    }

    offset = typeinfo->var_data[0];
    typeinfo->var_data[0] += typedata_size;
    typedata = typeinfo->var_data + (offset >> 2) + 1;
1773 1774

    /* fill out the basic type information */
1775
    typedata[0] = typedata_size | (index << 16);
1776 1777 1778
    typedata[2] = varflags;
    typedata[3] = (36 /*sizeof(VARDESC)*/ << 16) | 0;

1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
    if(typeinfo->vars_allocated == 0) {
        typeinfo->vars_allocated = 10;
        typeinfo->var_indices = xmalloc(typeinfo->vars_allocated * sizeof(int));
        typeinfo->var_names   = xmalloc(typeinfo->vars_allocated * sizeof(int));
        typeinfo->var_offsets = xmalloc(typeinfo->vars_allocated * sizeof(int));
    }
    if(typeinfo->vars_allocated == var_num) {
        typeinfo->vars_allocated *= 2;
        typeinfo->var_indices = xrealloc(typeinfo->var_indices, typeinfo->vars_allocated * sizeof(int));
        typeinfo->var_names   = xrealloc(typeinfo->var_names,   typeinfo->vars_allocated * sizeof(int));
        typeinfo->var_offsets = xrealloc(typeinfo->var_offsets, typeinfo->vars_allocated * sizeof(int));
    }
1791
    /* update the index data */
1792
    typeinfo->var_indices[var_num] = id;
1793 1794
    typeinfo->var_names[var_num] = -1;
    typeinfo->var_offsets[var_num] = offset;
1795 1796

    /* figure out type widths and whatnot */
1797 1798
    var_datawidth = type_memsize_and_alignment(var->declspec.type, &var_alignment);
    encode_var(typeinfo->typelib, var->declspec.type, var, &typedata[1], &var_type_size);
1799 1800 1801 1802

    /* pad out starting position to data width */
    typeinfo->datawidth += var_alignment - 1;
    typeinfo->datawidth &= ~(var_alignment - 1);
Huw Davies's avatar
Huw Davies committed
1803

1804
    switch(typeinfo->typekind) {
1805
    case TKIND_ENUM:
1806
        write_int_value(typeinfo->typelib, &typedata[4], VT_I4, var->eval->cval);
Huw Davies's avatar
Huw Davies committed
1807 1808 1809
        var_kind = 2; /* VAR_CONST */
        var_type_size += 16; /* sizeof(VARIANT) */
        typeinfo->datawidth = var_datawidth;
1810 1811
        break;
    case TKIND_RECORD:
Huw Davies's avatar
Huw Davies committed
1812 1813
        typedata[4] = typeinfo->datawidth;
        typeinfo->datawidth += var_datawidth;
1814
        break;
1815
    case TKIND_UNION:
1816
        typedata[4] = 0;
1817 1818
        typeinfo->datawidth = max(typeinfo->datawidth, var_datawidth);
        break;
1819 1820
    case TKIND_DISPATCH:
        var_kind = 3; /* VAR_DISPATCH */
1821
        typedata[4] = 0;
1822
        typeinfo->datawidth = pointer_size;
1823 1824
        break;
    default:
1825
        error("add_var_desc: unhandled type kind %d\n", typeinfo->typekind);
1826
        break;
Huw Davies's avatar
Huw Davies committed
1827
    }
1828 1829

    /* add type description size to total required allocation */
Huw Davies's avatar
Huw Davies committed
1830
    typedata[3] += var_type_size << 16 | var_kind;
1831

1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
    switch(extra_attr) {
    case 5: typedata[9] = -1 /*help_string_context*/;
    case 4: typedata[8] = var_custdata_offset;
    case 3: typedata[7] = -1;
    case 2: typedata[6] = -1 /*help_string_offset*/;
    case 1: typedata[5] = -1 /*help_context*/;
    case 0:
        break;
    default:
        warning("unknown number of optional attrs\n");
    }

1844 1845 1846 1847
    /* fix type alignment */
    alignment = (typeinfo->typeinfo->typekind >> 11) & 0x1f;
    if (alignment < var_alignment) {
	alignment = var_alignment;
Huw Davies's avatar
Huw Davies committed
1848 1849
	typeinfo->typeinfo->typekind &= ~0xffc0;
	typeinfo->typeinfo->typekind |= alignment << 11 | alignment << 6;
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
    }

    /* ??? */
    if (!typeinfo->typeinfo->res2) typeinfo->typeinfo->res2 = 0x1a;
    if ((index == 0) || (index == 1) || (index == 2) || (index == 4) || (index == 9)) {
	typeinfo->typeinfo->res2 <<= 1;
    }

    /* ??? */
    if (typeinfo->typeinfo->res3 == -1) typeinfo->typeinfo->res3 = 0;
    typeinfo->typeinfo->res3 += 0x2c;

    /* increment the number of variable elements */
    typeinfo->typeinfo->cElement += 0x10000;

    /* pad data width to alignment */
    typeinfo->typeinfo->size = (typeinfo->datawidth + (alignment - 1)) & ~(alignment - 1);

    offset = ctl2_alloc_name(typeinfo->typelib, var->name);
    if (offset == -1) return E_OUTOFMEMORY;

    namedata = typeinfo->typelib->typelib_segment_data[MSFT_SEG_NAME] + offset;
    if (*((INT *)namedata) == -1) {
	*((INT *)namedata) = typeinfo->typelib->typelib_typeinfo_offsets[typeinfo->typeinfo->typekind >> 16];
1874
        if(typeinfo->typekind != TKIND_DISPATCH)
1875
            namedata[9] |= 0x10;
Huw Davies's avatar
Huw Davies committed
1876 1877 1878
    } else
        namedata[9] &= ~0x10;

1879
    if (typeinfo->typekind == TKIND_ENUM) {
1880 1881
	namedata[9] |= 0x20;
    }
1882
    typeinfo->var_names[var_num] = offset;
1883 1884 1885 1886

    return S_OK;
}

1887
static HRESULT add_impl_type(msft_typeinfo_t *typeinfo, type_t *ref, importinfo_t *importinfo)
Huw Davies's avatar
Huw Davies committed
1888
{
1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
    if(importinfo) {
        alloc_importinfo(typeinfo->typelib, importinfo);
        typeinfo->typeinfo->datatype1 = importinfo->offset+1;
    }else {
        if(ref->typelib_idx == -1)
            add_interface_typeinfo(typeinfo->typelib, ref);
        if(ref->typelib_idx == -1)
            error("add_impl_type: unable to add inherited interface\n");

        typeinfo->typeinfo->datatype1 = typeinfo->typelib->typelib_typeinfo_offsets[ref->typelib_idx];
    }
Huw Davies's avatar
Huw Davies committed
1900 1901 1902 1903 1904

    typeinfo->typeinfo->cImplTypes++;
    return S_OK;
}

1905
static msft_typeinfo_t *create_msft_typeinfo(msft_typelib_t *typelib, enum type_kind kind,
1906
                                             const char *name, const attr_list_t *attrs)
1907
{
1908
    const attr_t *attr;
1909 1910 1911 1912 1913 1914
    msft_typeinfo_t *msft_typeinfo;
    int nameoffset;
    int typeinfo_offset;
    MSFT_TypeInfoBase *typeinfo;
    MSFT_GuidEntry guidentry;

1915
    chat("create_msft_typeinfo: name %s kind %d index %d\n", name, kind, typelib->typelib_header.nrtypeinfos);
1916 1917

    msft_typeinfo = xmalloc(sizeof(*msft_typeinfo));
1918
    memset( msft_typeinfo, 0, sizeof(*msft_typeinfo) );
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928

    msft_typeinfo->typelib = typelib;

    nameoffset = ctl2_alloc_name(typelib, name);
    typeinfo_offset = ctl2_alloc_typeinfo(typelib, nameoffset);
    typeinfo = (MSFT_TypeInfoBase *)&typelib->typelib_segment_data[MSFT_SEG_TYPEINFO][typeinfo_offset];

    typelib->typelib_segment_data[MSFT_SEG_NAME][nameoffset + 9] = 0x38;
    *((int *)&typelib->typelib_segment_data[MSFT_SEG_NAME][nameoffset]) = typeinfo_offset;

1929
    msft_typeinfo->typekind = kind;
1930 1931
    msft_typeinfo->typeinfo = typeinfo;

Huw Davies's avatar
Huw Davies committed
1932
    typeinfo->typekind |= kind | 0x20;
1933

Huw Davies's avatar
Huw Davies committed
1934 1935 1936
    if(kind == TKIND_COCLASS)
        typeinfo->flags |= 0x2; /* TYPEFLAG_FCANCREATE */

1937
    if (attrs) LIST_FOR_EACH_ENTRY( attr, attrs, const attr_t, entry ) {
1938
        switch(attr->type) {
1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
        case ATTR_AGGREGATABLE:
            if (kind == TKIND_COCLASS)
                typeinfo->flags |= 0x400; /* TYPEFLAG_FAGGREGATABLE */
            break;

        case ATTR_APPOBJECT:
            if (kind == TKIND_COCLASS)
                typeinfo->flags |= 0x1; /* TYPEFLAG_FAPPOBJECT */
            break;

        case ATTR_CONTROL:
            if (kind == TKIND_COCLASS)
                typeinfo->flags |= 0x20; /* TYPEFLAG_FCONTROL */
            break;
1953 1954 1955
        case ATTR_CUSTOM:
            set_custdata_attr(typelib, attr->u.pval, &typeinfo->oCustData);
            break;
Huw Davies's avatar
Huw Davies committed
1956 1957 1958 1959 1960 1961
        case ATTR_DLLNAME:
          {
            int offset = ctl2_alloc_string(typelib, attr->u.pval);
            typeinfo->datatype1 = offset;
            break;
          }
1962 1963

        case ATTR_DUAL:
1964
            /* FIXME: check interface is compatible */
1965
            typeinfo->typekind = (typeinfo->typekind & ~0xff) | 0x34;
1966
            typeinfo->flags |= 0x140; /* TYPEFLAG_FDUAL | TYPEFLAG_FOLEAUTOMATION */
1967 1968
            break;

1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
        case ATTR_HELPCONTEXT:
          {
            expr_t *expr = (expr_t*)attr->u.pval;
            typeinfo->helpcontext = expr->cval;
            break;
          }
        case ATTR_HELPSTRING:
          {
            int offset = ctl2_alloc_string(typelib, attr->u.pval);
            if (offset == -1) break;
            typeinfo->docstringoffs = offset;
            break;
          }
        case ATTR_HELPSTRINGCONTEXT:
          {
            expr_t *expr = (expr_t*)attr->u.pval;
            typeinfo->helpstringcontext = expr->cval;
            break;
          }
1988 1989 1990 1991
        case ATTR_HIDDEN:
            typeinfo->flags |= 0x10; /* TYPEFLAG_FHIDDEN */
            break;

1992 1993 1994
        case ATTR_LICENSED:
            typeinfo->flags |= 0x04; /* TYPEFLAG_FLICENSED */
            break;
1995

Huw Davies's avatar
Huw Davies committed
1996 1997 1998 1999
        case ATTR_NONCREATABLE:
            typeinfo->flags &= ~0x2; /* TYPEFLAG_FCANCREATE */
            break;

2000 2001 2002 2003
        case ATTR_NONEXTENSIBLE:
            typeinfo->flags |= 0x80; /* TYPEFLAG_FNONEXTENSIBLE */
            break;

2004 2005 2006 2007
        case ATTR_OLEAUTOMATION:
            typeinfo->flags |= 0x100; /* TYPEFLAG_FOLEAUTOMATION */
            break;

2008 2009
        /* FIXME: TYPEFLAG_FPREDCLID */

2010 2011 2012
        case ATTR_PROXY:
            typeinfo->flags |= 0x4000; /* TYPEFLAG_FPROXY */
            break;
2013 2014

        /* FIXME: TYPEFLAG_FREPLACEABLE */
Huw Davies's avatar
Huw Davies committed
2015

2016 2017 2018 2019 2020
        case ATTR_RESTRICTED:
            typeinfo->flags |= 0x200; /* TYPEFLAG_FRESTRICTED */
            break;

        case ATTR_UUID:
2021 2022 2023 2024 2025 2026 2027 2028 2029
            guidentry.guid = *(GUID*)attr->u.pval;
            guidentry.hreftype = typelib->typelib_typeinfo_offsets[typeinfo->typekind >> 16];
            guidentry.next_hash = -1;
            typeinfo->posguid = ctl2_alloc_guid(typelib, &guidentry);
#if 0
            if (IsEqualIID(guid, &IID_IDispatch)) {
                typelib->typelib_header.dispatchpos = typelib->typelib_typeinfo_offsets[typeinfo->typekind >> 16];
            }
#endif
2030
            break;
2031 2032 2033 2034 2035 2036 2037

        case ATTR_VERSION:
            typeinfo->version = attr->u.ival;
            break;

        default:
            break;
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
        }
    }

    if (typelib->last_typeinfo) typelib->last_typeinfo->next_typeinfo = msft_typeinfo;
    typelib->last_typeinfo = msft_typeinfo;
    if (!typelib->typeinfos) typelib->typeinfos = msft_typeinfo;


    return msft_typeinfo;
}

2049 2050
static void add_dispatch(msft_typelib_t *typelib)
{
2051
    int guid_offset, impfile_offset, hash_key;
2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
    MSFT_GuidEntry guidentry;
    MSFT_ImpInfo impinfo;
    GUID stdole =        {0x00020430,0x0000,0x0000,{0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46}};
    GUID iid_idispatch = {0x00020400,0x0000,0x0000,{0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46}};

    if(typelib->typelib_header.dispatchpos != -1) return;

    guidentry.guid = stdole;
    guidentry.hreftype = 2;
    guidentry.next_hash = -1;
2062 2063 2064 2065
    hash_key = ctl2_hash_guid(&guidentry.guid);
    guid_offset = ctl2_find_guid(typelib, hash_key, &guidentry.guid);
    if (guid_offset == -1)
        guid_offset = ctl2_alloc_guid(typelib, &guidentry);
2066 2067 2068 2069 2070
    impfile_offset = alloc_importfile(typelib, guid_offset, 2, 0, "stdole2.tlb");

    guidentry.guid = iid_idispatch;
    guidentry.hreftype = 1;
    guidentry.next_hash = -1;
2071
    impinfo.flags = TKIND_INTERFACE << 24 | MSFT_IMPINFO_OFFSET_IS_GUID;
2072
    impinfo.oImpFile = impfile_offset;
2073 2074 2075 2076 2077
    hash_key = ctl2_hash_guid(&guidentry.guid);
    guid_offset = ctl2_find_guid(typelib, hash_key, &guidentry.guid);
    if (guid_offset == -1)
        guid_offset = ctl2_alloc_guid(typelib, &guidentry);
    impinfo.oGuid = guid_offset;
2078
    typelib->typelib_header.dispatchpos = alloc_msft_importinfo(typelib, &impinfo) | 0x01;
2079 2080 2081
}

static void add_dispinterface_typeinfo(msft_typelib_t *typelib, type_t *dispinterface)
2082
{
2083 2084 2085 2086
    int num_parents = 0, num_funcs = 0;
    importinfo_t *importinfo = NULL;
    const statement_t *stmt_func;
    type_t *inherit, *ref;
2087
    int idx = 0;
Rob Shearman's avatar
Rob Shearman committed
2088
    var_t *func;
2089 2090 2091
    var_t *var;
    msft_typeinfo_t *msft_typeinfo;

2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
    if (-1 < dispinterface->typelib_idx)
        return;

    inherit = type_dispiface_get_inherit(dispinterface);

    if (inherit)
    {
        importinfo = find_importinfo(typelib, inherit->name);

        if (!importinfo && type_iface_get_inherit(inherit) && inherit->typelib_idx == -1)
            add_interface_typeinfo(typelib, inherit);
    }

    /* check typelib_idx again, it could have been added while resolving the parent interface */
2106 2107 2108
    if (-1 < dispinterface->typelib_idx)
        return;

Huw Davies's avatar
Huw Davies committed
2109
    dispinterface->typelib_idx = typelib->typelib_header.nrtypeinfos;
2110
    msft_typeinfo = create_msft_typeinfo(typelib, TKIND_DISPATCH, dispinterface->name,
2111
                                         dispinterface->attrs);
2112

2113
    msft_typeinfo->typeinfo->size = pointer_size;
2114
    msft_typeinfo->typeinfo->typekind |= pointer_size << 11 | pointer_size << 6;
2115 2116 2117

    msft_typeinfo->typeinfo->flags |= 0x1000; /* TYPEFLAG_FDISPATCHABLE */
    add_dispatch(typelib);
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138

    if (inherit)
    {
        add_impl_type(msft_typeinfo, inherit, importinfo);
        msft_typeinfo->typeinfo->typekind |= 0x10;
    }

    /* count the number of inherited interfaces and non-local functions */
    for (ref = inherit; ref; ref = type_iface_get_inherit(ref))
    {
        num_parents++;
        STATEMENTS_FOR_EACH_FUNC( stmt_func, type_iface_get_stmts(ref) )
        {
            var_t *func = stmt_func->u.var;
            if (!is_local(func->attrs)) num_funcs++;
        }
    }
    msft_typeinfo->typeinfo->datatype2 = num_funcs << 16 | num_parents;
    msft_typeinfo->typeinfo->cbSizeVft = num_funcs * pointer_size;

    msft_typeinfo->typeinfo->cImplTypes = 1;    /* IDispatch */
2139

2140 2141
    /* count the no of methods, as the variable indices come after the funcs */
    if (dispinterface->details.iface->disp_methods)
Rob Shearman's avatar
Rob Shearman committed
2142
        LIST_FOR_EACH_ENTRY( func, dispinterface->details.iface->disp_methods, var_t, entry )
2143
            idx++;
2144

2145 2146
    if (type_dispiface_get_props(dispinterface))
        LIST_FOR_EACH_ENTRY( var, type_dispiface_get_props(dispinterface), var_t, entry )
2147
            add_var_desc(msft_typeinfo, idx++, var);
2148

2149
    if (type_dispiface_get_methods(dispinterface))
2150 2151
    {
        idx = 0;
Rob Shearman's avatar
Rob Shearman committed
2152 2153
        LIST_FOR_EACH_ENTRY( func, type_dispiface_get_methods(dispinterface), var_t, entry )
            if(add_func_desc(msft_typeinfo, func, idx) == S_OK)
2154
                idx++;
2155
    }
2156 2157 2158 2159

        typelib->typelib->reg_ifaces = xrealloc(typelib->typelib->reg_ifaces,
                (typelib->typelib->reg_iface_count + 1) * sizeof(dispinterface));
    typelib->typelib->reg_ifaces[typelib->typelib->reg_iface_count++] = dispinterface;
2160
}
Huw Davies's avatar
Huw Davies committed
2161

2162 2163 2164
static void add_interface_typeinfo(msft_typelib_t *typelib, type_t *interface)
{
    int idx = 0;
2165
    const statement_t *stmt_func;
2166
    type_t *ref;
2167
    msft_typeinfo_t *msft_typeinfo;
2168
    importinfo_t *ref_importinfo = NULL;
2169
    int num_parents = 0, num_funcs = 0;
2170
    type_t *inherit;
2171
    const type_t *derived;
2172

2173 2174 2175
    if (-1 < interface->typelib_idx)
        return;

2176 2177 2178 2179 2180 2181
    if (!interface->details.iface)
    {
        error( "interface %s is referenced but not defined\n", interface->name );
        return;
    }

2182 2183 2184 2185
    if (is_attr(interface->attrs, ATTR_DISPINTERFACE)) {
        add_dispinterface_typeinfo(typelib, interface);
        return;
    }
2186 2187 2188 2189

    /* midl adds the parent interface first, unless the parent itself
       has no parent (i.e. it stops before IUnknown). */

2190
    inherit = type_iface_get_inherit(interface);
2191

2192 2193 2194 2195 2196 2197
    if(inherit) {
        ref_importinfo = find_importinfo(typelib, inherit->name);

        if(!ref_importinfo && type_iface_get_inherit(inherit) &&
           inherit->typelib_idx == -1)
            add_interface_typeinfo(typelib, inherit);
2198
    }
2199

2200 2201 2202 2203
    /* check typelib_idx again, it could have been added while resolving the parent interface */
    if (-1 < interface->typelib_idx)
        return;

2204
    interface->typelib_idx = typelib->typelib_header.nrtypeinfos;
2205
    msft_typeinfo = create_msft_typeinfo(typelib, TKIND_INTERFACE, interface->name, interface->attrs);
2206
    msft_typeinfo->typeinfo->size = pointer_size;
2207 2208
    msft_typeinfo->typeinfo->typekind |= 0x0200;
    msft_typeinfo->typeinfo->typekind |= pointer_size << 11;
2209

2210
    for (derived = inherit; derived; derived = type_iface_get_inherit(derived))
2211 2212 2213
        if (derived->name && !strcmp(derived->name, "IDispatch"))
            msft_typeinfo->typeinfo->flags |= 0x1000; /* TYPEFLAG_FDISPATCHABLE */

2214 2215 2216
    if(type_iface_get_inherit(interface))
        add_impl_type(msft_typeinfo, type_iface_get_inherit(interface),
                      ref_importinfo);
Huw Davies's avatar
Huw Davies committed
2217

2218
    /* count the number of inherited interfaces and non-local functions */
2219
    for(ref = inherit; ref; ref = type_iface_get_inherit(ref)) {
2220
        num_parents++;
2221
        STATEMENTS_FOR_EACH_FUNC( stmt_func, type_iface_get_stmts(ref) ) {
2222 2223 2224
            var_t *func = stmt_func->u.var;
            if (!is_local(func->attrs)) num_funcs++;
        }
2225 2226
    }
    msft_typeinfo->typeinfo->datatype2 = num_funcs << 16 | num_parents;
2227
    msft_typeinfo->typeinfo->cbSizeVft = num_funcs * pointer_size;
2228

2229
    STATEMENTS_FOR_EACH_FUNC( stmt_func, type_iface_get_stmts(interface) ) {
2230 2231 2232 2233
        var_t *func = stmt_func->u.var;
        if(add_func_desc(msft_typeinfo, func, idx) == S_OK)
            idx++;
    }
2234 2235 2236 2237 2238 2239 2240

    if (is_attr(interface->attrs, ATTR_OLEAUTOMATION) || is_attr(interface->attrs, ATTR_DUAL))
    {
        typelib->typelib->reg_ifaces = xrealloc(typelib->typelib->reg_ifaces,
                (typelib->typelib->reg_iface_count + 1) * sizeof(interface));
        typelib->typelib->reg_ifaces[typelib->typelib->reg_iface_count++] = interface;
    }
2241 2242 2243 2244
}

static void add_structure_typeinfo(msft_typelib_t *typelib, type_t *structure)
{
2245
    var_list_t *fields;
2246
    int idx = 0;
2247
    var_t *cur;
2248 2249
    msft_typeinfo_t *msft_typeinfo;

2250 2251 2252
    if (-1 < structure->typelib_idx)
        return;

2253
    structure->typelib_idx = typelib->typelib_header.nrtypeinfos;
2254
    msft_typeinfo = create_msft_typeinfo(typelib, TKIND_RECORD, structure->name, structure->attrs);
2255 2256
    msft_typeinfo->typeinfo->size = 0;

2257 2258 2259 2260 2261 2262 2263 2264
    if (type_get_type(structure) == TYPE_STRUCT)
        fields = type_struct_get_fields(structure);
    else
        fields = type_encapsulated_union_get_fields(structure);

    if (fields)
    {
        LIST_FOR_EACH_ENTRY( cur, fields, var_t, entry )
2265
            add_var_desc(msft_typeinfo, idx++, cur);
2266
    }
2267 2268
}

Huw Davies's avatar
Huw Davies committed
2269 2270 2271
static void add_enum_typeinfo(msft_typelib_t *typelib, type_t *enumeration)
{
    int idx = 0;
2272
    var_t *cur;
Huw Davies's avatar
Huw Davies committed
2273 2274
    msft_typeinfo_t *msft_typeinfo;

2275 2276 2277
    if (-1 < enumeration->typelib_idx)
        return;

Huw Davies's avatar
Huw Davies committed
2278
    enumeration->typelib_idx = typelib->typelib_header.nrtypeinfos;
2279
    msft_typeinfo = create_msft_typeinfo(typelib, TKIND_ENUM, enumeration->name, enumeration->attrs);
Huw Davies's avatar
Huw Davies committed
2280 2281
    msft_typeinfo->typeinfo->size = 0;

2282 2283
    if (type_enum_get_values(enumeration))
        LIST_FOR_EACH_ENTRY( cur, type_enum_get_values(enumeration), var_t, entry )
2284
            add_var_desc(msft_typeinfo, idx++, cur);
Huw Davies's avatar
Huw Davies committed
2285 2286
}

2287 2288 2289 2290 2291 2292 2293 2294 2295
static void add_union_typeinfo(msft_typelib_t *typelib, type_t *tunion)
{
    int idx = 0;
    var_t *cur;
    msft_typeinfo_t *msft_typeinfo;

    if (-1 < tunion->typelib_idx)
        return;

2296 2297 2298
    if (!tunion->name)
        tunion->name = gen_name();

2299 2300 2301 2302 2303 2304 2305 2306 2307
    tunion->typelib_idx = typelib->typelib_header.nrtypeinfos;
    msft_typeinfo = create_msft_typeinfo(typelib, TKIND_UNION, tunion->name, tunion->attrs);
    msft_typeinfo->typeinfo->size = 0;

    if (type_union_get_cases(tunion))
        LIST_FOR_EACH_ENTRY(cur, type_union_get_cases(tunion), var_t, entry)
            add_var_desc(msft_typeinfo, idx++, cur);
}

2308
static void add_typedef_typeinfo(msft_typelib_t *typelib, type_t *tdef)
Huw Davies's avatar
Huw Davies committed
2309
{
2310
    msft_typeinfo_t *msft_typeinfo = NULL;
2311 2312
    int datatype1, datatype2, duplicate = 0;
    unsigned int size, alignment = 0;
2313
    type_t *type;
Huw Davies's avatar
Huw Davies committed
2314

2315
    if (-1 < tdef->typelib_idx)
2316 2317
        return;

2318
    type = type_alias_get_aliasee_type(tdef);
2319 2320 2321 2322 2323 2324

    if (!type->name || strcmp(tdef->name, type->name) != 0)
    {
        tdef->typelib_idx = typelib->typelib_header.nrtypeinfos;
        msft_typeinfo = create_msft_typeinfo(typelib, TKIND_ALIAS, tdef->name, tdef->attrs);
    }
2325 2326
    else
        duplicate = 1;
2327

2328 2329
    encode_type(typelib, get_type_vt(type), type, &datatype1, &datatype2);
    size = type_memsize_and_alignment(type, &alignment);
2330 2331 2332 2333 2334 2335 2336 2337

    if (msft_typeinfo)
    {
        msft_typeinfo->typeinfo->datatype1 = datatype1;
        msft_typeinfo->typeinfo->size = size;
        msft_typeinfo->typeinfo->datatype2 = datatype2;
        msft_typeinfo->typeinfo->typekind |= (alignment << 11 | alignment << 6);
    }
2338 2339 2340 2341

    /* avoid adding duplicate type definitions */
    if (duplicate)
        tdef->typelib_idx = type->typelib_idx;
Huw Davies's avatar
Huw Davies committed
2342 2343
}

2344
static void add_coclass_typeinfo(msft_typelib_t *typelib, type_t *cls)
Huw Davies's avatar
Huw Davies committed
2345 2346
{
    msft_typeinfo_t *msft_typeinfo;
2347
    typeref_t *iref;
Huw Davies's avatar
Huw Davies committed
2348 2349 2350
    int num_ifaces = 0, offset, i;
    MSFT_RefRecord *ref, *first = NULL, *first_source = NULL;
    int have_default = 0, have_default_source = 0;
2351
    const attr_t *attr;
2352
    typeref_list_t *ifaces;
Huw Davies's avatar
Huw Davies committed
2353

2354 2355 2356
    if (-1 < cls->typelib_idx)
        return;

2357
    cls->typelib_idx = typelib->typelib_header.nrtypeinfos;
2358
    msft_typeinfo = create_msft_typeinfo(typelib, TKIND_COCLASS, cls->name, cls->attrs);
Huw Davies's avatar
Huw Davies committed
2359

2360
    ifaces = type_coclass_get_ifaces(cls);
2361
    if (ifaces) LIST_FOR_EACH_ENTRY( iref, ifaces, typeref_t, entry ) num_ifaces++;
Huw Davies's avatar
Huw Davies committed
2362 2363 2364

    offset = msft_typeinfo->typeinfo->datatype1 = ctl2_alloc_segment(typelib, MSFT_SEG_REFERENCES,
                                                                     num_ifaces * sizeof(*ref), 0);
2365 2366

    i = 0;
2367
    if (ifaces) LIST_FOR_EACH_ENTRY( iref, ifaces, typeref_t, entry ) {
2368 2369
        if(iref->type->typelib_idx == -1)
            add_interface_typeinfo(typelib, iref->type);
Huw Davies's avatar
Huw Davies committed
2370
        ref = (MSFT_RefRecord*) (typelib->typelib_segment_data[MSFT_SEG_REFERENCES] + offset + i * sizeof(*ref));
2371
        ref->reftype = typelib->typelib_typeinfo_offsets[iref->type->typelib_idx];
Huw Davies's avatar
Huw Davies committed
2372 2373 2374 2375 2376 2377
        ref->flags = 0;
        ref->oCustData = -1;
        ref->onext = -1;
        if(i < num_ifaces - 1)
            ref->onext = offset + (i + 1) * sizeof(*ref);

2378
        if (iref->attrs) LIST_FOR_EACH_ENTRY( attr, iref->attrs, const attr_t, entry ) {
Huw Davies's avatar
Huw Davies committed
2379 2380 2381 2382
            switch(attr->type) {
            case ATTR_DEFAULT:
                ref->flags |= 0x1; /* IMPLTYPEFLAG_FDEFAULT */
                break;
2383 2384 2385
            case ATTR_DEFAULTVTABLE:
                ref->flags |= 0x8; /* IMPLTYPEFLAG_FDEFAULTVTABLE */
                break;
Huw Davies's avatar
Huw Davies committed
2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412
            case ATTR_RESTRICTED:
                ref->flags |= 0x4; /* IMPLTYPEFLAG_FRESTRICTED */
                break;
            case ATTR_SOURCE:
                ref->flags |= 0x2; /* IMPLTYPEFLAG_FSOURCE */
                break;
            default:
                warning("add_coclass_typeinfo: unhandled attr %d\n", attr->type);
            }
        }
        if(ref->flags & 0x1) { /* IMPLTYPEFLAG_FDEFAULT */
            if(ref->flags & 0x2) /* IMPLTYPEFLAG_SOURCE */
                have_default_source = 1;
            else
                have_default = 1;
        }

        /* If the interface is non-restricted and we haven't already had one then
           remember it so that we can use it as a default later */
        if((ref->flags & 0x4) == 0) { /* IMPLTYPEFLAG_FRESTRICTED */
            if(ref->flags & 0x2) { /* IMPLTYPEFLAG_FSOURCE */
                if(!first_source)
                    first_source = ref;
            }
            else if(!first)
                first = ref;
        }
2413
        i++;
Huw Davies's avatar
Huw Davies committed
2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
    }

    /* If we haven't had a default interface, then set the default flags on the
       first ones */
    if(!have_default && first)
        first->flags |= 0x1;
    if(!have_default_source && first_source)
        first_source->flags |= 0x1;

    msft_typeinfo->typeinfo->cImplTypes = num_ifaces;
2424
    msft_typeinfo->typeinfo->size = pointer_size;
Huw Davies's avatar
Huw Davies committed
2425 2426 2427
    msft_typeinfo->typeinfo->typekind |= 0x2200;
}

Huw Davies's avatar
Huw Davies committed
2428 2429 2430
static void add_module_typeinfo(msft_typelib_t *typelib, type_t *module)
{
    int idx = 0;
2431
    const statement_t *stmt;
Huw Davies's avatar
Huw Davies committed
2432 2433
    msft_typeinfo_t *msft_typeinfo;

2434 2435 2436
    if (-1 < module->typelib_idx)
        return;

Huw Davies's avatar
Huw Davies committed
2437
    module->typelib_idx = typelib->typelib_header.nrtypeinfos;
2438
    msft_typeinfo = create_msft_typeinfo(typelib, TKIND_MODULE, module->name, module->attrs);
Huw Davies's avatar
Huw Davies committed
2439 2440
    msft_typeinfo->typeinfo->typekind |= 0x0a00;

2441 2442 2443 2444 2445
    STATEMENTS_FOR_EACH_FUNC( stmt, module->details.module->stmts ) {
        var_t *func = stmt->u.var;
        if(add_func_desc(msft_typeinfo, func, idx) == S_OK)
            idx++;
    }
2446

Huw Davies's avatar
Huw Davies committed
2447 2448 2449
    msft_typeinfo->typeinfo->size = idx;
}

2450 2451
static void add_type_typeinfo(msft_typelib_t *typelib, type_t *type)
{
2452 2453
    switch (type_get_type(type)) {
    case TYPE_INTERFACE:
2454 2455
        add_interface_typeinfo(typelib, type);
        break;
2456
    case TYPE_STRUCT:
2457
    case TYPE_ENCAPSULATED_UNION:
2458 2459
        add_structure_typeinfo(typelib, type);
        break;
2460
    case TYPE_ENUM:
2461 2462
        add_enum_typeinfo(typelib, type);
        break;
2463 2464 2465
    case TYPE_UNION:
        add_union_typeinfo(typelib, type);
        break;
2466
    case TYPE_COCLASS:
2467 2468
        add_coclass_typeinfo(typelib, type);
        break;
2469 2470
    case TYPE_BASIC:
    case TYPE_POINTER:
2471
    case TYPE_ARRAY:
2472 2473
        break;
    default:
2474 2475
        error("add_entry: unhandled type 0x%x for %s\n",
              type_get_type(type), type->name);
2476 2477 2478 2479
        break;
    }
}

2480
static void add_entry(msft_typelib_t *typelib, const statement_t *stmt)
2481
{
2482 2483 2484
    switch(stmt->type) {
    case STMT_LIBRARY:
    case STMT_IMPORT:
2485
    case STMT_PRAGMA:
2486 2487 2488
    case STMT_CPPQUOTE:
    case STMT_DECLARATION:
        /* not included in typelib */
Huw Davies's avatar
Huw Davies committed
2489
        break;
2490 2491
    case STMT_IMPORTLIB:
        /* not processed here */
Huw Davies's avatar
Huw Davies committed
2492
        break;
2493 2494
    case STMT_TYPEDEF:
    {
2495 2496
        typeref_t *ref;
        if (stmt->u.type_list) LIST_FOR_EACH_ENTRY(ref, stmt->u.type_list, typeref_t, entry) {
2497 2498
            /* if the type is public then add the typedef, otherwise attempt
             * to add the aliased type */
2499 2500
            if (is_attr(ref->type->attrs, ATTR_PUBLIC))
                add_typedef_typeinfo(typelib, ref->type);
2501
            else
2502
                add_type_typeinfo(typelib, type_alias_get_aliasee_type(ref->type));
2503
        }
Huw Davies's avatar
Huw Davies committed
2504
        break;
2505 2506 2507
    }
    case STMT_MODULE:
        add_module_typeinfo(typelib, stmt->u.type);
Huw Davies's avatar
Huw Davies committed
2508
        break;
2509 2510 2511 2512
    case STMT_TYPE:
    case STMT_TYPEREF:
    {
        type_t *type = stmt->u.type;
2513
        add_type_typeinfo(typelib, type);
2514 2515
        break;
    }
2516
    }
2517 2518
}

2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530
static void set_name(msft_typelib_t *typelib)
{
    int offset;

    offset = ctl2_alloc_name(typelib, typelib->typelib->name);
    if (offset == -1) return;
    typelib->typelib_header.NameOffset = offset;
    return;
}

static void set_version(msft_typelib_t *typelib)
{
2531
    typelib->typelib_header.version = get_attrv( typelib->typelib->attrs, ATTR_VERSION );
2532 2533 2534 2535 2536 2537
}

static void set_guid(msft_typelib_t *typelib)
{
    MSFT_GuidEntry guidentry;
    int offset;
2538
    void *ptr;
2539 2540 2541 2542 2543 2544
    GUID guid = {0,0,0,{0,0,0,0,0,0}};

    guidentry.guid = guid;
    guidentry.hreftype = -2;
    guidentry.next_hash = -1;

2545 2546
    ptr = get_attrp( typelib->typelib->attrs, ATTR_UUID );
    if (ptr) guidentry.guid = *(GUID *)ptr;
2547 2548 2549 2550 2551 2552 2553 2554 2555

    offset = ctl2_alloc_guid(typelib, &guidentry);
    typelib->typelib_header.posguid = offset;

    return;
}

static void set_doc_string(msft_typelib_t *typelib)
{
2556
    char *str = get_attrp( typelib->typelib->attrs, ATTR_HELPSTRING );
2557

2558 2559 2560 2561
    if (str)
    {
        int offset = ctl2_alloc_string(typelib, str);
        if (offset != -1) typelib->typelib_header.helpstring = offset;
2562 2563 2564 2565 2566
    }
}

static void set_help_file_name(msft_typelib_t *typelib)
{
2567 2568 2569 2570 2571 2572 2573
    char *str = get_attrp( typelib->typelib->attrs, ATTR_HELPFILE );

    if (str)
    {
        int offset = ctl2_alloc_string(typelib, str);
        if (offset != -1)
        {
2574 2575 2576 2577 2578 2579 2580 2581
            typelib->typelib_header.helpfile = offset;
            typelib->typelib_header.varflags |= 0x10;
        }
    }
}

static void set_help_context(msft_typelib_t *typelib)
{
2582 2583
    const expr_t *expr = get_attrp( typelib->typelib->attrs, ATTR_HELPCONTEXT );
    if (expr) typelib->typelib_header.helpcontext = expr->cval;
2584 2585 2586 2587
}

static void set_help_string_dll(msft_typelib_t *typelib)
{
2588 2589 2590 2591 2592 2593 2594
    char *str = get_attrp( typelib->typelib->attrs, ATTR_HELPSTRINGDLL );

    if (str)
    {
        int offset = ctl2_alloc_string(typelib, str);
        if (offset != -1)
        {
2595 2596 2597 2598 2599 2600 2601 2602
            typelib->help_string_dll_offset = offset;
            typelib->typelib_header.varflags |= 0x100;
        }
    }
}

static void set_help_string_context(msft_typelib_t *typelib)
{
2603 2604
    const expr_t *expr = get_attrp( typelib->typelib->attrs, ATTR_HELPSTRINGCONTEXT );
    if (expr) typelib->typelib_header.helpstringcontext = expr->cval;
2605 2606 2607 2608
}

static void set_lcid(msft_typelib_t *typelib)
{
2609
    const expr_t *lcid_expr = get_attrp( typelib->typelib->attrs, ATTR_LIBLCID );
2610 2611 2612 2613 2614
    if(lcid_expr)
    {
        typelib->typelib_header.lcid  = lcid_expr->cval;
        typelib->typelib_header.lcid2 = lcid_expr->cval;
    }
2615 2616 2617 2618
}

static void set_lib_flags(msft_typelib_t *typelib)
{
2619
    const attr_t *attr;
2620

2621
    typelib->typelib_header.flags = 0;
2622 2623 2624
    if (!typelib->typelib->attrs) return;
    LIST_FOR_EACH_ENTRY( attr, typelib->typelib->attrs, const attr_t, entry )
    {
2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638
        switch(attr->type) {
        case ATTR_CONTROL:
            typelib->typelib_header.flags |= 0x02; /* LIBFLAG_FCONTROL */
            break;
        case ATTR_HIDDEN:
            typelib->typelib_header.flags |= 0x04; /* LIBFLAG_FHIDDEN */
            break;
        case ATTR_RESTRICTED:
            typelib->typelib_header.flags |= 0x01; /* LIBFLAG_FRESTRICTED */
            break;
        default:
            break;
        }
    }
2639 2640 2641
    return;
}

2642
static void ctl2_write_segment(msft_typelib_t *typelib, int segment)
2643
{
2644 2645
    if (typelib->typelib_segment_data[segment])
        put_data(typelib->typelib_segment_data[segment], typelib->typelib_segdir[segment].length);
2646 2647 2648 2649 2650 2651 2652 2653
}

static void ctl2_finalize_typeinfos(msft_typelib_t *typelib, int filesize)
{
    msft_typeinfo_t *typeinfo;

    for (typeinfo = typelib->typeinfos; typeinfo; typeinfo = typeinfo->next_typeinfo) {
	typeinfo->typeinfo->memoffset = filesize;
2654 2655 2656 2657 2658 2659
	if (typeinfo->func_data)
	    filesize += typeinfo->func_data[0] + ((typeinfo->typeinfo->cElement & 0xffff) * 12);
	if (typeinfo->var_data)
	    filesize += typeinfo->var_data[0] + (((typeinfo->typeinfo->cElement >> 16) & 0xffff) * 12);
        if (typeinfo->func_data || typeinfo->var_data)
            filesize += 4;
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674
    }
}

static int ctl2_finalize_segment(msft_typelib_t *typelib, int filepos, int segment)
{
    if (typelib->typelib_segdir[segment].length) {
	typelib->typelib_segdir[segment].offset = filepos;
    } else {
	typelib->typelib_segdir[segment].offset = -1;
    }

    return typelib->typelib_segdir[segment].length;
}


2675
static void ctl2_write_typeinfos(msft_typelib_t *typelib)
2676 2677
{
    msft_typeinfo_t *typeinfo;
2678
    int typedata_size;
2679 2680

    for (typeinfo = typelib->typeinfos; typeinfo; typeinfo = typeinfo->next_typeinfo) {
2681 2682 2683 2684 2685 2686
        if (!typeinfo->func_data && !typeinfo->var_data) continue;
        typedata_size = 0;
	if (typeinfo->func_data)
            typedata_size = typeinfo->func_data[0];
	if (typeinfo->var_data)
            typedata_size += typeinfo->var_data[0];
2687
	put_data(&typedata_size, sizeof(int));
2688
        if (typeinfo->func_data)
2689
            put_data(typeinfo->func_data + 1, typeinfo->func_data[0]);
2690
        if (typeinfo->var_data)
2691
            put_data(typeinfo->var_data + 1, typeinfo->var_data[0]);
2692
        if (typeinfo->func_indices)
2693
            put_data(typeinfo->func_indices, (typeinfo->typeinfo->cElement & 0xffff) * 4);
2694
        if (typeinfo->var_indices)
2695
            put_data(typeinfo->var_indices, (typeinfo->typeinfo->cElement >> 16) * 4);
2696
        if (typeinfo->func_names)
2697
            put_data(typeinfo->func_names,   (typeinfo->typeinfo->cElement & 0xffff) * 4);
2698
        if (typeinfo->var_names)
2699
            put_data(typeinfo->var_names,   (typeinfo->typeinfo->cElement >> 16) * 4);
2700
        if (typeinfo->func_offsets)
2701
            put_data(typeinfo->func_offsets, (typeinfo->typeinfo->cElement & 0xffff) * 4);
2702 2703 2704 2705 2706 2707 2708
        if (typeinfo->var_offsets) {
            int add = 0, i, offset;
            if(typeinfo->func_data)
                add = typeinfo->func_data[0];
            for(i = 0; i < (typeinfo->typeinfo->cElement >> 16); i++) {
                offset = typeinfo->var_offsets[i];
                offset += add;
2709
                put_data(&offset, 4);
2710
            }
2711
        }
2712 2713 2714
    }
}

2715
static void save_all_changes(msft_typelib_t *typelib)
2716 2717 2718 2719 2720 2721
{
    int filepos;

    chat("save_all_changes(%p)\n", typelib);

    filepos = sizeof(MSFT_Header) + sizeof(MSFT_SegDir);
2722
    if(typelib->typelib_header.varflags & 0x100) filepos += 4; /* helpstringdll */
2723 2724 2725 2726 2727
    filepos += typelib->typelib_header.nrtypeinfos * 4;

    filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_TYPEINFO);
    filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_GUIDHASH);
    filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_GUID);
2728
    filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_REFERENCES);
2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740
    filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_IMPORTINFO);
    filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_IMPORTFILES);
    filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_NAMEHASH);
    filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_NAME);
    filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_STRING);
    filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_TYPEDESC);
    filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_ARRAYDESC);
    filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_CUSTDATA);
    filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_CUSTDATAGUID);

    ctl2_finalize_typeinfos(typelib, filepos);

2741 2742 2743 2744
    byte_swapped = 0;
    init_output_buffer();

    put_data(&typelib->typelib_header, sizeof(typelib->typelib_header));
Huw Davies's avatar
Huw Davies committed
2745
    if(typelib->typelib_header.varflags & 0x100)
2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764
        put_data(&typelib->help_string_dll_offset, sizeof(typelib->help_string_dll_offset));

    put_data(typelib->typelib_typeinfo_offsets, typelib->typelib_header.nrtypeinfos * 4);
    put_data(&typelib->typelib_segdir, sizeof(typelib->typelib_segdir));
    ctl2_write_segment( typelib, MSFT_SEG_TYPEINFO );
    ctl2_write_segment( typelib, MSFT_SEG_GUIDHASH );
    ctl2_write_segment( typelib, MSFT_SEG_GUID );
    ctl2_write_segment( typelib, MSFT_SEG_REFERENCES );
    ctl2_write_segment( typelib, MSFT_SEG_IMPORTINFO );
    ctl2_write_segment( typelib, MSFT_SEG_IMPORTFILES );
    ctl2_write_segment( typelib, MSFT_SEG_NAMEHASH );
    ctl2_write_segment( typelib, MSFT_SEG_NAME );
    ctl2_write_segment( typelib, MSFT_SEG_STRING );
    ctl2_write_segment( typelib, MSFT_SEG_TYPEDESC );
    ctl2_write_segment( typelib, MSFT_SEG_ARRAYDESC );
    ctl2_write_segment( typelib, MSFT_SEG_CUSTDATA );
    ctl2_write_segment( typelib, MSFT_SEG_CUSTDATAGUID );

    ctl2_write_typeinfos(typelib);
2765 2766 2767

    if (strendswith( typelib_name, ".res" ))  /* create a binary resource file */
    {
2768 2769 2770 2771 2772 2773
        char typelib_id[13] = "#1";

        expr_t *expr = get_attrp( typelib->typelib->attrs, ATTR_ID );
        if (expr)
            sprintf( typelib_id, "#%d", expr->cval );
        add_output_to_resources( "TYPELIB", typelib_id );
2774
        output_typelib_regscript( typelib->typelib );
2775 2776
    }
    else flush_output_buffer( typelib_name );
2777 2778 2779 2780 2781
}

int create_msft_typelib(typelib_t *typelib)
{
    msft_typelib_t *msft;
2782
    int failed = 0;
2783
    const statement_t *stmt;
2784
    const attr_t *attr;
2785
    time_t cur_time;
2786
    char *time_override;
2787
    unsigned int version = 7 << 24 | 555; /* 7.00.0555 */
2788 2789 2790 2791
    GUID midl_time_guid    = {0xde77ba63,0x517c,0x11d1,{0xa2,0xda,0x00,0x00,0xf8,0x77,0x3c,0xe9}};
    GUID midl_version_guid = {0xde77ba64,0x517c,0x11d1,{0xa2,0xda,0x00,0x00,0xf8,0x77,0x3c,0xe9}};
    GUID midl_info_guid = {0xde77ba65,0x517c,0x11d1,{0xa2,0xda,0x00,0x00,0xf8,0x77,0x3c,0xe9}};
    char info_string[128];
2792

2793
    msft = xmalloc(sizeof(*msft));
2794 2795 2796 2797 2798 2799
    memset(msft, 0, sizeof(*msft));
    msft->typelib = typelib;

    ctl2_init_header(msft);
    ctl2_init_segdir(msft);

2800
    msft->typelib_header.varflags |= (pointer_size == 8) ? SYS_WIN64 : SYS_WIN32;
2801 2802 2803 2804 2805 2806 2807 2808

    /*
     * The following two calls return an offset or -1 if out of memory. We
     * specifically need an offset of 0, however, so...
     */
    if (ctl2_alloc_segment(msft, MSFT_SEG_GUIDHASH, 0x80, 0x80)) { failed = 1; }
    if (ctl2_alloc_segment(msft, MSFT_SEG_NAMEHASH, 0x200, 0x200)) { failed = 1; }

Andrew Talbot's avatar
Andrew Talbot committed
2809 2810 2811 2812 2813
    if(failed)
    {
        free(msft);
        return 0;
    }
2814 2815 2816 2817 2818 2819 2820 2821 2822

    msft->typelib_guidhash_segment = (int *)msft->typelib_segment_data[MSFT_SEG_GUIDHASH];
    msft->typelib_namehash_segment = (int *)msft->typelib_segment_data[MSFT_SEG_NAMEHASH];

    memset(msft->typelib_guidhash_segment, 0xff, 0x80);
    memset(msft->typelib_namehash_segment, 0xff, 0x200);

    set_lib_flags(msft);
    set_lcid(msft);
2823
    set_help_file_name(msft);
2824 2825 2826 2827
    set_doc_string(msft);
    set_guid(msft);
    set_version(msft);
    set_name(msft);
2828 2829 2830 2831
    set_help_context(msft);
    set_help_string_dll(msft);
    set_help_string_context(msft);
    
2832 2833 2834 2835 2836 2837 2838 2839 2840 2841
    if (typelib->attrs) LIST_FOR_EACH_ENTRY( attr, typelib->attrs, const attr_t, entry ) {
        switch(attr->type) {
        case ATTR_CUSTOM:
            set_custdata_attr(msft, attr->u.pval, &msft->typelib_header.CustomDataOffset);
            break;
        default:
            break;
        }
    }

2842 2843
    /* midl adds two sets of custom data to the library: the current unix time
       and midl's version number */
2844 2845
    time_override = getenv( "WIDL_TIME_OVERRIDE");
    cur_time = time_override ? atol( time_override) : time(NULL);
2846
    sprintf(info_string, "Created by WIDL version %s at %s", PACKAGE_VERSION, ctime(&cur_time));
2847 2848 2849
    set_custdata(msft, &midl_info_guid, VT_BSTR, info_string, &msft->typelib_header.CustomDataOffset);
    set_custdata(msft, &midl_time_guid, VT_UI4, &cur_time, &msft->typelib_header.CustomDataOffset);
    set_custdata(msft, &midl_version_guid, VT_UI4, &version, &msft->typelib_header.CustomDataOffset);
2850

2851 2852 2853
    if (typelib->stmts)
        LIST_FOR_EACH_ENTRY( stmt, typelib->stmts, const statement_t, entry )
            add_entry(msft, stmt);
2854

2855
    save_all_changes(msft);
Andrew Talbot's avatar
Andrew Talbot committed
2856
    free(msft);
2857 2858
    return 1;
}