Fix memory leak in error path.
[wine] / tools / wrc / newstruc.c
1 /*
2  * Create dynamic new structures of various types
3  * and some utils in that trend.
4  *
5  * Copyright 1998 Bertho A. Stultiens
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 #include "config.h"
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <assert.h>
28 #include <ctype.h>
29
30 #include "wrc.h"
31 #include "newstruc.h"
32 #include "utils.h"
33 #include "parser.h"
34
35 #include "wingdi.h"     /* for BITMAPINFOHEADER */
36
37 #include <pshpack2.h>
38 typedef struct
39 {
40     DWORD biSize;
41     WORD  biWidth;
42     WORD  biHeight;
43     WORD  biPlanes;
44     WORD  biBitCount;
45 } BITMAPOS2HEADER;
46 #include <poppack.h>
47
48 /* Generate new_* functions that have no parameters (NOTE: no ';') */
49 __NEW_STRUCT_FUNC(dialog)
50 __NEW_STRUCT_FUNC(dialogex)
51 __NEW_STRUCT_FUNC(name_id)
52 __NEW_STRUCT_FUNC(menu)
53 __NEW_STRUCT_FUNC(menuex)
54 __NEW_STRUCT_FUNC(menu_item)
55 __NEW_STRUCT_FUNC(menuex_item)
56 __NEW_STRUCT_FUNC(control)
57 __NEW_STRUCT_FUNC(icon)
58 __NEW_STRUCT_FUNC(cursor)
59 __NEW_STRUCT_FUNC(versioninfo)
60 __NEW_STRUCT_FUNC(ver_value)
61 __NEW_STRUCT_FUNC(ver_block)
62 __NEW_STRUCT_FUNC(stt_entry)
63 __NEW_STRUCT_FUNC(accelerator)
64 __NEW_STRUCT_FUNC(event)
65 __NEW_STRUCT_FUNC(raw_data)
66 __NEW_STRUCT_FUNC(lvc)
67 __NEW_STRUCT_FUNC(res_count)
68 __NEW_STRUCT_FUNC(string)
69 __NEW_STRUCT_FUNC(toolbar_item)
70 __NEW_STRUCT_FUNC(ani_any)
71
72 /* New instances for all types of structures */
73 /* Very inefficient (in size), but very functional :-]
74  * Especially for type-checking.
75  */
76 resource_t *new_resource(enum res_e t, void *res, int memopt, language_t *lan)
77 {
78         resource_t *r = (resource_t *)xmalloc(sizeof(resource_t));
79         r->type = t;
80         r->res.overlay = res;
81         r->memopt = memopt;
82         r->lan = lan;
83         return r;
84 }
85
86 version_t *new_version(DWORD v)
87 {
88         version_t *vp = (version_t *)xmalloc(sizeof(version_t));
89         *vp = v;
90         return vp;
91 }
92
93 characts_t *new_characts(DWORD c)
94 {
95         characts_t *cp = (characts_t *)xmalloc(sizeof(characts_t));
96         *cp = c;
97         return cp;
98 }
99
100 language_t *new_language(int id, int sub)
101 {
102         language_t *lan = (language_t *)xmalloc(sizeof(language_t));
103         lan->id = id;
104         lan->sub = sub;
105         return lan;
106 }
107
108 language_t *dup_language(language_t *l)
109 {
110         if(!l) return NULL;
111         return new_language(l->id, l->sub);
112 }
113
114 version_t *dup_version(version_t *v)
115 {
116         if(!v) return NULL;
117         return new_version(*v);
118 }
119
120 characts_t *dup_characts(characts_t *c)
121 {
122         if(!c) return NULL;
123         return new_characts(*c);
124 }
125
126 rcdata_t *new_rcdata(raw_data_t *rd, int *memopt)
127 {
128         rcdata_t *rc = (rcdata_t *)xmalloc(sizeof(rcdata_t));
129         rc->data = rd;
130         if(memopt)
131         {
132                 rc->memopt = *memopt;
133                 free(memopt);
134         }
135         else
136                 rc->memopt = WRC_MO_MOVEABLE | WRC_MO_PURE;
137         return rc;
138 }
139
140 font_id_t *new_font_id(int size, string_t *face, int weight, int italic)
141 {
142         font_id_t *fid = (font_id_t *)xmalloc(sizeof(font_id_t));
143         fid->name = face;
144         fid->size = size;
145         fid->weight = weight;
146         fid->italic = italic;
147         return fid;
148 }
149
150 user_t *new_user(name_id_t *type, raw_data_t *rd, int *memopt)
151 {
152         user_t *usr = (user_t *)xmalloc(sizeof(user_t));
153         usr->data = rd;
154         if(memopt)
155         {
156                 usr->memopt = *memopt;
157                 free(memopt);
158         }
159         else
160                 usr->memopt = WRC_MO_MOVEABLE | WRC_MO_PURE;
161         usr->type = type;
162         return usr;
163 }
164
165 font_t *new_font(raw_data_t *rd, int *memopt)
166 {
167         font_t *fnt = (font_t *)xmalloc(sizeof(font_t));
168         fnt->data = rd;
169         if(memopt)
170         {
171                 fnt->memopt = *memopt;
172                 free(memopt);
173         }
174         else
175                 fnt->memopt = WRC_MO_MOVEABLE | WRC_MO_DISCARDABLE;
176         return fnt;
177 }
178
179 fontdir_t *new_fontdir(raw_data_t *rd, int *memopt)
180 {
181         fontdir_t *fnd = (fontdir_t *)xmalloc(sizeof(fontdir_t));
182         fnd->data = rd;
183         if(memopt)
184         {
185                 fnd->memopt = *memopt;
186                 free(memopt);
187         }
188         else
189                 fnd->memopt = WRC_MO_MOVEABLE | WRC_MO_DISCARDABLE;
190         return fnd;
191 }
192
193
194 /*
195  * Convert bitmaps to proper endian
196  */
197 static void convert_bitmap_swap_v3(BITMAPINFOHEADER *bih)
198 {
199         bih->biSize             = BYTESWAP_DWORD(bih->biSize);
200         bih->biWidth            = BYTESWAP_DWORD(bih->biWidth);
201         bih->biHeight           = BYTESWAP_DWORD(bih->biHeight);
202         bih->biPlanes           = BYTESWAP_WORD(bih->biPlanes);
203         bih->biBitCount         = BYTESWAP_WORD(bih->biBitCount);
204         bih->biCompression      = BYTESWAP_DWORD(bih->biCompression);
205         bih->biSizeImage        = BYTESWAP_DWORD(bih->biSizeImage);
206         bih->biXPelsPerMeter    = BYTESWAP_DWORD(bih->biXPelsPerMeter);
207         bih->biYPelsPerMeter    = BYTESWAP_DWORD(bih->biYPelsPerMeter);
208         bih->biClrUsed          = BYTESWAP_DWORD(bih->biClrUsed);
209         bih->biClrImportant     = BYTESWAP_DWORD(bih->biClrImportant);
210 }
211
212 static void convert_bitmap_swap_v4(BITMAPV4HEADER *b4h)
213 {
214         convert_bitmap_swap_v3((BITMAPINFOHEADER *)b4h);
215         b4h->bV4RedMask         = BYTESWAP_DWORD(b4h->bV4RedMask);
216         b4h->bV4GreenMask       = BYTESWAP_DWORD(b4h->bV4GreenMask);
217         b4h->bV4BlueMask        = BYTESWAP_DWORD(b4h->bV4BlueMask);
218         b4h->bV4AlphaMask       = BYTESWAP_DWORD(b4h->bV4AlphaMask);
219         b4h->bV4CSType          = BYTESWAP_DWORD(b4h->bV4CSType);
220         b4h->bV4Endpoints.ciexyzRed.ciexyzX     = BYTESWAP_DWORD(b4h->bV4Endpoints.ciexyzRed.ciexyzX);
221         b4h->bV4Endpoints.ciexyzRed.ciexyzY     = BYTESWAP_DWORD(b4h->bV4Endpoints.ciexyzRed.ciexyzY);
222         b4h->bV4Endpoints.ciexyzRed.ciexyzZ     = BYTESWAP_DWORD(b4h->bV4Endpoints.ciexyzRed.ciexyzZ);
223         b4h->bV4Endpoints.ciexyzGreen.ciexyzX   = BYTESWAP_DWORD(b4h->bV4Endpoints.ciexyzGreen.ciexyzX);
224         b4h->bV4Endpoints.ciexyzGreen.ciexyzY   = BYTESWAP_DWORD(b4h->bV4Endpoints.ciexyzGreen.ciexyzY);
225         b4h->bV4Endpoints.ciexyzGreen.ciexyzZ   = BYTESWAP_DWORD(b4h->bV4Endpoints.ciexyzGreen.ciexyzZ);
226         b4h->bV4Endpoints.ciexyzBlue.ciexyzX    = BYTESWAP_DWORD(b4h->bV4Endpoints.ciexyzBlue.ciexyzX);
227         b4h->bV4Endpoints.ciexyzBlue.ciexyzY    = BYTESWAP_DWORD(b4h->bV4Endpoints.ciexyzBlue.ciexyzY);
228         b4h->bV4Endpoints.ciexyzBlue.ciexyzZ    = BYTESWAP_DWORD(b4h->bV4Endpoints.ciexyzBlue.ciexyzZ);
229         b4h->bV4GammaRed        = BYTESWAP_DWORD(b4h->bV4GammaRed);
230         b4h->bV4GammaGreen      = BYTESWAP_DWORD(b4h->bV4GammaGreen);
231         b4h->bV4GammaBlue       = BYTESWAP_DWORD(b4h->bV4GammaBlue);
232 }
233
234 static void convert_bitmap_swap_os2(BITMAPOS2HEADER *boh)
235 {
236         boh->biSize             = BYTESWAP_DWORD(boh->biSize);
237         boh->biWidth            = BYTESWAP_WORD(boh->biWidth);
238         boh->biHeight           = BYTESWAP_WORD(boh->biHeight);
239         boh->biPlanes           = BYTESWAP_WORD(boh->biPlanes);
240         boh->biBitCount         = BYTESWAP_WORD(boh->biBitCount);
241 }
242
243 #define FL_SIGBE        0x01
244 #define FL_SIZEBE       0x02
245 #define FL_V4           0x04
246 #define FL_OS2          0x08
247 static int convert_bitmap(char *data, int size)
248 {
249         BITMAPINFOHEADER *bih = (BITMAPINFOHEADER *)data;
250         BITMAPV4HEADER *b4h = (BITMAPV4HEADER *)data;
251         BITMAPOS2HEADER *boh = (BITMAPOS2HEADER *)data;
252         int type = 0;
253         int returnSize = 0;           /* size to be returned */
254 #ifdef WORDS_BIGENDIAN
255         DWORD bisizel = BYTESWAP_DWORD(sizeof(BITMAPINFOHEADER));
256         DWORD b4sizel = BYTESWAP_DWORD(sizeof(BITMAPV4HEADER));
257         DWORD bosizel = BYTESWAP_DWORD(sizeof(BITMAPOS2HEADER));
258         DWORD bisizeb = sizeof(BITMAPINFOHEADER);
259         DWORD b4sizeb = sizeof(BITMAPV4HEADER);
260         DWORD bosizeb = sizeof(BITMAPOS2HEADER);
261 #else
262         DWORD bisizel = sizeof(BITMAPINFOHEADER);
263         DWORD b4sizel = sizeof(BITMAPV4HEADER);
264         DWORD bosizel = sizeof(BITMAPOS2HEADER);
265         DWORD bisizeb = BYTESWAP_DWORD(sizeof(BITMAPINFOHEADER));
266         DWORD b4sizeb = BYTESWAP_DWORD(sizeof(BITMAPV4HEADER));
267         DWORD bosizeb = BYTESWAP_DWORD(sizeof(BITMAPOS2HEADER));
268 #endif
269
270
271     /*
272      * Originally the bih and b4h pointers were simply incremented here,
273      * and memmoved at the end of the function.  This causes alignment
274      * issues on solaris, so we do the memmove here rather than at the end.
275      */
276         if(data[0] == 'B' && data[1] == 'M')
277         {
278                 /* Little endian signature */
279          memmove(data, data+sizeof(BITMAPFILEHEADER), size - sizeof(BITMAPFILEHEADER));
280          returnSize = sizeof(BITMAPFILEHEADER);
281         }
282         else if(data[0] == 'M' && data[1] == 'B')
283         {
284                 type |= FL_SIGBE;       /* Big endian signature */
285          memmove(data, data+sizeof(BITMAPFILEHEADER), size - sizeof(BITMAPFILEHEADER));
286          returnSize = sizeof(BITMAPFILEHEADER);
287
288         }
289
290         if(bih->biSize == bisizel)
291         {
292                 /* Little endian */
293         }
294         else if(bih->biSize == bisizeb)
295         {
296                 type |= FL_SIZEBE;
297         }
298         else if(bih->biSize == b4sizel)
299         {
300                 type |= FL_V4;
301         }
302         else if(bih->biSize == b4sizeb)
303         {
304                 type |= FL_SIZEBE | FL_V4;
305         }
306         else if(!bih->biSize || bih->biSize == bosizel)
307         {
308                 type |= FL_OS2;
309         }
310         else if(bih->biSize == bosizeb)
311         {
312                 type |= FL_SIZEBE | FL_OS2;
313         }
314         else
315                 yyerror("Invalid bitmap format, bih->biSize = %ld", bih->biSize);
316
317         switch(type)
318         {
319         default:
320                 break;
321         case FL_SIZEBE:
322         case FL_SIZEBE | FL_V4:
323         case FL_SIZEBE | FL_OS2:
324                 yywarning("Bitmap v%c signature little-endian, but size big-endian", type & FL_V4 ? '4' : '3');
325                 break;
326         case FL_SIGBE:
327         case FL_SIGBE | FL_V4:
328         case FL_SIGBE | FL_OS2:
329                 yywarning("Bitmap v%c signature big-endian, but size little-endian", type & FL_V4 ? '4' : '3');
330                 break;
331         }
332
333         switch(byteorder)
334         {
335 #ifdef WORDS_BIGENDIAN
336         default:
337 #endif
338         case WRC_BO_BIG:
339                 if(!(type & FL_SIZEBE))
340                 {
341                         if(type & FL_V4)
342                                 convert_bitmap_swap_v4(b4h);
343                         else if(type & FL_OS2)
344                         {
345                                 convert_bitmap_swap_os2(boh);
346                         }
347                         else
348                                 convert_bitmap_swap_v3(bih);
349                 }
350                 break;
351 #ifndef WORDS_BIGENDIAN
352         default:
353 #endif
354         case WRC_BO_LITTLE:
355                 if(type & FL_SIZEBE)
356                 {
357                         if(type & FL_V4)
358                                 convert_bitmap_swap_v4(b4h);
359                         else if(type & FL_OS2)
360                         {
361                                 convert_bitmap_swap_os2(boh);
362                         }
363                         else
364                                 convert_bitmap_swap_v3(bih);
365                 }
366                 break;
367         }
368
369         if(size && (void *)data != (void *)bih)
370         {
371                 /* We have the fileheader still attached, remove it */
372                 memmove(data, data+sizeof(BITMAPFILEHEADER), size - sizeof(BITMAPFILEHEADER));
373                 return sizeof(BITMAPFILEHEADER);
374         }
375     return returnSize;
376 }
377 #undef FL_SIGBE
378 #undef FL_SIZEBE
379 #undef FL_V4
380
381 /*
382  * Cursor and icon splitter functions used when allocating
383  * cursor- and icon-groups.
384  */
385 typedef struct {
386         language_t      lan;
387         int             id;
388 } id_alloc_t;
389
390 static int get_new_id(id_alloc_t **list, int *n, language_t *lan)
391 {
392         int i;
393         assert(lan != NULL);
394         assert(list != NULL);
395         assert(n != NULL);
396
397         if(!*list)
398         {
399                 *list = (id_alloc_t *)xmalloc(sizeof(id_alloc_t));
400                 *n = 1;
401                 (*list)[0].lan = *lan;
402                 (*list)[0].id = 1;
403                 return 1;
404         }
405
406         for(i = 0; i < *n; i++)
407         {
408                 if((*list)[i].lan.id == lan->id && (*list)[i].lan.sub == lan->sub)
409                         return ++((*list)[i].id);
410         }
411
412         *list = (id_alloc_t *)xrealloc(*list, sizeof(id_alloc_t) * (*n+1));
413         (*list)[*n].lan = *lan;
414         (*list)[*n].id = 1;
415         *n += 1;
416         return 1;
417 }
418
419 static int alloc_icon_id(language_t *lan)
420 {
421         static id_alloc_t *idlist = NULL;
422         static int nid = 0;
423
424         return get_new_id(&idlist, &nid, lan);
425 }
426
427 static int alloc_cursor_id(language_t *lan)
428 {
429         static id_alloc_t *idlist = NULL;
430         static int nid = 0;
431
432         return get_new_id(&idlist, &nid, lan);
433 }
434
435 static void split_icons(raw_data_t *rd, icon_group_t *icog, int *nico)
436 {
437         int cnt;
438         int i;
439         icon_t *ico;
440         icon_t *list = NULL;
441         icon_header_t *ih = (icon_header_t *)rd->data;
442         int swap = 0;
443
444         if(ih->type == 1)
445                 swap = 0;
446         else if(BYTESWAP_WORD(ih->type) == 1)
447                 swap = 1;
448         else
449                 yyerror("Icon resource data has invalid type id %d", ih->type);
450
451         cnt = swap ? BYTESWAP_WORD(ih->count) : ih->count;
452         for(i = 0; i < cnt; i++)
453         {
454                 icon_dir_entry_t ide;
455                 BITMAPINFOHEADER info;
456                 memcpy(&ide, rd->data + sizeof(icon_header_t)
457                                       + i*sizeof(icon_dir_entry_t), sizeof(ide));
458
459                 ico = new_icon();
460                 ico->id = alloc_icon_id(icog->lvc.language);
461                 ico->lvc = icog->lvc;
462                 if(swap)
463                 {
464                         ide.offset = BYTESWAP_DWORD(ide.offset);
465                         ide.ressize= BYTESWAP_DWORD(ide.ressize);
466                 }
467                 if(ide.offset > rd->size
468                 || ide.offset + ide.ressize > rd->size)
469                         yyerror("Icon resource data corrupt");
470                 ico->width = ide.width;
471                 ico->height = ide.height;
472                 ico->nclr = ide.nclr;
473                 ico->planes = swap ? BYTESWAP_WORD(ide.planes) : ide.planes;
474                 ico->bits = swap ? BYTESWAP_WORD(ide.bits) : ide.bits;
475                 memcpy(&info, rd->data + ide.offset, sizeof(info));
476          convert_bitmap((char *) &info, 0);
477          memcpy(rd->data + ide.offset, &info, sizeof(info));
478
479                 if(!ico->planes)
480                 {
481                         /* Argh! They did not fill out the resdir structure */
482                         /* The bitmap is in destination byteorder. We want native for our structures */
483                         switch(byteorder)
484                         {
485 #ifdef WORDS_BIGENDIAN
486                         case WRC_BO_LITTLE:
487 #else
488                         case WRC_BO_BIG:
489 #endif
490                                 ico->planes = BYTESWAP_WORD(info.biPlanes);
491                                 break;
492                         default:
493                                 ico->planes = info.biPlanes;
494                         }
495                 }
496                 if(!ico->bits)
497                 {
498                         /* Argh! They did not fill out the resdir structure */
499                         /* The bitmap is in destination byteorder. We want native for our structures */
500                         switch(byteorder)
501                         {
502 #ifdef WORDS_BIGENDIAN
503                         case WRC_BO_LITTLE:
504 #else
505                         case WRC_BO_BIG:
506 #endif
507                                 ico->bits = BYTESWAP_WORD(info.biBitCount);
508                                 break;
509                         default:
510                                 ico->bits = info.biBitCount;
511                         }
512                 }
513                 ico->data = new_raw_data();
514                 copy_raw_data(ico->data, rd, ide.offset, ide.ressize);
515                 if(!list)
516                 {
517                         list = ico;
518                 }
519                 else
520                 {
521                         ico->next = list;
522                         list->prev = ico;
523                         list = ico;
524                 }
525         }
526         icog->iconlist = list;
527         *nico = cnt;
528 }
529
530 static void split_cursors(raw_data_t *rd, cursor_group_t *curg, int *ncur)
531 {
532         int cnt;
533         int i;
534         cursor_t *cur;
535         cursor_t *list = NULL;
536         cursor_header_t *ch = (cursor_header_t *)rd->data;
537         int swap = 0;
538
539         if(ch->type == 2)
540                 swap = 0;
541         else if(BYTESWAP_WORD(ch->type) == 2)
542                 swap = 1;
543         else
544                 yyerror("Cursor resource data has invalid type id %d", ch->type);
545         cnt = swap ? BYTESWAP_WORD(ch->count) : ch->count;
546         for(i = 0; i < cnt; i++)
547         {
548                 cursor_dir_entry_t cde;
549                 BITMAPINFOHEADER info;
550                 memcpy(&cde, rd->data + sizeof(cursor_header_t)
551                                       + i*sizeof(cursor_dir_entry_t), sizeof(cde));
552
553                 cur = new_cursor();
554                 cur->id = alloc_cursor_id(curg->lvc.language);
555                 cur->lvc = curg->lvc;
556                 if(swap)
557                 {
558                         cde.offset = BYTESWAP_DWORD(cde.offset);
559                         cde.ressize= BYTESWAP_DWORD(cde.ressize);
560                 }
561                 if(cde.offset > rd->size
562                 || cde.offset + cde.ressize > rd->size)
563                         yyerror("Cursor resource data corrupt");
564                 cur->width = cde.width;
565                 cur->height = cde.height;
566                 cur->nclr = cde.nclr;
567                 memcpy(&info, rd->data + cde.offset, sizeof(info));
568          convert_bitmap((char *)&info, 0);
569          memcpy(rd->data + cde.offset, &info, sizeof(info));
570                 /* The bitmap is in destination byteorder. We want native for our structures */
571                 switch(byteorder)
572                 {
573 #ifdef WORDS_BIGENDIAN
574                 case WRC_BO_LITTLE:
575 #else
576                 case WRC_BO_BIG:
577 #endif
578                         cur->planes = BYTESWAP_WORD(info.biPlanes);
579                         cur->bits = BYTESWAP_WORD(info.biBitCount);
580                         break;
581                 default:
582                         cur->planes = info.biPlanes;
583                         cur->bits = info.biBitCount;
584                 }
585                 if(!win32 && (cur->planes != 1 || cur->bits != 1))
586                         yywarning("Win16 cursor contains colors");
587                 cur->xhot = swap ? BYTESWAP_WORD(cde.xhot) : cde.xhot;
588                 cur->yhot = swap ? BYTESWAP_WORD(cde.yhot) : cde.yhot;
589                 cur->data = new_raw_data();
590                 copy_raw_data(cur->data, rd, cde.offset, cde.ressize);
591                 if(!list)
592                 {
593                         list = cur;
594                 }
595                 else
596                 {
597                         cur->next = list;
598                         list->prev = cur;
599                         list = cur;
600                 }
601         }
602         curg->cursorlist = list;
603         *ncur = cnt;
604 }
605
606
607 icon_group_t *new_icon_group(raw_data_t *rd, int *memopt)
608 {
609         icon_group_t *icog = (icon_group_t *)xmalloc(sizeof(icon_group_t));
610         if(memopt)
611         {
612                 icog->memopt = *memopt;
613                 free(memopt);
614         }
615         else
616                 icog->memopt = WRC_MO_MOVEABLE | WRC_MO_PURE | WRC_MO_DISCARDABLE;
617         icog->lvc = rd->lvc;
618         split_icons(rd, icog, &(icog->nicon));
619         free(rd->data);
620         free(rd);
621         return icog;
622 }
623
624 cursor_group_t *new_cursor_group(raw_data_t *rd, int *memopt)
625 {
626         cursor_group_t *curg = (cursor_group_t *)xmalloc(sizeof(cursor_group_t));
627         if(memopt)
628         {
629                 curg->memopt = *memopt;
630                 free(memopt);
631         }
632         else
633                 curg->memopt = WRC_MO_MOVEABLE | WRC_MO_PURE | WRC_MO_DISCARDABLE;
634         curg->lvc = rd->lvc;
635         split_cursors(rd, curg, &(curg->ncursor));
636         free(rd->data);
637         free(rd);
638         return curg;
639 }
640
641 /*
642  * Animated cursors and icons
643  *
644  * The format of animated cursors and icons is yet another example
645  * of bad design by "The Company". The entire RIFF structure is
646  * flawed by design because it is inconsistent and single minded:
647  * - some tags have lengths attached, others don't. The use of these
648  *   non-length tags is absolutely unclear;
649  * - the content of "icon" tags can be both icons and cursors;
650  * - tags lack proper alignment constraints. It seems that everything
651  *   is 16bit aligned, but I could not find that in any docu. Just be
652  *   prepared to eat anything;
653  * - there are no strict constraints on tag-nesting and the organization
654  *   is highly illogical;
655  *
656  * Anyhow, here is the basic structure:
657  * "RIFF" { dword taglength }
658  *      "ACON"                                  // What does it do?
659  *      "LIST" { dword taglength }
660  *              "INFO"                          // And what does this do?
661  *              "INAM" { dword taglength }      // Icon/cursor name
662  *                      {inam data}
663  *              "IART" { dword taglength }      // The artist
664  *                      {iart data}
665  *              "fram"                          // Is followed by "icon"s
666  *              "icon" { dword taglength }      // First frame
667  *                      { icon/cursor data }
668  *              "icon" { dword taglength }      // Second frame
669  *                      { icon/cursor data }
670  *                      ...                     // ...
671  *      "anih" { dword taglength }              // Header structure
672  *              { aniheader_t structure }
673  *      "rate" { dword taglength }              // The rate for each frame
674  *              { `steps' dwords }
675  *      "seq " { dword taglength }              // The frame blit-order
676  *              { `steps' dwords }
677  *
678  * Tag length are bytelength without the header and length field (i.e. -8).
679  * The "LIST" tag may occur several times and may encapsulate different
680  * tags. The `steps' is the number of "icon" tags found (actually the
681  * number of steps specified in the aniheader_t structure). The "seq "uence
682  * tag can be omitted, in which case the sequence is equal to the sequence
683  * of "icon"s found in the file. Also "rate" may be omitted, in which case
684  * the default from the aniheader_t structure is used.
685  *
686  * An animated cursor puts `.cur' formatted files into each "icon" tag,
687  * whereas animated icons contain `.ico' formatted files.
688  *
689  * Note about the code: Yes, it can be shorter/compressed. Some tags can be
690  * dealt with in the same code. However, this version shows what is going on
691  * and is better debug-able.
692  */
693 static const char riff[4] = "RIFF";
694 static const char acon[4] = "ACON";
695 static const char list[4] = "LIST";
696 static const char info[4] = "INFO";
697 static const char inam[4] = "INAM";
698 static const char iart[4] = "IART";
699 static const char fram[4] = "fram";
700 static const char icon[4] = "icon";
701 static const char anih[4] = "anih";
702 static const char rate[4] = "rate";
703 static const char seq[4]  = "seq ";
704
705 #define SKIP_TAG(p,size)        ((riff_tag_t *)(((char *)p) + (size)))
706
707 #define NEXT_TAG(p)     SKIP_TAG(p,(isswapped ? BYTESWAP_DWORD(p->size) : p->size) + sizeof(*p))
708
709 static void handle_ani_icon(riff_tag_t *rtp, enum res_e type, int isswapped)
710 {
711         cursor_dir_entry_t *cdp;
712         cursor_header_t *chp;
713         int count;
714         int ctype;
715         int i;
716         static int once = 0;    /* This will trigger only once per file! */
717         const char *anistr = type == res_aniico ? "icon" : "cursor";
718         /* Notes:
719          * Both cursor and icon directories are similar
720          * Both cursor and icon headers are similar
721          */
722
723         chp = (cursor_header_t *)(rtp+1);
724         cdp = (cursor_dir_entry_t *)(chp+1);
725         count = isswapped ? BYTESWAP_WORD(chp->count) : chp->count;
726         ctype = isswapped ? BYTESWAP_WORD(chp->type) : chp->type;
727         chp->reserved   = BYTESWAP_WORD(chp->reserved);
728         chp->type       = BYTESWAP_WORD(chp->type);
729         chp->count      = BYTESWAP_WORD(chp->count);
730
731         if(type == res_anicur && ctype != 2 && !once)
732         {
733                 yywarning("Animated cursor contains invalid \"icon\" tag cursor-file (%d->%s)",
734                                 ctype,
735                                 ctype == 1 ? "icontype" : "?");
736                 once++;
737         }
738         else if(type == res_aniico && ctype != 1 && !once)
739         {
740                 yywarning("Animated icon contains invalid \"icon\" tag icon-file (%d->%s)",
741                                 ctype,
742                                 ctype == 2 ? "cursortype" : "?");
743                 once++;
744         }
745         else if(ctype != 1 && ctype != 2 && !once)
746         {
747                 yywarning("Animated %s contains invalid \"icon\" tag file-type (%d; neither icon nor cursor)", anistr, ctype);
748                 once++;
749         }
750
751         for(i = 0; i < count; i++)
752         {
753                 DWORD ofs = isswapped ? BYTESWAP_DWORD(cdp[i].offset) : cdp[i].offset;
754                 DWORD sze = isswapped ? BYTESWAP_DWORD(cdp[i].ressize) : cdp[i].ressize;
755                 if(ofs > rtp->size || ofs+sze > rtp->size)
756                         yyerror("Animated %s's data corrupt", anistr);
757                 convert_bitmap((char *)chp + ofs, 0);
758                 cdp[i].xhot     = BYTESWAP_WORD(cdp->xhot);
759                 cdp[i].yhot     = BYTESWAP_WORD(cdp->yhot);
760                 cdp[i].ressize  = BYTESWAP_DWORD(cdp->ressize);
761                 cdp[i].offset   = BYTESWAP_DWORD(cdp->offset);
762         }
763 }
764
765 static void handle_ani_list(riff_tag_t *lst, enum res_e type, int isswapped)
766 {
767         riff_tag_t *rtp = lst+1;        /* Skip the "LIST" tag */
768
769         while((char *)rtp < (char *)lst + lst->size + sizeof(*lst))
770         {
771                 if(!memcmp(rtp->tag, info, sizeof(info)))
772                 {
773                         rtp = SKIP_TAG(rtp,4);
774                 }
775                 else if(!memcmp(rtp->tag, inam, sizeof(inam)))
776                 {
777                         /* Ignore the icon/cursor name; its a string */
778                         rtp = NEXT_TAG(rtp);
779                 }
780                 else if(!memcmp(rtp->tag, iart, sizeof(iart)))
781                 {
782                         /* Ignore the author's name; its a string */
783                         rtp = NEXT_TAG(rtp);
784                 }
785                 else if(!memcmp(rtp->tag, fram, sizeof(fram)))
786                 {
787                         /* This should be followed by "icon"s, but we
788                          * simply ignore this because it is pure
789                          * non-information.
790                          */
791                         rtp = SKIP_TAG(rtp,4);
792                 }
793                 else if(!memcmp(rtp->tag, icon, sizeof(icon)))
794                 {
795                         handle_ani_icon(rtp, type, isswapped);
796                         rtp = NEXT_TAG(rtp);
797                 }
798                 else
799                         internal_error(__FILE__, __LINE__, "Unknown tag \"%c%c%c%c\" in RIFF file",
800                                        isprint(rtp->tag[0]) ? rtp->tag[0] : '.',
801                                        isprint(rtp->tag[1]) ? rtp->tag[1] : '.',
802                                        isprint(rtp->tag[2]) ? rtp->tag[2] : '.',
803                                        isprint(rtp->tag[3]) ? rtp->tag[3] : '.');
804
805                 /* FIXME: This relies in sizeof(DWORD) == sizeof(pointer_type) */
806                 if((DWORD)rtp & 1)
807                         rtp = SKIP_TAG(rtp,1);
808         }
809 }
810
811 ani_curico_t *new_ani_curico(enum res_e type, raw_data_t *rd, int *memopt)
812 {
813         ani_curico_t *ani = (ani_curico_t *)xmalloc(sizeof(ani_curico_t));
814         riff_tag_t *rtp;
815         int isswapped = 0;
816         int doswap;
817         const char *anistr = type == res_aniico ? "icon" : "cursor";
818
819         assert(!memcmp(rd->data, riff, sizeof(riff)));
820         assert(type == res_anicur || type == res_aniico);
821
822         rtp = (riff_tag_t *)rd->data;
823
824         if(BYTESWAP_DWORD(rtp->size) + 2*sizeof(DWORD) == rd->size)
825                 isswapped = 1;
826         else if(rtp->size + 2*sizeof(DWORD) == rd->size)
827                 isswapped = 0;
828         else
829                 yyerror("Animated %s has an invalid RIFF length", anistr);
830
831         switch(byteorder)
832         {
833 #ifdef WORDS_BIGENDIAN
834         case WRC_BO_LITTLE:
835 #else
836         case WRC_BO_BIG:
837 #endif
838                 doswap = !isswapped;
839                 break;
840         default:
841                 doswap = isswapped;
842         }
843
844         /*
845          * When to swap what:
846          * isswapped | doswap |
847          * ----------+--------+---------------------------------
848          *     0     |    0   | read native; don't convert
849          *     1     |    0   | read swapped size; don't convert
850          *     0     |    1   | read native; convert
851          *     1     |    1   | read swapped size; convert
852          * Reading swapped size if necessary to calculate in native
853          * format. E.g. a little-endian source on a big-endian
854          * processor.
855          */
856         if(doswap)
857         {
858                 /* We only go through the RIFF file if we need to swap
859                  * bytes in words/dwords. Else we couldn't care less
860                  * what the file contains. This is consistent with
861                  * MS' rc.exe, which doesn't complain at all, eventhough
862                  * the fileformat might not be entirely correct.
863                  */
864                 rtp++;  /* Skip the "RIFF" tag */
865
866                 while((char *)rtp < (char *)rd->data + rd->size)
867                 {
868                         if(!memcmp(rtp->tag, acon, sizeof(acon)))
869                         {
870                                 rtp = SKIP_TAG(rtp,4);
871                         }
872                         else if(!memcmp(rtp->tag, list, sizeof(list)))
873                         {
874                                 handle_ani_list(rtp, type, isswapped);
875                                 rtp = NEXT_TAG(rtp);
876                         }
877                         else if(!memcmp(rtp->tag, anih, sizeof(anih)))
878                         {
879                                 aniheader_t *ahp = (aniheader_t *)((char *)(rtp+1));
880                                 ahp->structsize = BYTESWAP_DWORD(ahp->structsize);
881                                 ahp->frames     = BYTESWAP_DWORD(ahp->frames);
882                                 ahp->steps      = BYTESWAP_DWORD(ahp->steps);
883                                 ahp->cx         = BYTESWAP_DWORD(ahp->cx);
884                                 ahp->cy         = BYTESWAP_DWORD(ahp->cy);
885                                 ahp->bitcount   = BYTESWAP_DWORD(ahp->bitcount);
886                                 ahp->planes     = BYTESWAP_DWORD(ahp->planes);
887                                 ahp->rate       = BYTESWAP_DWORD(ahp->rate);
888                                 ahp->flags      = BYTESWAP_DWORD(ahp->flags);
889                                 rtp = NEXT_TAG(rtp);
890                         }
891                         else if(!memcmp(rtp->tag, rate, sizeof(rate)))
892                         {
893                                 int cnt = rtp->size / sizeof(DWORD);
894                                 DWORD *dwp = (DWORD *)(rtp+1);
895                                 int i;
896                                 for(i = 0; i < cnt; i++)
897                                         dwp[i] = BYTESWAP_DWORD(dwp[i]);
898                                 rtp = NEXT_TAG(rtp);
899                         }
900                         else if(!memcmp(rtp->tag, seq, sizeof(seq)))
901                         {
902                                 int cnt = rtp->size / sizeof(DWORD);
903                                 DWORD *dwp = (DWORD *)(rtp+1);
904                                 int i;
905                                 for(i = 0; i < cnt; i++)
906                                         dwp[i] = BYTESWAP_DWORD(dwp[i]);
907                                 rtp = NEXT_TAG(rtp);
908                         }
909                         else
910                                 internal_error(__FILE__, __LINE__, "Unknown tag \"%c%c%c%c\" in RIFF file",
911                                        isprint(rtp->tag[0]) ? rtp->tag[0] : '.',
912                                        isprint(rtp->tag[1]) ? rtp->tag[1] : '.',
913                                        isprint(rtp->tag[2]) ? rtp->tag[2] : '.',
914                                        isprint(rtp->tag[3]) ? rtp->tag[3] : '.');
915
916                         /* FIXME: This relies in sizeof(DWORD) == sizeof(pointer_type) */
917                         if((DWORD)rtp & 1)
918                                 rtp = SKIP_TAG(rtp,1);
919                 }
920
921                 /* We must end correctly here */
922                 if((char *)rtp != (char *)rd->data + rd->size)
923                         yyerror("Animated %s contains invalid field size(s)", anistr);
924         }
925
926         ani->data = rd;
927         if(memopt)
928         {
929                 ani->memopt = *memopt;
930                 free(memopt);
931         }
932         else
933                 ani->memopt = WRC_MO_MOVEABLE | WRC_MO_DISCARDABLE;
934         return ani;
935 }
936 #undef NEXT_TAG
937
938 /* Bitmaps */
939 bitmap_t *new_bitmap(raw_data_t *rd, int *memopt)
940 {
941         bitmap_t *bmp = (bitmap_t *)xmalloc(sizeof(bitmap_t));
942
943         bmp->data = rd;
944         if(memopt)
945         {
946                 bmp->memopt = *memopt;
947                 free(memopt);
948         }
949         else
950                 bmp->memopt = WRC_MO_MOVEABLE | WRC_MO_PURE;
951         rd->size -= convert_bitmap(rd->data, rd->size);
952         return bmp;
953 }
954
955 ver_words_t *new_ver_words(int i)
956 {
957         ver_words_t *w = (ver_words_t *)xmalloc(sizeof(ver_words_t));
958         w->words = (WORD *)xmalloc(sizeof(WORD));
959         w->words[0] = (WORD)i;
960         w->nwords = 1;
961         return w;
962 }
963
964 ver_words_t *add_ver_words(ver_words_t *w, int i)
965 {
966         w->words = (WORD *)xrealloc(w->words, (w->nwords+1) * sizeof(WORD));
967         w->words[w->nwords] = (WORD)i;
968         w->nwords++;
969         return w;
970 }
971
972 #define MSGTAB_BAD_PTR(p, b, l, r)      (((l) - ((char *)(p) - (char *)(b))) > (r))
973 messagetable_t *new_messagetable(raw_data_t *rd, int *memopt)
974 {
975         messagetable_t *msg = (messagetable_t *)xmalloc(sizeof(messagetable_t));
976         msgtab_block_t *mbp;
977         DWORD nblk;
978         DWORD i;
979         WORD lo;
980         WORD hi;
981
982         msg->data = rd;
983         if(memopt)
984         {
985                 msg->memopt = *memopt;
986                 free(memopt);
987         }
988         else
989                 msg->memopt = WRC_MO_MOVEABLE | WRC_MO_PURE;
990
991         if(rd->size < sizeof(DWORD))
992                 yyerror("Invalid messagetable, size too small");
993
994         nblk = *(DWORD *)rd->data;
995         lo = WRC_LOWORD(nblk);
996         hi = WRC_HIWORD(nblk);
997
998         /* FIXME:
999          * This test will fail for all n*2^16 blocks in the messagetable.
1000          * However, no sane person would want to have so many blocks
1001          * and have a table of megabytes attached.
1002          * So, I will assume that we have less than 2^16 blocks in the table
1003          * and all will just work out fine. Otherwise, we would need to test
1004          * the ID, offset and length (and flag) fields to be very sure.
1005          */
1006         if(hi && lo)
1007                 internal_error(__FILE__, __LINE__, "Messagetable contains more than 65535 blocks; cannot determine endian");
1008         if(!hi && !lo)
1009                 yyerror("Invalid messagetable block count 0");
1010
1011         if(!hi && lo)  /* Messagetable byteorder == native byteorder */
1012         {
1013 #ifdef WORDS_BIGENDIAN
1014                 if(byteorder != WRC_BO_LITTLE) goto out;
1015 #else
1016                 if(byteorder != WRC_BO_BIG) goto out;
1017 #endif
1018                 /* Resource byteorder != native byteorder */
1019
1020                 mbp = (msgtab_block_t *)&(((DWORD *)rd->data)[1]);
1021                 if(MSGTAB_BAD_PTR(mbp, rd->data, rd->size, nblk * sizeof(*mbp)))
1022                         yyerror("Messagetable's blocks are outside of defined data");
1023                 for(i = 0; i < nblk; i++)
1024                 {
1025                         msgtab_entry_t *mep, *next_mep;
1026                         DWORD id;
1027
1028                         mep = (msgtab_entry_t *)(((char *)rd->data) + mbp[i].offset);
1029
1030                         for(id = mbp[i].idlo; id <= mbp[i].idhi; id++)
1031                         {
1032                                 if(MSGTAB_BAD_PTR(mep, rd->data, rd->size, mep->length))
1033                                         yyerror("Messagetable's data for block %d, ID 0x%08lx is outside of defined data", (int)i, id);
1034                                 if(mep->flags == 1)     /* Docu says 'flags == 0x0001' for unicode */
1035                                 {
1036                                         WORD *wp = (WORD *)&mep[1];
1037                                         int l = mep->length/2 - 2; /* Length included header */
1038                                         int n;
1039
1040                                         if(mep->length & 1)
1041                                                 yyerror("Message 0x%08lx is unicode (block %d), but has odd length (%d)", id, (int)i, mep->length);
1042                                         for(n = 0; n < l; n++)
1043                                                 wp[n] = BYTESWAP_WORD(wp[n]);
1044
1045                                 }
1046                                 next_mep = (msgtab_entry_t *)(((char *)mep) + mep->length);
1047                                 mep->length = BYTESWAP_WORD(mep->length);
1048                                 mep->flags  = BYTESWAP_WORD(mep->flags);
1049                                 mep = next_mep;
1050                         }
1051
1052                         mbp[i].idlo   = BYTESWAP_DWORD(mbp[i].idlo);
1053                         mbp[i].idhi   = BYTESWAP_DWORD(mbp[i].idhi);
1054                         mbp[i].offset = BYTESWAP_DWORD(mbp[i].offset);
1055                 }
1056         }
1057         if(hi && !lo)  /* Messagetable byteorder != native byteorder */
1058         {
1059 #ifdef WORDS_BIGENDIAN
1060                 if(byteorder == WRC_BO_LITTLE) goto out;
1061 #else
1062                 if(byteorder == WRC_BO_BIG) goto out;
1063 #endif
1064                 /* Resource byteorder == native byteorder */
1065
1066                 mbp = (msgtab_block_t *)&(((DWORD *)rd->data)[1]);
1067                 nblk = BYTESWAP_DWORD(nblk);
1068                 if(MSGTAB_BAD_PTR(mbp, rd->data, rd->size, nblk * sizeof(*mbp)))
1069                         yyerror("Messagetable's blocks are outside of defined data");
1070                 for(i = 0; i < nblk; i++)
1071                 {
1072                         msgtab_entry_t *mep;
1073                         DWORD id;
1074
1075                         mbp[i].idlo   = BYTESWAP_DWORD(mbp[i].idlo);
1076                         mbp[i].idhi   = BYTESWAP_DWORD(mbp[i].idhi);
1077                         mbp[i].offset = BYTESWAP_DWORD(mbp[i].offset);
1078                         mep = (msgtab_entry_t *)(((char *)rd->data) + mbp[i].offset);
1079
1080                         for(id = mbp[i].idlo; id <= mbp[i].idhi; id++)
1081                         {
1082                                 mep->length = BYTESWAP_WORD(mep->length);
1083                                 mep->flags  = BYTESWAP_WORD(mep->flags);
1084
1085                                 if(MSGTAB_BAD_PTR(mep, rd->data, rd->size, mep->length))
1086                                         yyerror("Messagetable's data for block %d, ID 0x%08lx is outside of defined data", (int)i, id);
1087                                 if(mep->flags == 1)     /* Docu says 'flags == 0x0001' for unicode */
1088                                 {
1089                                         WORD *wp = (WORD *)&mep[1];
1090                                         int l = mep->length/2 - 2; /* Length included header */
1091                                         int n;
1092
1093                                         if(mep->length & 1)
1094                                                 yyerror("Message 0x%08lx is unicode (block %d), but has odd length (%d)", id, (int)i, mep->length);
1095                                         for(n = 0; n < l; n++)
1096                                                 wp[n] = BYTESWAP_WORD(wp[n]);
1097
1098                                 }
1099                                 mep = (msgtab_entry_t *)(((char *)mep) + mep->length);
1100                         }
1101                 }
1102         }
1103
1104  out:
1105         return msg;
1106 }
1107 #undef MSGTAB_BAD_PTR
1108
1109 void copy_raw_data(raw_data_t *dst, raw_data_t *src, unsigned int offs, int len)
1110 {
1111         assert(offs <= src->size);
1112         assert(offs + len <= src->size);
1113         if(!dst->data)
1114         {
1115                 dst->data = (char *)xmalloc(len);
1116                 dst->size = 0;
1117         }
1118         else
1119                 dst->data = (char *)xrealloc(dst->data, dst->size + len);
1120         /* dst->size holds the offset to copy to */
1121         memcpy(dst->data + dst->size, src->data + offs, len);
1122         dst->size += len;
1123 }
1124
1125 int *new_int(int i)
1126 {
1127         int *ip = (int *)xmalloc(sizeof(int));
1128         *ip = i;
1129         return ip;
1130 }
1131
1132 stringtable_t *new_stringtable(lvc_t *lvc)
1133 {
1134         stringtable_t *stt = (stringtable_t *)xmalloc(sizeof(stringtable_t));
1135
1136         if(lvc)
1137                 stt->lvc = *lvc;
1138
1139         return stt;
1140 }
1141
1142 toolbar_t *new_toolbar(int button_width, int button_height, toolbar_item_t *items, int nitems)
1143 {
1144         toolbar_t *tb = (toolbar_t *)xmalloc(sizeof(toolbar_t));
1145         tb->button_width = button_width;
1146         tb->button_height = button_height;
1147         tb->nitems = nitems;
1148         tb->items = items;
1149         return tb;
1150 }
1151
1152 dlginit_t *new_dlginit(raw_data_t *rd, int *memopt)
1153 {
1154         dlginit_t *di = (dlginit_t *)xmalloc(sizeof(dlginit_t));
1155         di->data = rd;
1156         if(memopt)
1157         {
1158                 di->memopt = *memopt;
1159                 free(memopt);
1160         }
1161         else
1162                 di->memopt = WRC_MO_MOVEABLE | WRC_MO_PURE | WRC_MO_DISCARDABLE;
1163
1164         return di;
1165 }
1166
1167 style_pair_t *new_style_pair(style_t *style, style_t *exstyle)
1168 {
1169         style_pair_t *sp = (style_pair_t *)xmalloc(sizeof(style_pair_t));
1170         sp->style = style;
1171         sp->exstyle = exstyle;
1172         return sp;
1173 }
1174
1175 style_t *new_style(DWORD or_mask, DWORD and_mask)
1176 {
1177         style_t *st = (style_t *)xmalloc(sizeof(style_t));
1178         st->or_mask = or_mask;
1179         st->and_mask = and_mask;
1180         return st;
1181 }