comctl32: A couple fixes for tab icon offsets.
[wine] / tools / widl / write_msft.c
1 /*
2  *      Typelib v2 (MSFT) generation
3  *
4  *      Copyright 2004  Alastair Bridgewater
5  *                2004, 2005 Huw Davies
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  * --------------------------------------------------------------------------------------
22  *  Known problems:
23  *
24  *    Badly incomplete.
25  *
26  *    Only works on little-endian systems.
27  *
28  */
29
30 #include "config.h"
31 #include "wine/port.h"
32
33 #include <stdlib.h>
34 #include <string.h>
35 #include <stdarg.h>
36 #include <stdio.h>
37 #include <ctype.h>
38 #include <time.h>
39
40 #define NONAMELESSUNION
41 #define NONAMELESSSTRUCT
42
43 #include "winerror.h"
44 #include "windef.h"
45 #include "winbase.h"
46 #include "winnls.h"
47
48 #include "wine/unicode.h"
49
50 #include "widltypes.h"
51 #include "typelib.h"
52 #include "typelib_struct.h"
53 #include "utils.h"
54 #include "hash.h"
55
56 enum MSFT_segment_index {
57     MSFT_SEG_TYPEINFO = 0,  /* type information */
58     MSFT_SEG_IMPORTINFO,    /* import information */
59     MSFT_SEG_IMPORTFILES,   /* import filenames */
60     MSFT_SEG_REFERENCES,    /* references (?) */
61     MSFT_SEG_GUIDHASH,      /* hash table for guids? */
62     MSFT_SEG_GUID,          /* guid storage */
63     MSFT_SEG_NAMEHASH,      /* hash table for names */
64     MSFT_SEG_NAME,          /* name storage */
65     MSFT_SEG_STRING,        /* string storage */
66     MSFT_SEG_TYPEDESC,      /* type descriptions */
67     MSFT_SEG_ARRAYDESC,     /* array descriptions */
68     MSFT_SEG_CUSTDATA,      /* custom data */
69     MSFT_SEG_CUSTDATAGUID,  /* custom data guids */
70     MSFT_SEG_UNKNOWN,       /* ??? */
71     MSFT_SEG_UNKNOWN2,      /* ??? */
72     MSFT_SEG_MAX            /* total number of segments */
73 };
74
75 typedef struct tagMSFT_ImpFile {
76     int guid;
77     LCID lcid;
78     int version;
79     char filename[0]; /* preceded by two bytes of encoded (length << 2) + flags in the low two bits. */
80 } MSFT_ImpFile;
81
82 typedef struct _msft_typelib_t
83 {
84     typelib_t *typelib;
85     MSFT_Header typelib_header;
86     MSFT_pSeg typelib_segdir[MSFT_SEG_MAX];
87     char *typelib_segment_data[MSFT_SEG_MAX];
88     int typelib_segment_block_length[MSFT_SEG_MAX];
89
90     INT typelib_typeinfo_offsets[0x200]; /* Hope that's enough. */
91
92     INT *typelib_namehash_segment;
93     INT *typelib_guidhash_segment;
94
95     INT help_string_dll_offset;
96
97     struct _msft_typeinfo_t *typeinfos;
98     struct _msft_typeinfo_t *last_typeinfo;
99 } msft_typelib_t;
100
101 typedef struct _msft_typeinfo_t
102 {
103     msft_typelib_t *typelib;
104     MSFT_TypeInfoBase *typeinfo;
105
106     unsigned int var_data_allocated;
107     int *var_data;
108
109     unsigned int func_data_allocated;
110     int *func_data;
111
112     int vars_allocated;
113     int *var_indices;
114     int *var_names;
115     int *var_offsets;
116
117     int funcs_allocated;
118     int *func_indices;
119     int *func_names;
120     int *func_offsets;
121
122     int datawidth;
123
124     struct _msft_typeinfo_t *next_typeinfo;
125 } msft_typeinfo_t;
126
127
128
129 /*================== Internal functions ===================================*/
130
131 /****************************************************************************
132  *      ctl2_init_header
133  *
134  *  Initializes the type library header of a new typelib.
135  */
136 static void ctl2_init_header(
137         msft_typelib_t *typelib) /* [I] The typelib to initialize. */
138 {
139     typelib->typelib_header.magic1 = 0x5446534d;
140     typelib->typelib_header.magic2 = 0x00010002;
141     typelib->typelib_header.posguid = -1;
142     typelib->typelib_header.lcid = 0x0409; /* or do we use the current one? */
143     typelib->typelib_header.lcid2 = 0x0;
144     typelib->typelib_header.varflags = 0x40;
145     typelib->typelib_header.version = 0;
146     typelib->typelib_header.flags = 0;
147     typelib->typelib_header.nrtypeinfos = 0;
148     typelib->typelib_header.helpstring = -1;
149     typelib->typelib_header.helpstringcontext = 0;
150     typelib->typelib_header.helpcontext = 0;
151     typelib->typelib_header.nametablecount = 0;
152     typelib->typelib_header.nametablechars = 0;
153     typelib->typelib_header.NameOffset = -1;
154     typelib->typelib_header.helpfile = -1;
155     typelib->typelib_header.CustomDataOffset = -1;
156     typelib->typelib_header.res44 = 0x20;
157     typelib->typelib_header.res48 = 0x80;
158     typelib->typelib_header.dispatchpos = -1;
159     typelib->typelib_header.res50 = 0;
160 }
161
162 /****************************************************************************
163  *      ctl2_init_segdir
164  *
165  *  Initializes the segment directory of a new typelib.
166  */
167 static void ctl2_init_segdir(
168         msft_typelib_t *typelib) /* [I] The typelib to initialize. */
169 {
170     int i;
171     MSFT_pSeg *segdir;
172
173     segdir = &typelib->typelib_segdir[MSFT_SEG_TYPEINFO];
174
175     for (i = 0; i < 15; i++) {
176         segdir[i].offset = -1;
177         segdir[i].length = 0;
178         segdir[i].res08 = -1;
179         segdir[i].res0c = 0x0f;
180     }
181 }
182
183 /****************************************************************************
184  *      ctl2_hash_guid
185  *
186  *  Generates a hash key from a GUID.
187  *
188  * RETURNS
189  *
190  *  The hash key for the GUID.
191  */
192 static int ctl2_hash_guid(
193         REFGUID guid)                /* [I] The guid to hash. */
194 {
195     int hash;
196     int i;
197
198     hash = 0;
199     for (i = 0; i < 8; i ++) {
200         hash ^= ((const short *)guid)[i];
201     }
202
203     return hash & 0x1f;
204 }
205
206 /****************************************************************************
207  *      ctl2_find_guid
208  *
209  *  Locates a guid in a type library.
210  *
211  * RETURNS
212  *
213  *  The offset into the GUID segment of the guid, or -1 if not found.
214  */
215 static int ctl2_find_guid(
216         msft_typelib_t *typelib,   /* [I] The typelib to operate against. */
217         int hash_key,              /* [I] The hash key for the guid. */
218         REFGUID guid)              /* [I] The guid to find. */
219 {
220     int offset;
221     MSFT_GuidEntry *guidentry;
222
223     offset = typelib->typelib_guidhash_segment[hash_key];
224     while (offset != -1) {
225         guidentry = (MSFT_GuidEntry *)&typelib->typelib_segment_data[MSFT_SEG_GUID][offset];
226
227         if (!memcmp(guidentry, guid, sizeof(GUID))) return offset;
228
229         offset = guidentry->next_hash;
230     }
231
232     return offset;
233 }
234
235 /****************************************************************************
236  *      ctl2_find_name
237  *
238  *  Locates a name in a type library.
239  *
240  * RETURNS
241  *
242  *  The offset into the NAME segment of the name, or -1 if not found.
243  *
244  * NOTES
245  *
246  *  The name must be encoded as with ctl2_encode_name().
247  */
248 static int ctl2_find_name(
249         msft_typelib_t *typelib,   /* [I] The typelib to operate against. */
250         char *name)                /* [I] The encoded name to find. */
251 {
252     int offset;
253     int *namestruct;
254
255     offset = typelib->typelib_namehash_segment[name[2] & 0x7f];
256     while (offset != -1) {
257         namestruct = (int *)&typelib->typelib_segment_data[MSFT_SEG_NAME][offset];
258
259         if (!((namestruct[2] ^ *((int *)name)) & 0xffff00ff)) {
260             /* hash codes and lengths match, final test */
261             if (!strncasecmp(name+4, (void *)(namestruct+3), name[0])) break;
262         }
263
264         /* move to next item in hash bucket */
265         offset = namestruct[1];
266     }
267
268     return offset;
269 }
270
271 /****************************************************************************
272  *      ctl2_encode_name
273  *
274  *  Encodes a name string to a form suitable for storing into a type library
275  *  or comparing to a name stored in a type library.
276  *
277  * RETURNS
278  *
279  *  The length of the encoded name, including padding and length+hash fields.
280  *
281  * NOTES
282  *
283  *  Will throw an exception if name or result are NULL. Is not multithread
284  *  safe in the slightest.
285  */
286 static int ctl2_encode_name(
287         msft_typelib_t *typelib,   /* [I] The typelib to operate against (used for LCID only). */
288         const char *name,          /* [I] The name string to encode. */
289         char **result)             /* [O] A pointer to a pointer to receive the encoded name. */
290 {
291     int length;
292     static char converted_name[0x104];
293     int offset;
294     int value;
295
296     length = strlen(name);
297     memcpy(converted_name + 4, name, length);
298     converted_name[0] = length & 0xff;
299
300     converted_name[length + 4] = 0;
301
302     converted_name[1] = 0x00;
303
304     value = lhash_val_of_name_sys(typelib->typelib_header.varflags & 0x0f, typelib->typelib_header.lcid, converted_name + 4);
305
306     converted_name[2] = value;
307     converted_name[3] = value >> 8;
308
309     for (offset = (4 - length) & 3; offset; offset--) converted_name[length + offset + 3] = 0x57;
310
311     *result = converted_name;
312
313     return (length + 7) & ~3;
314 }
315
316 /****************************************************************************
317  *      ctl2_encode_string
318  *
319  *  Encodes a string to a form suitable for storing into a type library or
320  *  comparing to a string stored in a type library.
321  *
322  * RETURNS
323  *
324  *  The length of the encoded string, including padding and length fields.
325  *
326  * NOTES
327  *
328  *  Will throw an exception if string or result are NULL. Is not multithread
329  *  safe in the slightest.
330  */
331 static int ctl2_encode_string(
332         msft_typelib_t *typelib,   /* [I] The typelib to operate against (not used?). */
333         const char *string,        /* [I] The string to encode. */
334         char **result)             /* [O] A pointer to a pointer to receive the encoded string. */
335 {
336     int length;
337     static char converted_string[0x104];
338     int offset;
339
340     length = strlen(string);
341     memcpy(converted_string + 2, string, length);
342     converted_string[0] = length & 0xff;
343     converted_string[1] = (length >> 8) & 0xff;
344
345     if(length < 3) { /* strings of this length are padded with up to 8 bytes incl the 2 byte length */
346         for(offset = 0; offset < 4; offset++)
347             converted_string[length + offset + 2] = 0x57;
348         length += 4;
349     }
350     for (offset = (4 - (length + 2)) & 3; offset; offset--) converted_string[length + offset + 1] = 0x57;
351
352     *result = converted_string;
353
354     return (length + 5) & ~3;
355 }
356
357 /****************************************************************************
358  *      ctl2_alloc_segment
359  *
360  *  Allocates memory from a segment in a type library.
361  *
362  * RETURNS
363  *
364  *  Success: The offset within the segment of the new data area.
365  *  Failure: -1 (this is invariably an out of memory condition).
366  *
367  * BUGS
368  *
369  *  Does not (yet) handle the case where the allocated segment memory needs to grow.
370  */
371 static int ctl2_alloc_segment(
372         msft_typelib_t *typelib,         /* [I] The type library in which to allocate. */
373         enum MSFT_segment_index segment, /* [I] The segment in which to allocate. */
374         int size,                        /* [I] The amount to allocate. */
375         int block_size)                  /* [I] Initial allocation block size, or 0 for default. */
376 {
377     int offset;
378
379     if(!typelib->typelib_segment_data[segment]) {
380         if (!block_size) block_size = 0x2000;
381
382         typelib->typelib_segment_block_length[segment] = block_size;
383         typelib->typelib_segment_data[segment] = xmalloc(block_size);
384         if (!typelib->typelib_segment_data[segment]) return -1;
385         memset(typelib->typelib_segment_data[segment], 0x57, block_size);
386     }
387
388     while ((typelib->typelib_segdir[segment].length + size) > typelib->typelib_segment_block_length[segment]) {
389         char *block;
390
391         block_size = typelib->typelib_segment_block_length[segment];
392         block = realloc(typelib->typelib_segment_data[segment], block_size << 1);
393         if (!block) return -1;
394
395         if (segment == MSFT_SEG_TYPEINFO) {
396             /* TypeInfos have a direct pointer to their memory space, so we have to fix them up. */
397             msft_typeinfo_t *typeinfo;
398
399             for (typeinfo = typelib->typeinfos; typeinfo; typeinfo = typeinfo->next_typeinfo) {
400                 typeinfo->typeinfo = (void *)&block[((char *)typeinfo->typeinfo) - typelib->typelib_segment_data[segment]];
401             }
402         }
403
404         memset(block + block_size, 0x57, block_size);
405         typelib->typelib_segment_block_length[segment] = block_size << 1;
406         typelib->typelib_segment_data[segment] = block;
407     }
408
409     offset = typelib->typelib_segdir[segment].length;
410     typelib->typelib_segdir[segment].length += size;
411
412     return offset;
413 }
414
415 /****************************************************************************
416  *      ctl2_alloc_typeinfo
417  *
418  *  Allocates and initializes a typeinfo structure in a type library.
419  *
420  * RETURNS
421  *
422  *  Success: The offset of the new typeinfo.
423  *  Failure: -1 (this is invariably an out of memory condition).
424  */
425 static int ctl2_alloc_typeinfo(
426         msft_typelib_t *typelib,   /* [I] The type library to allocate in. */
427         int nameoffset)            /* [I] The offset of the name for this typeinfo. */
428 {
429     int offset;
430     MSFT_TypeInfoBase *typeinfo;
431
432     offset = ctl2_alloc_segment(typelib, MSFT_SEG_TYPEINFO, sizeof(MSFT_TypeInfoBase), 0);
433     if (offset == -1) return -1;
434
435     typelib->typelib_typeinfo_offsets[typelib->typelib_header.nrtypeinfos++] = offset;
436
437     typeinfo = (void *)(typelib->typelib_segment_data[MSFT_SEG_TYPEINFO] + offset);
438
439     typeinfo->typekind = (typelib->typelib_header.nrtypeinfos - 1) << 16;
440     typeinfo->memoffset = -1; /* should be EOF if no elements */
441     typeinfo->res2 = 0;
442     typeinfo->res3 = -1;
443     typeinfo->res4 = 3;
444     typeinfo->res5 = 0;
445     typeinfo->cElement = 0;
446     typeinfo->res7 = 0;
447     typeinfo->res8 = 0;
448     typeinfo->res9 = 0;
449     typeinfo->resA = 0;
450     typeinfo->posguid = -1;
451     typeinfo->flags = 0;
452     typeinfo->NameOffset = nameoffset;
453     typeinfo->version = 0;
454     typeinfo->docstringoffs = -1;
455     typeinfo->helpstringcontext = 0;
456     typeinfo->helpcontext = 0;
457     typeinfo->oCustData = -1;
458     typeinfo->cbSizeVft = 0;
459     typeinfo->cImplTypes = 0;
460     typeinfo->size = 0;
461     typeinfo->datatype1 = -1;
462     typeinfo->datatype2 = 0;
463     typeinfo->res18 = 0;
464     typeinfo->res19 = -1;
465
466     return offset;
467 }
468
469 /****************************************************************************
470  *      ctl2_alloc_guid
471  *
472  *  Allocates and initializes a GUID structure in a type library. Also updates
473  *  the GUID hash table as needed.
474  *
475  * RETURNS
476  *
477  *  Success: The offset of the new GUID.
478  *  Failure: -1 (this is invariably an out of memory condition).
479  */
480 static int ctl2_alloc_guid(
481         msft_typelib_t *typelib,   /* [I] The type library to allocate in. */
482         MSFT_GuidEntry *guid)      /* [I] The GUID to store. */
483 {
484     int offset;
485     MSFT_GuidEntry *guid_space;
486     int hash_key;
487
488     hash_key = ctl2_hash_guid(&guid->guid);
489
490     offset = ctl2_find_guid(typelib, hash_key, &guid->guid);
491     if (offset != -1) return offset;
492
493     offset = ctl2_alloc_segment(typelib, MSFT_SEG_GUID, sizeof(MSFT_GuidEntry), 0);
494     if (offset == -1) return -1;
495
496     guid_space = (void *)(typelib->typelib_segment_data[MSFT_SEG_GUID] + offset);
497     *guid_space = *guid;
498
499     guid_space->next_hash = typelib->typelib_guidhash_segment[hash_key];
500     typelib->typelib_guidhash_segment[hash_key] = offset;
501
502     return offset;
503 }
504
505 /****************************************************************************
506  *      ctl2_alloc_name
507  *
508  *  Allocates and initializes a name within a type library. Also updates the
509  *  name hash table as needed.
510  *
511  * RETURNS
512  *
513  *  Success: The offset within the segment of the new name.
514  *  Failure: -1 (this is invariably an out of memory condition).
515  */
516 static int ctl2_alloc_name(
517         msft_typelib_t *typelib,  /* [I] The type library to allocate in. */
518         const char *name)         /* [I] The name to store. */
519 {
520     int length;
521     int offset;
522     MSFT_NameIntro *name_space;
523     char *encoded_name;
524
525     length = ctl2_encode_name(typelib, name, &encoded_name);
526
527     offset = ctl2_find_name(typelib, encoded_name);
528     if (offset != -1) return offset;
529
530     offset = ctl2_alloc_segment(typelib, MSFT_SEG_NAME, length + 8, 0);
531     if (offset == -1) return -1;
532
533     name_space = (void *)(typelib->typelib_segment_data[MSFT_SEG_NAME] + offset);
534     name_space->hreftype = -1;
535     name_space->next_hash = -1;
536     memcpy(&name_space->namelen, encoded_name, length);
537
538     if (typelib->typelib_namehash_segment[encoded_name[2] & 0x7f] != -1)
539         name_space->next_hash = typelib->typelib_namehash_segment[encoded_name[2] & 0x7f];
540
541     typelib->typelib_namehash_segment[encoded_name[2] & 0x7f] = offset;
542
543     typelib->typelib_header.nametablecount += 1;
544     typelib->typelib_header.nametablechars += *encoded_name;
545
546     return offset;
547 }
548
549 /****************************************************************************
550  *      ctl2_alloc_string
551  *
552  *  Allocates and initializes a string in a type library.
553  *
554  * RETURNS
555  *
556  *  Success: The offset within the segment of the new string.
557  *  Failure: -1 (this is invariably an out of memory condition).
558  */
559 static int ctl2_alloc_string(
560         msft_typelib_t *typelib,  /* [I] The type library to allocate in. */
561         const char *string)       /* [I] The string to store. */
562 {
563     int length;
564     int offset;
565     char *string_space;
566     char *encoded_string;
567
568     length = ctl2_encode_string(typelib, string, &encoded_string);
569
570     for (offset = 0; offset < typelib->typelib_segdir[MSFT_SEG_STRING].length;
571          offset += ((((typelib->typelib_segment_data[MSFT_SEG_STRING][offset + 1] << 8) & 0xff)
572              | (typelib->typelib_segment_data[MSFT_SEG_STRING][offset + 0] & 0xff)) + 5) & ~3) {
573         if (!memcmp(encoded_string, typelib->typelib_segment_data[MSFT_SEG_STRING] + offset, length)) return offset;
574     }
575
576     offset = ctl2_alloc_segment(typelib, MSFT_SEG_STRING, length, 0);
577     if (offset == -1) return -1;
578
579     string_space = typelib->typelib_segment_data[MSFT_SEG_STRING] + offset;
580     memcpy(string_space, encoded_string, length);
581
582     return offset;
583 }
584
585 /****************************************************************************
586  *      alloc_importinfo
587  *
588  *  Allocates and initializes an import information structure in a type library.
589  *
590  * RETURNS
591  *
592  *  Success: The offset of the new importinfo.
593  *  Failure: -1 (this is invariably an out of memory condition).
594  */
595 static int alloc_importinfo(
596         msft_typelib_t *typelib,   /* [I] The type library to allocate in. */
597         MSFT_ImpInfo *impinfo)     /* [I] The import information to store. */
598 {
599     int offset;
600     MSFT_ImpInfo *impinfo_space;
601
602     for (offset = 0;
603          offset < typelib->typelib_segdir[MSFT_SEG_IMPORTINFO].length;
604          offset += sizeof(MSFT_ImpInfo)) {
605         if (!memcmp(&(typelib->typelib_segment_data[MSFT_SEG_IMPORTINFO][offset]),
606                     impinfo, sizeof(MSFT_ImpInfo))) {
607             return offset;
608         }
609     }
610
611     offset = ctl2_alloc_segment(typelib, MSFT_SEG_IMPORTINFO, sizeof(MSFT_ImpInfo), 0);
612     if (offset == -1) return -1;
613
614     impinfo_space = (void *)(typelib->typelib_segment_data[MSFT_SEG_IMPORTINFO] + offset);
615     *impinfo_space = *impinfo;
616
617     return offset;
618 }
619
620 /****************************************************************************
621  *      alloc_importfile
622  *
623  *  Allocates and initializes an import file definition in a type library.
624  *
625  * RETURNS
626  *
627  *  Success: The offset of the new importinfo.
628  *  Failure: -1 (this is invariably an out of memory condition).
629  */
630 static int alloc_importfile(
631         msft_typelib_t *typelib,   /* [I] The type library to allocate in. */
632         int guidoffset,            /* [I] The offset to the GUID for the imported library. */
633         int major_version,         /* [I] The major version number of the imported library. */
634         int minor_version,         /* [I] The minor version number of the imported library. */
635         const char *filename)      /* [I] The filename of the imported library. */
636 {
637     int length;
638     int offset;
639     MSFT_ImpFile *importfile;
640     char *encoded_string;
641
642     length = ctl2_encode_string(typelib, filename, &encoded_string);
643
644     encoded_string[0] <<= 2;
645     encoded_string[0] |= 1;
646
647     for (offset = 0; offset < typelib->typelib_segdir[MSFT_SEG_IMPORTFILES].length;
648          offset += ((((typelib->typelib_segment_data[MSFT_SEG_IMPORTFILES][offset + 0xd] << 8) & 0xff)
649              | (typelib->typelib_segment_data[MSFT_SEG_IMPORTFILES][offset + 0xc] & 0xff)) >> 2) + 0xc) {
650         if (!memcmp(encoded_string, typelib->typelib_segment_data[MSFT_SEG_IMPORTFILES] + offset + 0xc, length)) return offset;
651     }
652
653     offset = ctl2_alloc_segment(typelib, MSFT_SEG_IMPORTFILES, length + 0xc, 0);
654     if (offset == -1) return -1;
655
656     importfile = (MSFT_ImpFile *)&typelib->typelib_segment_data[MSFT_SEG_IMPORTFILES][offset];
657     importfile->guid = guidoffset;
658     importfile->lcid = typelib->typelib_header.lcid2;
659     importfile->version = major_version | (minor_version << 16);
660     memcpy(&importfile->filename, encoded_string, length);
661
662     return offset;
663 }
664
665 static void add_structure_typeinfo(msft_typelib_t *typelib, type_t *structure);
666 static void add_interface_typeinfo(msft_typelib_t *typelib, type_t *interface);
667
668 /****************************************************************************
669  *      encode_type
670  *
671  *  Encodes a type, storing information in the TYPEDESC and ARRAYDESC
672  *  segments as needed.
673  *
674  * RETURNS
675  *
676  *  Success: 0.
677  *  Failure: -1.
678  */
679 static int encode_type(
680         msft_typelib_t *typelib,   /* [I] The type library in which to encode the TYPEDESC. */
681         int vt,                    /* [I] vt to encode */
682         type_t *type,              /* [I] type */
683         int *encoded_type,         /* [O] The encoded type description. */
684         int *width,                /* [O] The width of the type, or NULL. */
685         int *alignment,            /* [O] The alignment of the type, or NULL. */
686         int *decoded_size)         /* [O] The total size of the unencoded TYPEDESCs, including nested descs. */
687 {
688     int default_type;
689     int scratch;
690     int typeoffset;
691     int *typedata;
692     int target_type;
693     int child_size = 0;
694
695     chat("encode_type vt %d type %p\n", vt, type);
696
697     default_type = 0x80000000 | (vt << 16) | vt;
698     if (!width) width = &scratch;
699     if (!alignment) alignment = &scratch;
700     if (!decoded_size) decoded_size = &scratch;
701
702
703     switch (vt) {
704     case VT_I1:
705     case VT_UI1:
706         *encoded_type = default_type;
707         *width = 1;
708         *alignment = 1;
709         break;
710
711     case VT_INT:
712         *encoded_type = 0x80000000 | (VT_I4 << 16) | VT_INT;
713         if ((typelib->typelib_header.varflags & 0x0f) == SYS_WIN16) {
714             *width = 2;
715             *alignment = 2;
716         } else {
717             *width = 4;
718             *alignment = 4;
719         }
720         break;
721
722     case VT_UINT:
723         *encoded_type = 0x80000000 | (VT_UI4 << 16) | VT_UINT;
724         if ((typelib->typelib_header.varflags & 0x0f) == SYS_WIN16) {
725             *width = 2;
726             *alignment = 2;
727         } else {
728             *width = 4;
729             *alignment = 4;
730         }
731         break;
732
733     case VT_UI2:
734     case VT_I2:
735     case VT_BOOL:
736         *encoded_type = default_type;
737         *width = 2;
738         *alignment = 2;
739         break;
740
741     case VT_I4:
742     case VT_UI4:
743     case VT_R4:
744     case VT_ERROR:
745     case VT_BSTR:
746     case VT_HRESULT:
747         *encoded_type = default_type;
748         *width = 4;
749         *alignment = 4;
750         break;
751
752     case VT_R8:
753         *encoded_type = default_type;
754         *width = 8;
755         *alignment = 8;
756         break;
757
758     case VT_CY:
759         *encoded_type = default_type;
760         *width = 8;
761         *alignment = 8;
762         break;
763
764     case VT_VOID:
765         *encoded_type = 0x80000000 | (VT_EMPTY << 16) | vt;
766         *width = 0;
767         *alignment = 1;
768         break;
769
770     case VT_UNKNOWN:
771     case VT_DISPATCH:
772         *encoded_type = default_type;
773         *width = 4;
774         *alignment = 4;
775         break;
776
777     case VT_VARIANT:
778         *encoded_type = default_type;
779         break;
780
781     case VT_PTR:
782       {
783         int next_vt;
784         while((next_vt = get_type_vt(type->ref)) == 0) {
785             if(type->ref == NULL) {
786                 next_vt = VT_VOID;
787                 break;
788             }
789             type = type->ref;
790         }
791
792         encode_type(typelib, next_vt, type->ref, &target_type, NULL, NULL, &child_size);
793         if(type->ref->type == RPC_FC_IP) {
794             chat("encode_type: skipping ptr\n");
795             *encoded_type = target_type;
796             *width = 4;
797             *alignment = 4;
798             *decoded_size = child_size;
799             break;
800         }
801
802         for (typeoffset = 0; typeoffset < typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length; typeoffset += 8) {
803             typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];
804             if (((typedata[0] & 0xffff) == VT_PTR) && (typedata[1] == target_type)) break;
805         }
806
807         if (typeoffset == typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length) {
808             int mix_field;
809             
810             if (target_type & 0x80000000) {
811                 mix_field = ((target_type >> 16) & 0x3fff) | VT_BYREF;
812             } else {
813                 typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][target_type];
814                 mix_field = ((typedata[0] >> 16) == 0x7fff)? 0x7fff: 0x7ffe;
815             }
816
817             typeoffset = ctl2_alloc_segment(typelib, MSFT_SEG_TYPEDESC, 8, 0);
818             typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];
819
820             typedata[0] = (mix_field << 16) | VT_PTR;
821             typedata[1] = target_type;
822         }
823
824         *encoded_type = typeoffset;
825
826         *width = 4;
827         *alignment = 4;
828         *decoded_size = 8 /*sizeof(TYPEDESC)*/ + child_size;
829         break;
830     }
831 #if 0
832
833
834     case VT_SAFEARRAY:
835         /* FIXME: Make with the error checking. */
836         FIXME("SAFEARRAY vartype, may not work correctly.\n");
837
838         ctl2_encode_typedesc(typelib, tdesc->u.lptdesc, &target_type, NULL, NULL, &child_size);
839
840         for (typeoffset = 0; typeoffset < typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length; typeoffset += 8) {
841             typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];
842             if (((typedata[0] & 0xffff) == VT_SAFEARRAY) && (typedata[1] == target_type)) break;
843         }
844
845         if (typeoffset == typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length) {
846             int mix_field;
847             
848             if (target_type & 0x80000000) {
849                 mix_field = ((target_type >> 16) & VT_TYPEMASK) | VT_ARRAY;
850             } else {
851                 typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][target_type];
852                 mix_field = ((typedata[0] >> 16) == 0x7fff)? 0x7fff: 0x7ffe;
853             }
854
855             typeoffset = ctl2_alloc_segment(typelib, MSFT_SEG_TYPEDESC, 8, 0);
856             typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];
857
858             typedata[0] = (mix_field << 16) | VT_SAFEARRAY;
859             typedata[1] = target_type;
860         }
861
862         *encoded_tdesc = typeoffset;
863
864         *width = 4;
865         *alignment = 4;
866         *decoded_size = sizeof(TYPEDESC) + child_size;
867         break;
868
869
870 #endif
871
872     case VT_USERDEFINED:
873       {
874         int typeinfo_offset;
875         chat("encode_type: VT_USERDEFINED - type %p name = %s type->type %d idx %d\n", type,
876              type->name, type->type, type->typelib_idx);
877
878         if(type->typelib_idx == -1) {
879             chat("encode_type: trying to ref not added type\n");
880             switch(type->type) {
881             case RPC_FC_STRUCT:
882             case RPC_FC_PSTRUCT:
883             case RPC_FC_CSTRUCT:
884             case RPC_FC_CPSTRUCT:
885             case RPC_FC_CVSTRUCT:
886             case RPC_FC_BOGUS_STRUCT:
887                 add_structure_typeinfo(typelib, type);
888                 break;
889             case RPC_FC_IP:
890                 add_interface_typeinfo(typelib, type);
891                 break;
892             case 0:
893                 error("encode_type: VT_USERDEFINED - can't yet add typedef's on the fly\n");
894             default:
895                 error("encode_type: VT_USERDEFINED - unhandled type %d\n", type->type);
896             }
897         }
898
899         typeinfo_offset = typelib->typelib_typeinfo_offsets[type->typelib_idx];
900         for (typeoffset = 0; typeoffset < typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length; typeoffset += 8) {
901             typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];
902             if ((typedata[0] == ((0x7fff << 16) | VT_USERDEFINED)) && (typedata[1] == typeinfo_offset)) break;
903         }
904
905         if (typeoffset == typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length) {
906             typeoffset = ctl2_alloc_segment(typelib, MSFT_SEG_TYPEDESC, 8, 0);
907             typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];
908
909             typedata[0] = (0x7fff << 16) | VT_USERDEFINED;
910             typedata[1] = typeinfo_offset;
911         }
912
913         *encoded_type = typeoffset;
914         *width = 0;
915         *alignment = 1;
916
917         if(type->type == RPC_FC_IP) {
918             for (typeoffset = 0; typeoffset < typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length; typeoffset += 8) {
919                 typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];
920                 if ((typedata[0] == ((0x7fff << 16) | VT_PTR)) && (typedata[1] == *encoded_type)) break;
921             }
922             if (typeoffset == typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length) {
923                 typeoffset = ctl2_alloc_segment(typelib, MSFT_SEG_TYPEDESC, 8, 0);
924                 typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];
925
926                 typedata[0] = (0x7fff << 16) | VT_PTR;
927                 typedata[1] = *encoded_type;
928             }
929             *encoded_type = typeoffset;
930             *width = 4;
931             *alignment = 4;
932             *decoded_size += 8;
933         }
934         break;
935       }
936
937     default:
938         error("encode_type: unrecognized type %d.\n", vt);
939         *encoded_type = default_type;
940         *width = 0;
941         *alignment = 1;
942         break;
943     }
944
945     return 0;
946 }
947
948 static void dump_type(type_t *t)
949 {
950     chat("dump_type: %p name %s type %d ref %p attrs %p\n", t, t->name, t->type, t->ref, t->attrs);
951     if(t->ref) dump_type(t->ref);
952 }
953
954 static int encode_var(
955         msft_typelib_t *typelib,   /* [I] The type library in which to encode the TYPEDESC. */
956         var_t *var,                /* [I] The type description to encode. */
957         int *encoded_type,         /* [O] The encoded type description. */
958         int *width,                /* [O] The width of the type, or NULL. */
959         int *alignment,            /* [O] The alignment of the type, or NULL. */
960         int *decoded_size)         /* [O] The total size of the unencoded TYPEDESCs, including nested descs. */
961 {
962     int typeoffset;
963     int *typedata;
964     int target_type;
965     int child_size;
966     int vt;
967     int scratch;
968     type_t *type;
969
970     if (!width) width = &scratch;
971     if (!alignment) alignment = &scratch;
972     if (!decoded_size) decoded_size = &scratch;
973     *decoded_size = 0;
974
975     chat("encode_var: var %p var->tname %s var->type %p var->ptr_level %d var->type->ref %p\n", var, var->tname, var->type, var->ptr_level, var->type->ref);
976     if(var->ptr_level) {
977         int skip_ptr;
978         var->ptr_level--;
979         skip_ptr = encode_var(typelib, var, &target_type, NULL, NULL, &child_size);
980         var->ptr_level++;
981
982         if(skip_ptr == 2) {
983             chat("encode_var: skipping ptr\n");
984             *encoded_type = target_type;
985             *decoded_size = child_size;
986             *width = 4;
987             *alignment = 4;
988             return 0;
989         }
990
991         for (typeoffset = 0; typeoffset < typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length; typeoffset += 8) {
992             typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];
993             if (((typedata[0] & 0xffff) == VT_PTR) && (typedata[1] == target_type)) break;
994         }
995
996         if (typeoffset == typelib->typelib_segdir[MSFT_SEG_TYPEDESC].length) {
997             int mix_field;
998             
999             if (target_type & 0x80000000) {
1000                 mix_field = ((target_type >> 16) & 0x3fff) | VT_BYREF;
1001             } else {
1002                 typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][target_type];
1003                 mix_field = ((typedata[0] >> 16) == 0x7fff)? 0x7fff: 0x7ffe;
1004             }
1005
1006             typeoffset = ctl2_alloc_segment(typelib, MSFT_SEG_TYPEDESC, 8, 0);
1007             typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];
1008
1009             typedata[0] = (mix_field << 16) | VT_PTR;
1010             typedata[1] = target_type;
1011         }
1012
1013         *encoded_type = typeoffset;
1014
1015         *width = 4;
1016         *alignment = 4;
1017         *decoded_size = 8 /*sizeof(TYPEDESC)*/ + child_size;
1018         return 0;
1019     }
1020
1021     if(var->array) {
1022         expr_t *dim = var->array;
1023         expr_t *array_save;
1024         int num_dims = 1, elements = 1, arrayoffset;
1025         int *arraydata;
1026
1027         while(NEXT_LINK(dim)) {
1028             dim = NEXT_LINK(dim);
1029             num_dims++;
1030         }
1031         chat("array with %d dimensions\n", num_dims);
1032         array_save = var->array;
1033         var->array = NULL;
1034         encode_var(typelib, var, &target_type, width, alignment, NULL);
1035         var->array = array_save;
1036         arrayoffset = ctl2_alloc_segment(typelib, MSFT_SEG_ARRAYDESC, (2 + 2 * num_dims) * sizeof(long), 0);
1037         arraydata = (void *)&typelib->typelib_segment_data[MSFT_SEG_ARRAYDESC][arrayoffset];
1038
1039         arraydata[0] = target_type;
1040         arraydata[1] = num_dims;
1041         arraydata[1] |= ((num_dims * 2 * sizeof(long)) << 16);
1042
1043         arraydata += 2;
1044         while(dim) {
1045             arraydata[0] = dim->cval;
1046             arraydata[1] = 0;
1047             arraydata += 2;
1048             elements *= dim->cval;
1049             dim = PREV_LINK(dim);
1050         }
1051
1052         typeoffset = ctl2_alloc_segment(typelib, MSFT_SEG_TYPEDESC, 8, 0);
1053         typedata = (void *)&typelib->typelib_segment_data[MSFT_SEG_TYPEDESC][typeoffset];
1054
1055         typedata[0] = (0x7ffe << 16) | VT_CARRAY;
1056         typedata[1] = arrayoffset;
1057
1058         *encoded_type = typeoffset;
1059         *width = *width * elements;
1060         *decoded_size = 20 /*sizeof(ARRAYDESC)*/ + (num_dims - 1) * 8 /*sizeof(SAFEARRAYBOUND)*/;
1061         return 0;
1062     }
1063     dump_type(var->type);
1064
1065     vt = get_var_vt(var);
1066     type = var->type;
1067     while(!vt) {
1068         if(type->ref == NULL) {
1069             vt = VT_VOID;
1070             break;
1071         }
1072         type = type->ref;
1073         vt = get_type_vt(type);
1074     }
1075     encode_type(typelib, vt, type, encoded_type, width, alignment, decoded_size);
1076     if(type->type == RPC_FC_IP) return 2;
1077     return 0;
1078 }
1079
1080
1081 static void write_value(msft_typelib_t* typelib, int *out, int vt, void *value)
1082 {
1083     switch(vt) {
1084     case VT_I2:
1085     case VT_I4:
1086     case VT_R4:
1087     case VT_BOOL:
1088     case VT_I1:
1089     case VT_UI1:
1090     case VT_UI2:
1091     case VT_UI4:
1092     case VT_INT:
1093     case VT_UINT:
1094     case VT_HRESULT:
1095       {
1096         unsigned long *lv = value;
1097         if((*lv & 0x3ffffff) == *lv) {
1098             *out = 0x80000000;
1099             *out |= vt << 26;
1100             *out |= *lv;
1101         } else {
1102             int offset = ctl2_alloc_segment(typelib, MSFT_SEG_CUSTDATA, 8, 0);
1103             *((unsigned short *)&typelib->typelib_segment_data[MSFT_SEG_CUSTDATA][offset]) = vt;
1104             memcpy(&typelib->typelib_segment_data[MSFT_SEG_CUSTDATA][offset+2], value, 4);
1105             *((unsigned short *)&typelib->typelib_segment_data[MSFT_SEG_CUSTDATA][offset+6]) = 0x5757;
1106             *out = offset;
1107         }
1108         return;
1109       }
1110     case VT_BSTR:
1111       {
1112         char *s = (char *) value;
1113         int len = strlen(s), seg_len = (len + 6 + 3) & ~0x3;
1114         int offset = ctl2_alloc_segment(typelib, MSFT_SEG_CUSTDATA, seg_len, 0);
1115         *((unsigned short *)&typelib->typelib_segment_data[MSFT_SEG_CUSTDATA][offset]) = vt;
1116         *((unsigned int *)&typelib->typelib_segment_data[MSFT_SEG_CUSTDATA][offset+2]) = len;        
1117         memcpy(&typelib->typelib_segment_data[MSFT_SEG_CUSTDATA][offset+6], value, len);
1118         len += 6;
1119         while(len < seg_len) {
1120             *((char *)&typelib->typelib_segment_data[MSFT_SEG_CUSTDATA][offset+len]) = 0x57;
1121             len++;
1122         }
1123         *out = offset;
1124         return;
1125       }
1126
1127     default:
1128         warning("can't write value of type %d yet\n", vt);
1129     }
1130     return;
1131 }
1132
1133 static HRESULT set_custdata(msft_typelib_t *typelib, REFGUID guid,
1134                             int vt, void *value, int *offset)
1135 {
1136     MSFT_GuidEntry guidentry;
1137     int guidoffset;
1138     int custoffset;
1139     int *custdata;
1140     int data_out;
1141
1142     guidentry.guid = *guid;
1143
1144     guidentry.hreftype = -1;
1145     guidentry.next_hash = -1;
1146
1147     guidoffset = ctl2_alloc_guid(typelib, &guidentry);
1148     if (guidoffset == -1) return E_OUTOFMEMORY;
1149     write_value(typelib, &data_out, vt, value);
1150
1151     custoffset = ctl2_alloc_segment(typelib, MSFT_SEG_CUSTDATAGUID, 12, 0);
1152     if (custoffset == -1) return E_OUTOFMEMORY;
1153
1154     custdata = (int *)&typelib->typelib_segment_data[MSFT_SEG_CUSTDATAGUID][custoffset];
1155     custdata[0] = guidoffset;
1156     custdata[1] = data_out;
1157     custdata[2] = *offset;
1158     *offset = custoffset;
1159
1160     return S_OK;
1161 }
1162
1163 static HRESULT add_func_desc(msft_typeinfo_t* typeinfo, func_t *func, int index)
1164 {
1165     int offset, name_offset;
1166     int *typedata, typedata_size;
1167     int i, id, next_idx;
1168     int decoded_size, extra_attr = 0;
1169     int num_params = 0, num_defaults = 0;
1170     var_t *arg, *last_arg = NULL;
1171     char *namedata;
1172     const attr_t *attr;
1173     unsigned int funcflags = 0, callconv = 4 /* CC_STDCALL */;
1174     unsigned int funckind, invokekind = 1 /* INVOKE_FUNC */;
1175     int help_context = 0, help_string_context = 0, help_string_offset = -1;
1176     int entry = -1, entry_is_ord = 0;
1177
1178     chat("add_func_desc(%p,%d)\n", typeinfo, index);
1179
1180     id = ((0x6000 | (typeinfo->typeinfo->datatype2 & 0xffff)) << 16) | index;
1181
1182     switch(typeinfo->typeinfo->typekind & 15) {
1183     case TKIND_DISPATCH:
1184         funckind = 0x4; /* FUNC_DISPATCH */
1185         break;
1186     case TKIND_MODULE:
1187         funckind = 0x3; /* FUNC_STATIC */
1188         break;
1189     default:
1190         funckind = 0x1; /* FUNC_PUREVIRTUAL */
1191         break;
1192     }
1193
1194     for(attr = func->def->attrs; attr; attr = NEXT_LINK(attr)) {
1195         if(attr->type == ATTR_LOCAL) {
1196             chat("add_func_desc: skipping local function\n");
1197             return S_FALSE;
1198         }
1199     }
1200
1201     for(arg = func->args; arg; arg = NEXT_LINK(arg)) {
1202         last_arg = arg;
1203         num_params++;
1204         for(attr = arg->attrs; attr; attr = NEXT_LINK(attr)) {
1205             if(attr->type == ATTR_DEFAULTVALUE_EXPR || attr->type == ATTR_DEFAULTVALUE_STRING) {
1206                 num_defaults++;
1207                 break;
1208             }
1209         }
1210     }
1211
1212     chat("add_func_desc: num of params %d\n", num_params);
1213
1214     name_offset = ctl2_alloc_name(typeinfo->typelib, func->def->name);
1215
1216     for(attr = func->def->attrs; attr; attr = NEXT_LINK(attr)) {
1217         expr_t *expr = attr->u.pval; 
1218         switch(attr->type) {
1219         case ATTR_ENTRY_ORDINAL:
1220             extra_attr = max(extra_attr, 3);
1221             entry = expr->cval;
1222             entry_is_ord = 1;
1223             break;
1224         case ATTR_ENTRY_STRING:
1225             extra_attr = max(extra_attr, 3);
1226             entry = ctl2_alloc_string(typeinfo->typelib, attr->u.pval);
1227             break;
1228         case ATTR_HELPCONTEXT:
1229             extra_attr = max(extra_attr, 1);
1230             help_context = expr->u.lval;
1231             break;
1232         case ATTR_HELPSTRING:
1233             extra_attr = max(extra_attr, 2);
1234             help_string_offset = ctl2_alloc_string(typeinfo->typelib, attr->u.pval);
1235             break;
1236         case ATTR_HELPSTRINGCONTEXT:
1237             extra_attr = max(extra_attr, 6);
1238             help_string_context = expr->u.lval;
1239             break;
1240         case ATTR_HIDDEN:
1241             funcflags |= 0x40; /* FUNCFLAG_FHIDDEN */
1242             break;
1243         case ATTR_ID:
1244             id = expr->u.lval;
1245             break;
1246         case ATTR_OUT:
1247             break;
1248         case ATTR_PROPGET:
1249             invokekind = 0x2; /* INVOKE_PROPERTYGET */
1250             break;
1251         case ATTR_PROPPUT:
1252             invokekind = 0x4; /* INVOKE_PROPERTYPUT */
1253             break;
1254         case ATTR_PROPPUTREF:
1255             invokekind = 0x8; /* INVOKE_PROPERTYPUTREF */
1256             break;
1257         case ATTR_RESTRICTED:
1258             funcflags |= 0x1; /* FUNCFLAG_FRESTRICTED */
1259             break;
1260         default:
1261             warning("add_func_desc: ignoring attr %d\n", attr->type);
1262             break;
1263         }
1264     }
1265
1266     switch(invokekind) {
1267     case 0x2: /* INVOKE_PROPERTYGET */
1268         if((num_params != 0 && (typeinfo->typeinfo->typekind & 15) == TKIND_DISPATCH)
1269            || (num_params != 1 && (typeinfo->typeinfo->typekind & 15) == TKIND_INTERFACE)) {
1270             error("expecting no args on a propget func\n");
1271             return S_FALSE;
1272         }
1273         break;
1274     case 0x4: /* INVOKE_PROPERTYPUT */
1275     case 0x8: /* INVOKE_PROPERTYPUTREF */
1276         if(num_params != 1) {
1277             error("expecting one arg on a propput func\n");
1278             return S_FALSE;
1279         }
1280         break;
1281     default:
1282         break;
1283     }
1284
1285     /* allocate type data space for us */
1286     typedata_size = 0x18 + extra_attr * sizeof(int) + (num_params * (num_defaults ? 16 : 12));
1287
1288     if (!typeinfo->func_data) {
1289         typeinfo->func_data = xmalloc(0x100);
1290         typeinfo->func_data_allocated = 0x100;
1291         typeinfo->func_data[0] = 0;
1292     }
1293
1294     if(typeinfo->func_data[0] + typedata_size + sizeof(int) > typeinfo->func_data_allocated) {
1295         typeinfo->func_data_allocated = max(typeinfo->func_data_allocated * 2,
1296                                             typeinfo->func_data[0] + typedata_size + sizeof(int));
1297         typeinfo->func_data = xrealloc(typeinfo->func_data, typeinfo->func_data_allocated);
1298     }
1299
1300     offset = typeinfo->func_data[0];
1301     typeinfo->func_data[0] += typedata_size;
1302     typedata = typeinfo->func_data + (offset >> 2) + 1;
1303
1304
1305     /* find func with the same name - if it exists use its id */
1306     for(i = 0; i < (typeinfo->typeinfo->cElement & 0xffff); i++) {
1307         if(name_offset == typeinfo->func_names[i]) {
1308             id = typeinfo->func_indices[i];
1309             break;
1310         }
1311     }
1312
1313     /* find the first func with the same id and link via the hiword of typedata[4] */
1314     next_idx = index;
1315     for(i = 0; i < (typeinfo->typeinfo->cElement & 0xffff); i++) {
1316         if(id == typeinfo->func_indices[i]) {
1317             next_idx = typeinfo->func_data[(typeinfo->func_offsets[i] >> 2) + 1 + 4] >> 16;
1318             typeinfo->func_data[(typeinfo->func_offsets[i] >> 2) + 1 + 4] &= 0xffff;
1319             typeinfo->func_data[(typeinfo->func_offsets[i] >> 2) + 1 + 4] |= (index << 16);
1320             break;
1321         }
1322     }
1323
1324     /* fill out the basic type information */
1325     typedata[0] = typedata_size | (index << 16);
1326     encode_var(typeinfo->typelib, func->def, &typedata[1], NULL, NULL, &decoded_size);
1327     typedata[2] = funcflags;
1328     typedata[3] = ((52 /*sizeof(FUNCDESC)*/ + decoded_size) << 16) | typeinfo->typeinfo->cbSizeVft;
1329     typedata[4] = (next_idx << 16) | (callconv << 8) | (invokekind << 3) | funckind;
1330     if(num_defaults) typedata[4] |= 0x1000;
1331     if(entry_is_ord) typedata[4] |= 0x2000;
1332     typedata[5] = num_params;
1333
1334     /* NOTE: High word of typedata[3] is total size of FUNCDESC + size of all ELEMDESCs for params + TYPEDESCs for pointer params and return types. */
1335     /* That is, total memory allocation required to reconstitute the FUNCDESC in its entirety. */
1336     typedata[3] += (16 /*sizeof(ELEMDESC)*/ * num_params) << 16;
1337     typedata[3] += (24 /*sizeof(PARAMDESCEX)*/ * num_defaults) << 16;
1338
1339     switch(extra_attr) {
1340     case 6: typedata[11] = help_string_context;
1341     case 5: typedata[10] = -1;
1342     case 4: typedata[9] = -1;
1343     case 3: typedata[8] = entry;
1344     case 2: typedata[7] = help_string_offset;
1345     case 1: typedata[6] = help_context;
1346     case 0:
1347         break;
1348     default:
1349         warning("unknown number of optional attrs\n");
1350     }
1351
1352     for (arg = last_arg, i = 0; arg; arg = PREV_LINK(arg), i++) {
1353         const attr_t *attr;
1354         int paramflags = 0;
1355         int *paramdata = typedata + 6 + extra_attr + (num_defaults ? num_params : 0) + i * 3;
1356         int *defaultdata = num_defaults ? typedata + 6 + extra_attr + i : NULL;
1357
1358         if(defaultdata) *defaultdata = -1;
1359
1360         encode_var(typeinfo->typelib, arg, paramdata, NULL, NULL, &decoded_size);
1361         for(attr = arg->attrs; attr; attr = NEXT_LINK(attr)) {
1362             switch(attr->type) {
1363             case ATTR_DEFAULTVALUE_EXPR:
1364               {
1365                 int vt;
1366                 expr_t *expr = (expr_t *)attr->u.pval;
1367                 if (arg->type->type == RPC_FC_ENUM16)
1368                     vt = VT_INT;
1369                 else
1370                     vt = get_var_vt(arg);
1371                 paramflags |= 0x30; /* PARAMFLAG_FHASDEFAULT | PARAMFLAG_FOPT */
1372                 chat("default value %ld\n", expr->cval);
1373                 write_value(typeinfo->typelib, defaultdata, vt, &expr->cval);
1374                 break;
1375               }
1376             case ATTR_DEFAULTVALUE_STRING:
1377               {
1378                 char *s = (char *)attr->u.pval;
1379                 int vt;
1380                 if (arg->type->type == RPC_FC_ENUM16)
1381                   vt = VT_INT;
1382                 else
1383                   vt = get_var_vt(arg);
1384                 paramflags |= 0x30; /* PARAMFLAG_FHASDEFAULT | PARAMFLAG_FOPT */
1385                 chat("default value '%s'\n", s);
1386                 write_value(typeinfo->typelib, defaultdata, vt, s);
1387                 break;
1388               }
1389             case ATTR_IN:
1390                 paramflags |= 0x01; /* PARAMFLAG_FIN */
1391                 break;
1392             case ATTR_OPTIONAL:
1393                 paramflags |= 0x10; /* PARAMFLAG_FOPT */
1394                 break;
1395             case ATTR_OUT:
1396                 paramflags |= 0x02; /* PARAMFLAG_FOUT */
1397                 break;
1398             case ATTR_RETVAL:
1399                 paramflags |= 0x08; /* PARAMFLAG_FRETVAL */
1400                 typedata[4] |= 0x4000;
1401                 break;
1402             default:
1403                 chat("unhandled param attr %d\n", attr->type);
1404                 break;
1405             }
1406         }
1407         paramdata[1] = -1;
1408         paramdata[2] = paramflags;
1409         typedata[3] += decoded_size << 16;
1410     }
1411
1412     if(typeinfo->funcs_allocated == 0) {
1413         typeinfo->funcs_allocated = 10;
1414         typeinfo->func_indices = xmalloc(typeinfo->funcs_allocated * sizeof(int));
1415         typeinfo->func_names   = xmalloc(typeinfo->funcs_allocated * sizeof(int));
1416         typeinfo->func_offsets = xmalloc(typeinfo->funcs_allocated * sizeof(int));
1417     }
1418     if(typeinfo->funcs_allocated == (typeinfo->typeinfo->cElement & 0xffff)) {
1419         typeinfo->funcs_allocated *= 2;
1420         typeinfo->func_indices = xrealloc(typeinfo->func_indices, typeinfo->funcs_allocated * sizeof(int));
1421         typeinfo->func_names   = xrealloc(typeinfo->func_names,   typeinfo->funcs_allocated * sizeof(int));
1422         typeinfo->func_offsets = xrealloc(typeinfo->func_offsets, typeinfo->funcs_allocated * sizeof(int));
1423     }
1424
1425     /* update the index data */
1426     typeinfo->func_indices[typeinfo->typeinfo->cElement & 0xffff] = id; 
1427     typeinfo->func_offsets[typeinfo->typeinfo->cElement & 0xffff] = offset;
1428     typeinfo->func_names[typeinfo->typeinfo->cElement & 0xffff] = name_offset;
1429
1430     /* ??? */
1431     if (!typeinfo->typeinfo->res2) typeinfo->typeinfo->res2 = 0x20;
1432     typeinfo->typeinfo->res2 <<= 1;
1433     /* ??? */
1434     if (index < 2) typeinfo->typeinfo->res2 += num_params << 4;
1435
1436     if (typeinfo->typeinfo->res3 == -1) typeinfo->typeinfo->res3 = 0;
1437     typeinfo->typeinfo->res3 += 0x38 + num_params * 0x10;
1438     if(num_defaults) typeinfo->typeinfo->res3 += num_params * 0x4;
1439
1440     /* adjust size of VTBL */
1441     if(funckind != 0x3 /* FUNC_STATIC */)
1442         typeinfo->typeinfo->cbSizeVft += 4;
1443
1444     /* Increment the number of function elements */
1445     typeinfo->typeinfo->cElement += 1;
1446
1447     namedata = typeinfo->typelib->typelib_segment_data[MSFT_SEG_NAME] + name_offset;
1448     if (*((INT *)namedata) == -1) {
1449         *((INT *)namedata) = typeinfo->typelib->typelib_typeinfo_offsets[typeinfo->typeinfo->typekind >> 16];
1450         if((typeinfo->typeinfo->typekind & 15) == TKIND_MODULE)
1451             namedata[9] |= 0x10;
1452     } else
1453         namedata[9] &= ~0x10;
1454
1455     if((typeinfo->typeinfo->typekind & 15) == TKIND_MODULE)
1456         namedata[9] |= 0x20;
1457
1458     if(invokekind != 0x4 /* INVOKE_PROPERTYPUT */ && invokekind != 0x8 /* INVOKE_PROPERTYPUTREF */) { 
1459         /* don't give the arg of a [propput*] func a name */
1460         for (arg = last_arg, i = 0; arg; arg = PREV_LINK(arg), i++) {
1461             int *paramdata = typedata + 6 + extra_attr + (num_defaults ? num_params : 0) + i * 3;
1462             offset = ctl2_alloc_name(typeinfo->typelib, arg->name);
1463             paramdata[1] = offset;
1464         }
1465     }
1466     return S_OK;
1467 }
1468
1469 static HRESULT add_var_desc(msft_typeinfo_t *typeinfo, UINT index, var_t* var)
1470 {
1471     int offset, id;
1472     unsigned int typedata_size;
1473     INT *typedata;
1474     int var_datawidth;
1475     int var_alignment;
1476     int var_type_size, var_kind = 0 /* VAR_PERINSTANCE */; 
1477     int alignment;
1478     int varflags = 0;
1479     const attr_t *attr;
1480     char *namedata;
1481     int var_num = (typeinfo->typeinfo->cElement >> 16) & 0xffff;
1482
1483     chat("add_var_desc(%d,%s) array %p\n", index, var->name, var->array);
1484
1485     id = 0x40000000 + index;
1486
1487     for(attr = var->attrs; attr; attr = NEXT_LINK(attr)) {
1488         expr_t *expr = attr->u.pval; 
1489         switch(attr->type) {
1490         case ATTR_HIDDEN:
1491             varflags |= 0x40; /* VARFLAG_FHIDDEN */
1492             break;
1493         case ATTR_ID:
1494             id = expr->u.lval;
1495             break;
1496         case ATTR_READONLY:
1497             varflags |= 0x01; /* VARFLAG_FREADONLY */
1498             break;
1499         case ATTR_RESTRICTED:
1500             varflags |= 0x80; /* VARFLAG_FRESTRICTED */
1501             break;
1502         case ATTR_SOURCE:
1503             varflags |= 0x02; /* VARFLAG_FSOURCE */
1504             break;
1505         default:
1506             warning("AddVarDesc: unhandled attr type %d\n", attr->type);
1507             break;
1508         }
1509     }
1510
1511     /* allocate type data space for us */
1512     typedata_size = 0x14;
1513
1514     if (!typeinfo->var_data) {
1515         typeinfo->var_data = xmalloc(0x100);
1516         typeinfo->var_data_allocated = 0x100;
1517         typeinfo->var_data[0] = 0;
1518     }
1519
1520     if(typeinfo->var_data[0] + typedata_size + sizeof(int) > typeinfo->var_data_allocated) {
1521         typeinfo->var_data_allocated = max(typeinfo->var_data_allocated * 2,
1522                                             typeinfo->var_data[0] + typedata_size + sizeof(int));
1523         typeinfo->var_data = xrealloc(typeinfo->var_data, typeinfo->var_data_allocated);
1524     }
1525
1526     offset = typeinfo->var_data[0];
1527     typeinfo->var_data[0] += typedata_size;
1528     typedata = typeinfo->var_data + (offset >> 2) + 1;
1529
1530     /* fill out the basic type information */
1531     typedata[0] = typedata_size | (index << 16);
1532     typedata[2] = varflags;
1533     typedata[3] = (36 /*sizeof(VARDESC)*/ << 16) | 0;
1534
1535     if(typeinfo->vars_allocated == 0) {
1536         typeinfo->vars_allocated = 10;
1537         typeinfo->var_indices = xmalloc(typeinfo->vars_allocated * sizeof(int));
1538         typeinfo->var_names   = xmalloc(typeinfo->vars_allocated * sizeof(int));
1539         typeinfo->var_offsets = xmalloc(typeinfo->vars_allocated * sizeof(int));
1540     }
1541     if(typeinfo->vars_allocated == var_num) {
1542         typeinfo->vars_allocated *= 2;
1543         typeinfo->var_indices = xrealloc(typeinfo->var_indices, typeinfo->vars_allocated * sizeof(int));
1544         typeinfo->var_names   = xrealloc(typeinfo->var_names,   typeinfo->vars_allocated * sizeof(int));
1545         typeinfo->var_offsets = xrealloc(typeinfo->var_offsets, typeinfo->vars_allocated * sizeof(int));
1546     }
1547     /* update the index data */
1548     typeinfo->var_indices[var_num] = id;
1549     typeinfo->var_names[var_num] = -1;
1550     typeinfo->var_offsets[var_num] = offset;
1551
1552     /* figure out type widths and whatnot */
1553     encode_var(typeinfo->typelib, var, &typedata[1], &var_datawidth,
1554                &var_alignment, &var_type_size);
1555
1556     /* pad out starting position to data width */
1557     typeinfo->datawidth += var_alignment - 1;
1558     typeinfo->datawidth &= ~(var_alignment - 1);
1559
1560     switch(typeinfo->typeinfo->typekind & 0xf) {
1561     case TKIND_ENUM:
1562         write_value(typeinfo->typelib, &typedata[4], VT_I4, &var->lval);
1563         var_kind = 2; /* VAR_CONST */
1564         var_type_size += 16; /* sizeof(VARIANT) */
1565         typeinfo->datawidth = var_datawidth;
1566         break;
1567     case TKIND_RECORD:
1568         typedata[4] = typeinfo->datawidth;
1569         typeinfo->datawidth += var_datawidth;
1570         break;
1571     case TKIND_DISPATCH:
1572         var_kind = 3; /* VAR_DISPATCH */
1573         typeinfo->datawidth = 4;
1574         var_alignment = 4;
1575         break;
1576     default:
1577         error("add_var_desc: unhandled type kind %d\n", typeinfo->typeinfo->typekind & 0xf);
1578         break;
1579     }
1580
1581     /* add type description size to total required allocation */
1582     typedata[3] += var_type_size << 16 | var_kind;
1583
1584     /* fix type alignment */
1585     alignment = (typeinfo->typeinfo->typekind >> 11) & 0x1f;
1586     if (alignment < var_alignment) {
1587         alignment = var_alignment;
1588         typeinfo->typeinfo->typekind &= ~0xffc0;
1589         typeinfo->typeinfo->typekind |= alignment << 11 | alignment << 6;
1590     }
1591
1592     /* ??? */
1593     if (!typeinfo->typeinfo->res2) typeinfo->typeinfo->res2 = 0x1a;
1594     if ((index == 0) || (index == 1) || (index == 2) || (index == 4) || (index == 9)) {
1595         typeinfo->typeinfo->res2 <<= 1;
1596     }
1597
1598     /* ??? */
1599     if (typeinfo->typeinfo->res3 == -1) typeinfo->typeinfo->res3 = 0;
1600     typeinfo->typeinfo->res3 += 0x2c;
1601
1602     /* increment the number of variable elements */
1603     typeinfo->typeinfo->cElement += 0x10000;
1604
1605     /* pad data width to alignment */
1606     typeinfo->typeinfo->size = (typeinfo->datawidth + (alignment - 1)) & ~(alignment - 1);
1607
1608     offset = ctl2_alloc_name(typeinfo->typelib, var->name);
1609     if (offset == -1) return E_OUTOFMEMORY;
1610
1611     namedata = typeinfo->typelib->typelib_segment_data[MSFT_SEG_NAME] + offset;
1612     if (*((INT *)namedata) == -1) {
1613         *((INT *)namedata) = typeinfo->typelib->typelib_typeinfo_offsets[typeinfo->typeinfo->typekind >> 16];
1614         if((typeinfo->typeinfo->typekind & 15) != TKIND_DISPATCH)
1615             namedata[9] |= 0x10;
1616     } else
1617         namedata[9] &= ~0x10;
1618
1619     if ((typeinfo->typeinfo->typekind & 15) == TKIND_ENUM) {
1620         namedata[9] |= 0x20;
1621     }
1622     typeinfo->var_names[var_num] = offset;
1623
1624     return S_OK;
1625 }
1626
1627 static HRESULT add_impl_type(msft_typeinfo_t *typeinfo, type_t *ref)
1628 {
1629     if(ref->typelib_idx == -1)
1630         add_interface_typeinfo(typeinfo->typelib, ref);
1631     if(ref->typelib_idx == -1)
1632         error("add_impl_type: unable to add inherited interface\n");
1633
1634     typeinfo->typeinfo->datatype1 = typeinfo->typelib->typelib_typeinfo_offsets[ref->typelib_idx];
1635     typeinfo->typeinfo->cImplTypes++;
1636     return S_OK;
1637 }
1638
1639 static msft_typeinfo_t *create_msft_typeinfo(msft_typelib_t *typelib, enum type_kind kind,
1640                                              const char *name, const attr_t *attr, int idx)
1641 {
1642     msft_typeinfo_t *msft_typeinfo;
1643     int nameoffset;
1644     int typeinfo_offset;
1645     MSFT_TypeInfoBase *typeinfo;
1646     MSFT_GuidEntry guidentry;
1647
1648     chat("create_msft_typeinfo: name %s kind %d\n", name, kind);
1649
1650     msft_typeinfo = xmalloc(sizeof(*msft_typeinfo));
1651
1652     msft_typeinfo->typelib = typelib;
1653
1654     nameoffset = ctl2_alloc_name(typelib, name);
1655     typeinfo_offset = ctl2_alloc_typeinfo(typelib, nameoffset);
1656     typeinfo = (MSFT_TypeInfoBase *)&typelib->typelib_segment_data[MSFT_SEG_TYPEINFO][typeinfo_offset];
1657
1658     typelib->typelib_segment_data[MSFT_SEG_NAME][nameoffset + 9] = 0x38;
1659     *((int *)&typelib->typelib_segment_data[MSFT_SEG_NAME][nameoffset]) = typeinfo_offset;
1660
1661     msft_typeinfo->typeinfo = typeinfo;
1662
1663     typeinfo->typekind |= kind | 0x20;
1664
1665     if(kind == TKIND_COCLASS)
1666         typeinfo->flags |= 0x2; /* TYPEFLAG_FCANCREATE */
1667
1668     for( ; attr; attr = NEXT_LINK(attr)) {
1669         switch(attr->type) {
1670         case ATTR_AGGREGATABLE:
1671             if (kind == TKIND_COCLASS)
1672                 typeinfo->flags |= 0x400; /* TYPEFLAG_FAGGREGATABLE */
1673             break;
1674
1675         case ATTR_APPOBJECT:
1676             if (kind == TKIND_COCLASS)
1677                 typeinfo->flags |= 0x1; /* TYPEFLAG_FAPPOBJECT */
1678             break;
1679
1680         case ATTR_CONTROL:
1681             if (kind == TKIND_COCLASS)
1682                 typeinfo->flags |= 0x20; /* TYPEFLAG_FCONTROL */
1683             break;
1684
1685         case ATTR_DISPINTERFACE:
1686             break;
1687
1688         case ATTR_DLLNAME:
1689           {
1690             int offset = ctl2_alloc_string(typelib, attr->u.pval);
1691             typeinfo->datatype1 = offset;
1692             break;
1693           }
1694
1695         case ATTR_DUAL:
1696             /* FIXME: check interface is compatible */
1697             typeinfo->flags |= 0x140; /* TYPEFLAG_FDUAL | TYPEFLAG_FOLEAUTOMATION */
1698             break;
1699
1700         case ATTR_HELPCONTEXT:
1701           {
1702             expr_t *expr = (expr_t*)attr->u.pval;
1703             typeinfo->helpcontext = expr->cval;
1704             break;
1705           }
1706         case ATTR_HELPSTRING:
1707           {
1708             int offset = ctl2_alloc_string(typelib, attr->u.pval);
1709             if (offset == -1) break;
1710             typeinfo->docstringoffs = offset;
1711             break;
1712           }
1713         case ATTR_HELPSTRINGCONTEXT:
1714           {
1715             expr_t *expr = (expr_t*)attr->u.pval;
1716             typeinfo->helpstringcontext = expr->cval;
1717             break;
1718           }
1719         case ATTR_HIDDEN:
1720             typeinfo->flags |= 0x10; /* TYPEFLAG_FHIDDEN */
1721             break;
1722
1723         case ATTR_NONCREATABLE:
1724             typeinfo->flags &= ~0x2; /* TYPEFLAG_FCANCREATE */
1725             break;
1726
1727         case ATTR_NONEXTENSIBLE:
1728             typeinfo->flags |= 0x80; /* TYPEFLAG_FNONEXTENSIBLE */
1729             break;
1730
1731         case ATTR_ODL:
1732             break;
1733
1734         case ATTR_OLEAUTOMATION:
1735             typeinfo->flags |= 0x100; /* TYPEFLAG_FOLEAUTOMATION */
1736             break;
1737
1738         case ATTR_PUBLIC:
1739             break;
1740
1741         case ATTR_RESTRICTED:
1742             typeinfo->flags |= 0x200; /* TYPEFLAG_FRESTRICTED */
1743             break;
1744
1745         case ATTR_UUID:
1746             guidentry.guid = *(GUID*)attr->u.pval;
1747             guidentry.hreftype = typelib->typelib_typeinfo_offsets[typeinfo->typekind >> 16];
1748             guidentry.next_hash = -1;
1749             typeinfo->posguid = ctl2_alloc_guid(typelib, &guidentry);
1750 #if 0
1751             if (IsEqualIID(guid, &IID_IDispatch)) {
1752                 typelib->typelib_header.dispatchpos = typelib->typelib_typeinfo_offsets[typeinfo->typekind >> 16];
1753             }
1754 #endif
1755             break;
1756
1757         case ATTR_VERSION:
1758             typeinfo->version = attr->u.ival;
1759             break;
1760
1761         default:
1762             warning("create_msft_typeinfo: ignoring attr %d\n", attr->type);
1763             break;
1764         }
1765     }
1766
1767     if (typelib->last_typeinfo) typelib->last_typeinfo->next_typeinfo = msft_typeinfo;
1768     typelib->last_typeinfo = msft_typeinfo;
1769     if (!typelib->typeinfos) typelib->typeinfos = msft_typeinfo;
1770
1771
1772     return msft_typeinfo;
1773 }
1774
1775 static void add_dispatch(msft_typelib_t *typelib)
1776 {
1777     int guid_offset, impfile_offset;
1778     MSFT_GuidEntry guidentry;
1779     MSFT_ImpInfo impinfo;
1780     GUID stdole =        {0x00020430,0x0000,0x0000,{0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46}};
1781     GUID iid_idispatch = {0x00020400,0x0000,0x0000,{0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46}};
1782
1783     if(typelib->typelib_header.dispatchpos != -1) return;
1784
1785     guidentry.guid = stdole;
1786     guidentry.hreftype = 2;
1787     guidentry.next_hash = -1;
1788     guid_offset = ctl2_alloc_guid(typelib, &guidentry);
1789     impfile_offset = alloc_importfile(typelib, guid_offset, 2, 0, "stdole2.tlb");
1790
1791     guidentry.guid = iid_idispatch;
1792     guidentry.hreftype = 1;
1793     guidentry.next_hash = -1;
1794     impinfo.flags = TKIND_INTERFACE << 24 | MSFT_IMPINFO_OFFSET_IS_GUID;
1795     impinfo.oImpFile = impfile_offset;
1796     impinfo.oGuid = ctl2_alloc_guid(typelib, &guidentry);
1797     typelib->typelib_header.dispatchpos = alloc_importinfo(typelib, &impinfo) | 0x01;
1798
1799     typelib->typelib_header.res50 = 1;
1800
1801 }
1802
1803 static void add_dispinterface_typeinfo(msft_typelib_t *typelib, type_t *dispinterface)
1804
1805     int idx = 0;
1806     func_t *func;
1807     var_t *var;
1808     msft_typeinfo_t *msft_typeinfo;
1809
1810     dispinterface->typelib_idx = typelib->typelib_header.nrtypeinfos;
1811     msft_typeinfo = create_msft_typeinfo(typelib, TKIND_DISPATCH, dispinterface->name,
1812                                          dispinterface->attrs, typelib->typelib_header.nrtypeinfos);
1813
1814     msft_typeinfo->typeinfo->size = 4;
1815     msft_typeinfo->typeinfo->typekind |= 0x2100;
1816
1817     msft_typeinfo->typeinfo->flags |= 0x1000; /* TYPEFLAG_FDISPATCHABLE */
1818     add_dispatch(typelib);
1819     msft_typeinfo->typeinfo->cImplTypes = 1;
1820
1821     /* count the no of funcs, as the variable indicies come after the funcs */
1822     if((func = dispinterface->funcs)) {
1823         idx++;
1824         while(NEXT_LINK(func)) {
1825             func = NEXT_LINK(func);
1826             idx++;
1827         }
1828     }
1829
1830     if((var = dispinterface->fields)) {
1831         while(NEXT_LINK(var)) var = NEXT_LINK(var);
1832         while(var) {
1833             add_var_desc(msft_typeinfo, idx, var);
1834             idx++;
1835             var = PREV_LINK(var);
1836         }
1837     }
1838
1839     idx = 0;
1840     /* the func count above has already left us pointing at the first func */
1841     while(func) {
1842         if(add_func_desc(msft_typeinfo, func, idx) == S_OK)
1843             idx++;
1844         func = PREV_LINK(func);
1845     }
1846 }
1847
1848 static void add_interface_typeinfo(msft_typelib_t *typelib, type_t *interface)
1849 {
1850     int idx = 0;
1851     func_t *func;
1852     type_t *ref;
1853     msft_typeinfo_t *msft_typeinfo;
1854     int num_parents = 0, num_funcs = 0;
1855     const attr_t *attr;
1856     const type_t *derived;
1857
1858     for(attr = interface->attrs; attr; attr = NEXT_LINK(attr))
1859         if(attr->type == ATTR_DISPINTERFACE)
1860             return add_dispinterface_typeinfo(typelib, interface);
1861
1862     /* midl adds the parent interface first, unless the parent itself
1863        has no parent (i.e. it stops before IUnknown). */
1864
1865     if(interface->ref && interface->ref->ref && interface->ref->typelib_idx == -1)
1866         add_interface_typeinfo(typelib, interface->ref);
1867
1868     interface->typelib_idx = typelib->typelib_header.nrtypeinfos;
1869     msft_typeinfo = create_msft_typeinfo(typelib, TKIND_INTERFACE, interface->name, interface->attrs,
1870                                          typelib->typelib_header.nrtypeinfos);
1871     msft_typeinfo->typeinfo->size = 4;
1872     msft_typeinfo->typeinfo->typekind |= 0x2200;
1873
1874     for (derived = interface->ref; derived; derived = derived->ref)
1875         if (derived->name && !strcmp(derived->name, "IDispatch"))
1876             msft_typeinfo->typeinfo->flags |= 0x1000; /* TYPEFLAG_FDISPATCHABLE */
1877
1878     /* can't be dual if it doesn't derive from IDispatch */
1879     if (!(msft_typeinfo->typeinfo->flags & 0x1000)) /* TYPEFLAG_FDISPATCHABLE */
1880         msft_typeinfo->typeinfo->flags &= ~0x40; /* TYPEFLAG_FDUAL */
1881
1882     if(interface->ref)
1883         add_impl_type(msft_typeinfo, interface->ref);
1884
1885     /* count the number of inherited interfaces and non-local functions */
1886     for(ref = interface->ref; ref; ref = ref->ref) {
1887         num_parents++;
1888         for(func = ref->funcs; func; func = NEXT_LINK(func)) {
1889             const attr_t *attr;
1890             for(attr = func->def->attrs; attr; attr = NEXT_LINK(attr))
1891                 if(attr->type == ATTR_LOCAL)
1892                     break;
1893             if(!attr)
1894                 num_funcs++;
1895         }
1896     }
1897     msft_typeinfo->typeinfo->datatype2 = num_funcs << 16 | num_parents;
1898     msft_typeinfo->typeinfo->cbSizeVft = num_funcs * 4;
1899
1900     if((func = interface->funcs)) {
1901         while(NEXT_LINK(func)) func = NEXT_LINK(func);
1902         while(func) {
1903             if(add_func_desc(msft_typeinfo, func, idx) == S_OK)
1904                 idx++;
1905             func = PREV_LINK(func);
1906         }
1907     }
1908 }
1909
1910 static void add_structure_typeinfo(msft_typelib_t *typelib, type_t *structure)
1911 {
1912     int idx = 0;
1913     var_t *cur = structure->fields;
1914     msft_typeinfo_t *msft_typeinfo;
1915
1916     structure->typelib_idx = typelib->typelib_header.nrtypeinfos;
1917     msft_typeinfo = create_msft_typeinfo(typelib, TKIND_RECORD, structure->name, structure->attrs,
1918                                          typelib->typelib_header.nrtypeinfos);
1919     msft_typeinfo->typeinfo->size = 0;
1920
1921     while(NEXT_LINK(cur)) cur = NEXT_LINK(cur);
1922     while(cur) {
1923         add_var_desc(msft_typeinfo, idx, cur);
1924         idx++;
1925         cur = PREV_LINK(cur);
1926     }
1927 }
1928
1929 static void add_enum_typeinfo(msft_typelib_t *typelib, type_t *enumeration)
1930 {
1931     int idx = 0;
1932     var_t *cur = enumeration->fields;
1933     msft_typeinfo_t *msft_typeinfo;
1934
1935     enumeration->typelib_idx = typelib->typelib_header.nrtypeinfos;
1936     msft_typeinfo = create_msft_typeinfo(typelib, TKIND_ENUM, enumeration->name, enumeration->attrs,
1937                                          typelib->typelib_header.nrtypeinfos);
1938     msft_typeinfo->typeinfo->size = 0;
1939
1940     while(NEXT_LINK(cur)) cur = NEXT_LINK(cur);
1941     while(cur) {
1942         add_var_desc(msft_typeinfo, idx, cur);
1943         idx++;
1944         cur = PREV_LINK(cur);
1945     }
1946 }
1947
1948 static void add_typedef_typeinfo(msft_typelib_t *typelib, var_t *tdef)
1949 {
1950     msft_typeinfo_t *msft_typeinfo;
1951     int alignment;
1952     const attr_t *attrs;
1953
1954     tdef->type->typelib_idx = typelib->typelib_header.nrtypeinfos;
1955     msft_typeinfo = create_msft_typeinfo(typelib, TKIND_ALIAS, tdef->name, tdef->type->attrs,
1956                                          typelib->typelib_header.nrtypeinfos);
1957     attrs = tdef->type->attrs;
1958     tdef->type->attrs = NULL;
1959     encode_var(typelib, tdef, &msft_typeinfo->typeinfo->datatype1, &msft_typeinfo->typeinfo->size,
1960                &alignment, &msft_typeinfo->typeinfo->datatype2);
1961     tdef->type->attrs = attrs;
1962     msft_typeinfo->typeinfo->typekind |= (alignment << 11 | alignment << 6);
1963 }
1964
1965 static void add_coclass_typeinfo(msft_typelib_t *typelib, class_t *cls)
1966 {
1967     msft_typeinfo_t *msft_typeinfo;
1968     ifref_t *iref;
1969     int num_ifaces = 0, offset, i;
1970     MSFT_RefRecord *ref, *first = NULL, *first_source = NULL;
1971     int have_default = 0, have_default_source = 0;
1972     const attr_t *attr;
1973
1974     msft_typeinfo = create_msft_typeinfo(typelib, TKIND_COCLASS, cls->name, cls->attrs,
1975                                          typelib->typelib_header.nrtypeinfos);
1976
1977     if((iref = cls->ifaces)) {
1978         num_ifaces++;
1979         while(NEXT_LINK(iref)) {
1980             iref = NEXT_LINK(iref);
1981             num_ifaces++;
1982         }
1983     }
1984
1985     offset = msft_typeinfo->typeinfo->datatype1 = ctl2_alloc_segment(typelib, MSFT_SEG_REFERENCES,
1986                                                                      num_ifaces * sizeof(*ref), 0);
1987     for(i = 0; i < num_ifaces; i++) {
1988         if(iref->iface->typelib_idx == -1)
1989             add_interface_typeinfo(typelib, iref->iface);
1990         ref = (MSFT_RefRecord*) (typelib->typelib_segment_data[MSFT_SEG_REFERENCES] + offset + i * sizeof(*ref));
1991         ref->reftype = typelib->typelib_typeinfo_offsets[iref->iface->typelib_idx];
1992         ref->flags = 0;
1993         ref->oCustData = -1;
1994         ref->onext = -1;
1995         if(i < num_ifaces - 1)
1996             ref->onext = offset + (i + 1) * sizeof(*ref);
1997
1998         for(attr = iref->attrs; attr; attr = NEXT_LINK(attr)) {
1999             switch(attr->type) {
2000             case ATTR_DEFAULT:
2001                 ref->flags |= 0x1; /* IMPLTYPEFLAG_FDEFAULT */
2002                 break;
2003             case ATTR_RESTRICTED:
2004                 ref->flags |= 0x4; /* IMPLTYPEFLAG_FRESTRICTED */
2005                 break;
2006             case ATTR_SOURCE:
2007                 ref->flags |= 0x2; /* IMPLTYPEFLAG_FSOURCE */
2008                 break;
2009             default:
2010                 warning("add_coclass_typeinfo: unhandled attr %d\n", attr->type);
2011             }
2012         }
2013         if(ref->flags & 0x1) { /* IMPLTYPEFLAG_FDEFAULT */
2014             if(ref->flags & 0x2) /* IMPLTYPEFLAG_SOURCE */
2015                 have_default_source = 1;
2016             else
2017                 have_default = 1;
2018         }
2019
2020         /* If the interface is non-restricted and we haven't already had one then
2021            remember it so that we can use it as a default later */
2022         if((ref->flags & 0x4) == 0) { /* IMPLTYPEFLAG_FRESTRICTED */
2023             if(ref->flags & 0x2) { /* IMPLTYPEFLAG_FSOURCE */
2024                 if(!first_source)
2025                     first_source = ref;
2026             }
2027             else if(!first)
2028                 first = ref;
2029         }
2030         iref = PREV_LINK(iref);
2031     }
2032
2033     /* If we haven't had a default interface, then set the default flags on the
2034        first ones */
2035     if(!have_default && first)
2036         first->flags |= 0x1;
2037     if(!have_default_source && first_source)
2038         first_source->flags |= 0x1;
2039
2040     msft_typeinfo->typeinfo->cImplTypes = num_ifaces;
2041     msft_typeinfo->typeinfo->size = 4;
2042     msft_typeinfo->typeinfo->typekind |= 0x2200;
2043 }
2044
2045 static void add_module_typeinfo(msft_typelib_t *typelib, type_t *module)
2046 {
2047     int idx = 0;
2048     func_t *func;
2049     msft_typeinfo_t *msft_typeinfo;
2050
2051     module->typelib_idx = typelib->typelib_header.nrtypeinfos;
2052     msft_typeinfo = create_msft_typeinfo(typelib, TKIND_MODULE, module->name, module->attrs,
2053                                          typelib->typelib_header.nrtypeinfos);
2054     msft_typeinfo->typeinfo->typekind |= 0x0a00;
2055
2056     if((func = module->funcs)) {
2057         while(NEXT_LINK(func)) func = NEXT_LINK(func);
2058         while(func) {
2059             if(add_func_desc(msft_typeinfo, func, idx) == S_OK)
2060                 idx++;
2061             func = PREV_LINK(func);
2062         }
2063     }
2064     msft_typeinfo->typeinfo->size = idx;
2065 }
2066
2067 static void add_entry(msft_typelib_t *typelib, typelib_entry_t *entry)
2068 {
2069     switch(entry->kind) {
2070     case TKIND_INTERFACE:
2071         add_interface_typeinfo(typelib, entry->u.interface);
2072         break;
2073
2074     case TKIND_RECORD:
2075         add_structure_typeinfo(typelib, entry->u.structure);
2076         break;
2077
2078     case TKIND_ENUM:
2079         add_enum_typeinfo(typelib, entry->u.enumeration);
2080         break;
2081
2082     case TKIND_ALIAS:
2083         add_typedef_typeinfo(typelib, entry->u.tdef);
2084         break;
2085
2086     case TKIND_COCLASS:
2087         add_coclass_typeinfo(typelib, entry->u.class);
2088         break;
2089
2090     case TKIND_MODULE:
2091         add_module_typeinfo(typelib, entry->u.module);
2092         break;
2093
2094     default:
2095         error("add_entry: unhandled type %d\n", entry->kind);
2096         break;
2097     }
2098 }
2099
2100 static void set_name(msft_typelib_t *typelib)
2101 {
2102     int offset;
2103
2104     offset = ctl2_alloc_name(typelib, typelib->typelib->name);
2105     if (offset == -1) return;
2106     typelib->typelib_header.NameOffset = offset;
2107     return;
2108 }
2109
2110 static void set_version(msft_typelib_t *typelib)
2111 {
2112     long version = MAKELONG(0,0);
2113     const attr_t *attr;
2114
2115     for(attr = typelib->typelib->attrs; attr; attr = NEXT_LINK(attr)) {
2116         if(attr->type == ATTR_VERSION) {
2117             version = attr->u.ival;
2118         }
2119     }
2120     typelib->typelib_header.version = version;
2121     return;
2122 }
2123
2124 static void set_guid(msft_typelib_t *typelib)
2125 {
2126     MSFT_GuidEntry guidentry;
2127     int offset;
2128     const attr_t *attr;
2129     GUID guid = {0,0,0,{0,0,0,0,0,0}};
2130
2131     guidentry.guid = guid;
2132     guidentry.hreftype = -2;
2133     guidentry.next_hash = -1;
2134
2135     for(attr = typelib->typelib->attrs; attr; attr = NEXT_LINK(attr)) {
2136         if(attr->type == ATTR_UUID) {
2137             guidentry.guid = *(GUID*)(attr->u.pval);
2138         }
2139     }
2140
2141     offset = ctl2_alloc_guid(typelib, &guidentry);
2142     
2143     if (offset == -1) return;
2144
2145     typelib->typelib_header.posguid = offset;
2146
2147     return;
2148 }
2149
2150 static void set_doc_string(msft_typelib_t *typelib)
2151 {
2152     const attr_t *attr;
2153     int offset;
2154
2155     for(attr = typelib->typelib->attrs; attr; attr = NEXT_LINK(attr)) {
2156         if(attr->type == ATTR_HELPSTRING) {
2157             offset = ctl2_alloc_string(typelib, attr->u.pval);
2158             if (offset == -1) return;
2159             typelib->typelib_header.helpstring = offset;
2160         }
2161     }
2162     return;
2163 }
2164
2165 static void set_help_file_name(msft_typelib_t *typelib)
2166 {
2167     int offset;
2168     const attr_t *attr;
2169     for(attr = typelib->typelib->attrs; attr; attr = NEXT_LINK(attr)) {
2170         if(attr->type == ATTR_HELPFILE) {
2171             offset = ctl2_alloc_string(typelib, attr->u.pval);
2172             if (offset == -1) return;
2173             typelib->typelib_header.helpfile = offset;
2174             typelib->typelib_header.varflags |= 0x10;
2175         }
2176     }
2177     return;
2178 }
2179
2180 static void set_help_context(msft_typelib_t *typelib)
2181 {
2182     const attr_t *attr;
2183     for(attr = typelib->typelib->attrs; attr; attr = NEXT_LINK(attr)) {
2184         if(attr->type == ATTR_HELPCONTEXT) {
2185             const expr_t *expr = (expr_t *)attr->u.pval;
2186             typelib->typelib_header.helpcontext = expr->cval;
2187         }
2188     }
2189     return;
2190 }
2191
2192 static void set_help_string_dll(msft_typelib_t *typelib)
2193 {
2194     int offset;
2195     const attr_t *attr;
2196     for(attr = typelib->typelib->attrs; attr; attr = NEXT_LINK(attr)) {
2197         if(attr->type == ATTR_HELPSTRINGDLL) {
2198             offset = ctl2_alloc_string(typelib, attr->u.pval);
2199             if (offset == -1) return;
2200             typelib->help_string_dll_offset = offset;
2201             typelib->typelib_header.varflags |= 0x100;
2202         }
2203     }
2204     return;
2205 }
2206
2207 static void set_help_string_context(msft_typelib_t *typelib)
2208 {
2209     const attr_t *attr;
2210     for(attr = typelib->typelib->attrs; attr; attr = NEXT_LINK(attr)) {
2211         if(attr->type == ATTR_HELPSTRINGCONTEXT) {
2212             const expr_t *expr = (expr_t *)attr->u.pval;
2213             typelib->typelib_header.helpstringcontext = expr->cval;
2214         }
2215     }
2216     return;
2217 }
2218
2219 static void set_lcid(msft_typelib_t *typelib)
2220 {
2221     typelib->typelib_header.lcid2 = 0x0;
2222     return;
2223 }
2224
2225 static void set_lib_flags(msft_typelib_t *typelib)
2226 {
2227     const attr_t *attr;
2228
2229     typelib->typelib_header.flags = 0;
2230     for(attr = typelib->typelib->attrs; attr; attr = NEXT_LINK(attr)) {
2231         switch(attr->type) {
2232         case ATTR_CONTROL:
2233             typelib->typelib_header.flags |= 0x02; /* LIBFLAG_FCONTROL */
2234             break;
2235         case ATTR_HIDDEN:
2236             typelib->typelib_header.flags |= 0x04; /* LIBFLAG_FHIDDEN */
2237             break;
2238         case ATTR_RESTRICTED:
2239             typelib->typelib_header.flags |= 0x01; /* LIBFLAG_FRESTRICTED */
2240             break;
2241         default:
2242             break;
2243         }
2244     }
2245     return;
2246 }
2247
2248 static int ctl2_write_chunk(int fd, void *segment, int length)
2249 {
2250     if (write(fd, segment, length) != length) {
2251         close(fd);
2252         return 0;
2253     }
2254     return -1;
2255 }
2256
2257 static int ctl2_write_segment(msft_typelib_t *typelib, int fd, int segment)
2258 {
2259     if (write(fd, typelib->typelib_segment_data[segment], typelib->typelib_segdir[segment].length)
2260         != typelib->typelib_segdir[segment].length) {
2261         close(fd);
2262         return 0;
2263     }
2264
2265     return -1;
2266 }
2267
2268 static void ctl2_finalize_typeinfos(msft_typelib_t *typelib, int filesize)
2269 {
2270     msft_typeinfo_t *typeinfo;
2271
2272     for (typeinfo = typelib->typeinfos; typeinfo; typeinfo = typeinfo->next_typeinfo) {
2273         typeinfo->typeinfo->memoffset = filesize;
2274         if (typeinfo->func_data)
2275             filesize += typeinfo->func_data[0] + ((typeinfo->typeinfo->cElement & 0xffff) * 12);
2276         if (typeinfo->var_data)
2277             filesize += typeinfo->var_data[0] + (((typeinfo->typeinfo->cElement >> 16) & 0xffff) * 12);
2278         if (typeinfo->func_data || typeinfo->var_data)
2279             filesize += 4;
2280     }
2281 }
2282
2283 static int ctl2_finalize_segment(msft_typelib_t *typelib, int filepos, int segment)
2284 {
2285     if (typelib->typelib_segdir[segment].length) {
2286         typelib->typelib_segdir[segment].offset = filepos;
2287     } else {
2288         typelib->typelib_segdir[segment].offset = -1;
2289     }
2290
2291     return typelib->typelib_segdir[segment].length;
2292 }
2293
2294
2295 static void ctl2_write_typeinfos(msft_typelib_t *typelib, int fd)
2296 {
2297     msft_typeinfo_t *typeinfo;
2298     int typedata_size;
2299
2300     for (typeinfo = typelib->typeinfos; typeinfo; typeinfo = typeinfo->next_typeinfo) {
2301         if (!typeinfo->func_data && !typeinfo->var_data) continue;
2302         typedata_size = 0;
2303         if (typeinfo->func_data)
2304             typedata_size = typeinfo->func_data[0];
2305         if (typeinfo->var_data)
2306             typedata_size += typeinfo->var_data[0];
2307         ctl2_write_chunk(fd, &typedata_size, sizeof(int));
2308         if (typeinfo->func_data)
2309             ctl2_write_chunk(fd, typeinfo->func_data + 1, typeinfo->func_data[0]);
2310         if (typeinfo->var_data)
2311             ctl2_write_chunk(fd, typeinfo->var_data + 1, typeinfo->var_data[0]);
2312         if (typeinfo->func_indices)
2313             ctl2_write_chunk(fd, typeinfo->func_indices, (typeinfo->typeinfo->cElement & 0xffff) * 4);
2314         if (typeinfo->var_indices)
2315             ctl2_write_chunk(fd, typeinfo->var_indices, (typeinfo->typeinfo->cElement >> 16) * 4);
2316         if (typeinfo->func_names)
2317             ctl2_write_chunk(fd, typeinfo->func_names,   (typeinfo->typeinfo->cElement & 0xffff) * 4);
2318         if (typeinfo->var_names)
2319             ctl2_write_chunk(fd, typeinfo->var_names,   (typeinfo->typeinfo->cElement >> 16) * 4); 
2320         if (typeinfo->func_offsets)
2321             ctl2_write_chunk(fd, typeinfo->func_offsets, (typeinfo->typeinfo->cElement & 0xffff) * 4);
2322         if (typeinfo->var_offsets) {
2323             int add = 0, i, offset;
2324             if(typeinfo->func_data)
2325                 add = typeinfo->func_data[0];
2326             for(i = 0; i < (typeinfo->typeinfo->cElement >> 16); i++) {
2327                 offset = typeinfo->var_offsets[i];
2328                 offset += add;
2329                 ctl2_write_chunk(fd, &offset, 4);
2330             }
2331         }
2332     }
2333 }
2334
2335 static int save_all_changes(msft_typelib_t *typelib)
2336 {
2337     int retval;
2338     int filepos;
2339     int fd;
2340
2341     chat("save_all_changes(%p)\n", typelib);
2342
2343     retval = TYPE_E_IOERROR;
2344
2345     fd = creat(typelib->typelib->filename, 0666);
2346     if (fd == -1) return retval;
2347
2348     filepos = sizeof(MSFT_Header) + sizeof(MSFT_SegDir);
2349     if(typelib->typelib_header.varflags & 0x100) filepos += 4; /* helpstringdll */
2350     filepos += typelib->typelib_header.nrtypeinfos * 4;
2351
2352     filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_TYPEINFO);
2353     filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_GUIDHASH);
2354     filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_GUID);
2355     filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_IMPORTINFO);
2356     filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_IMPORTFILES);
2357     filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_REFERENCES);
2358     filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_NAMEHASH);
2359     filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_NAME);
2360     filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_STRING);
2361     filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_TYPEDESC);
2362     filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_ARRAYDESC);
2363     filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_CUSTDATA);
2364     filepos += ctl2_finalize_segment(typelib, filepos, MSFT_SEG_CUSTDATAGUID);
2365
2366     ctl2_finalize_typeinfos(typelib, filepos);
2367
2368     if (!ctl2_write_chunk(fd, &typelib->typelib_header, sizeof(typelib->typelib_header))) return retval;
2369     if(typelib->typelib_header.varflags & 0x100)
2370         if (!ctl2_write_chunk(fd, &typelib->help_string_dll_offset, sizeof(typelib->help_string_dll_offset)))
2371             return retval;
2372
2373     if (!ctl2_write_chunk(fd, typelib->typelib_typeinfo_offsets, typelib->typelib_header.nrtypeinfos * 4)) return retval;
2374     if (!ctl2_write_chunk(fd, &typelib->typelib_segdir, sizeof(typelib->typelib_segdir))) return retval;
2375     if (!ctl2_write_segment(typelib, fd, MSFT_SEG_TYPEINFO    )) return retval;
2376     if (!ctl2_write_segment(typelib, fd, MSFT_SEG_GUIDHASH    )) return retval;
2377     if (!ctl2_write_segment(typelib, fd, MSFT_SEG_GUID        )) return retval;
2378     if (!ctl2_write_segment(typelib, fd, MSFT_SEG_IMPORTINFO  )) return retval;
2379     if (!ctl2_write_segment(typelib, fd, MSFT_SEG_IMPORTFILES )) return retval;
2380     if (!ctl2_write_segment(typelib, fd, MSFT_SEG_REFERENCES  )) return retval;
2381     if (!ctl2_write_segment(typelib, fd, MSFT_SEG_NAMEHASH    )) return retval;
2382     if (!ctl2_write_segment(typelib, fd, MSFT_SEG_NAME        )) return retval;
2383     if (!ctl2_write_segment(typelib, fd, MSFT_SEG_STRING      )) return retval;
2384     if (!ctl2_write_segment(typelib, fd, MSFT_SEG_TYPEDESC    )) return retval;
2385     if (!ctl2_write_segment(typelib, fd, MSFT_SEG_ARRAYDESC   )) return retval;
2386     if (!ctl2_write_segment(typelib, fd, MSFT_SEG_CUSTDATA    )) return retval;
2387     if (!ctl2_write_segment(typelib, fd, MSFT_SEG_CUSTDATAGUID)) return retval;
2388
2389     ctl2_write_typeinfos(typelib, fd);
2390
2391     if (close(fd) == -1) return retval;
2392
2393     retval = S_OK;
2394     return retval;
2395 }
2396
2397 int create_msft_typelib(typelib_t *typelib)
2398 {
2399     msft_typelib_t *msft;
2400     int failed = 0;
2401     typelib_entry_t *entry;
2402     time_t cur_time;
2403     unsigned int version = 5 << 24 | 1 << 16 | 164; /* 5.01.0164 */
2404     GUID midl_time_guid    = {0xde77ba63,0x517c,0x11d1,{0xa2,0xda,0x00,0x00,0xf8,0x77,0x3c,0xe9}}; 
2405     GUID midl_version_guid = {0xde77ba64,0x517c,0x11d1,{0xa2,0xda,0x00,0x00,0xf8,0x77,0x3c,0xe9}}; 
2406
2407     msft = malloc(sizeof(*msft));
2408     if (!msft) return 0;
2409     memset(msft, 0, sizeof(*msft));
2410     msft->typelib = typelib;
2411
2412     ctl2_init_header(msft);
2413     ctl2_init_segdir(msft);
2414
2415     msft->typelib_header.varflags |= SYS_WIN32;
2416
2417     /*
2418      * The following two calls return an offset or -1 if out of memory. We
2419      * specifically need an offset of 0, however, so...
2420      */
2421     if (ctl2_alloc_segment(msft, MSFT_SEG_GUIDHASH, 0x80, 0x80)) { failed = 1; }
2422     if (ctl2_alloc_segment(msft, MSFT_SEG_NAMEHASH, 0x200, 0x200)) { failed = 1; }
2423
2424     if(failed) return 0;
2425
2426     msft->typelib_guidhash_segment = (int *)msft->typelib_segment_data[MSFT_SEG_GUIDHASH];
2427     msft->typelib_namehash_segment = (int *)msft->typelib_segment_data[MSFT_SEG_NAMEHASH];
2428
2429     memset(msft->typelib_guidhash_segment, 0xff, 0x80);
2430     memset(msft->typelib_namehash_segment, 0xff, 0x200);
2431
2432     set_lib_flags(msft);
2433     set_lcid(msft);
2434     set_help_file_name(msft);
2435     set_doc_string(msft);
2436     set_guid(msft);
2437     set_version(msft);
2438     set_name(msft);
2439     set_help_context(msft);
2440     set_help_string_dll(msft);
2441     set_help_string_context(msft);
2442     
2443     /* midl adds two sets of custom data to the library: the current unix time
2444        and midl's version number */
2445     cur_time = time(NULL);
2446     set_custdata(msft, &midl_time_guid, VT_UI4, &cur_time, &msft->typelib_header.CustomDataOffset);
2447     set_custdata(msft, &midl_version_guid, VT_UI4, &version, &msft->typelib_header.CustomDataOffset);
2448
2449     for(entry = typelib->entry; entry && NEXT_LINK(entry); entry = NEXT_LINK(entry))
2450         ;
2451
2452     for( ; entry; entry = PREV_LINK(entry))
2453         add_entry(msft, entry);
2454
2455     save_all_changes(msft);
2456     return 1;
2457 }