ddraw/tests: Fix compilation on systems that don't support nameless unions.
[wine] / dlls / user32 / exticon.c
1 /*
2  *      icon extracting
3  *
4  * taken and slightly changed from shell
5  * this should replace the icon extraction code in shell32 and shell16 once
6  * it needs a serious test for compliance with the native API
7  *
8  * Copyright 2000 Juergen Schmied
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include "config.h"
26
27 #include <stdarg.h>
28 #include <string.h>
29 #include <stdlib.h>     /* abs() */
30 #include <sys/types.h>
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34
35 #define NONAMELESSUNION
36 #define NONAMELESSSTRUCT
37 #include "windef.h"
38 #include "winbase.h"
39 #include "winuser.h"
40 #include "winnls.h"
41 #include "user_private.h"
42 #include "wine/debug.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(icon);
45
46 #include "pshpack1.h"
47
48 typedef struct
49 {
50     BYTE        bWidth;          /* Width, in pixels, of the image      */
51     BYTE        bHeight;         /* Height, in pixels, of the image     */
52     BYTE        bColorCount;     /* Number of colors in image (0 if >=8bpp) */
53     BYTE        bReserved;       /* Reserved ( must be 0)               */
54     WORD        wPlanes;         /* Color Planes                        */
55     WORD        wBitCount;       /* Bits per pixel                      */
56     DWORD       dwBytesInRes;    /* How many bytes in this resource?    */
57     DWORD       dwImageOffset;   /* Where in the file is this image?    */
58 } icoICONDIRENTRY, *LPicoICONDIRENTRY;
59
60 typedef struct
61 {
62     WORD            idReserved;   /* Reserved (must be 0) */
63     WORD            idType;       /* Resource Type (RES_ICON or RES_CURSOR) */
64     WORD            idCount;      /* How many images */
65     icoICONDIRENTRY idEntries[1]; /* An entry for each image (idCount of 'em) */
66 } icoICONDIR, *LPicoICONDIR;
67
68 typedef struct
69 {
70     WORD offset;
71     WORD length;
72     WORD flags;
73     WORD id;
74     WORD handle;
75     WORD usage;
76 } NE_NAMEINFO;
77
78 typedef struct
79 {
80     WORD  type_id;
81     WORD  count;
82     DWORD resloader;
83 } NE_TYPEINFO;
84
85 #define NE_RSCTYPE_ICON        0x8003
86 #define NE_RSCTYPE_GROUP_ICON  0x800e
87
88 #include "poppack.h"
89
90 #if 0
91 static void dumpIcoDirEnty ( LPicoICONDIRENTRY entry )
92 {
93         TRACE("width = 0x%08x height = 0x%08x\n", entry->bWidth, entry->bHeight);
94         TRACE("colors = 0x%08x planes = 0x%08x\n", entry->bColorCount, entry->wPlanes);
95         TRACE("bitcount = 0x%08x bytesinres = 0x%08lx offset = 0x%08lx\n",
96         entry->wBitCount, entry->dwBytesInRes, entry->dwImageOffset);
97 }
98 static void dumpIcoDir ( LPicoICONDIR entry )
99 {
100         TRACE("type = 0x%08x count = 0x%08x\n", entry->idType, entry->idCount);
101 }
102 #endif
103
104 /**********************************************************************
105  *  find_entry_by_id
106  *
107  * Find an entry by id in a resource directory
108  * Copied from loader/pe_resource.c (FIXME: should use exported resource functions)
109  */
110 static const IMAGE_RESOURCE_DIRECTORY *find_entry_by_id( const IMAGE_RESOURCE_DIRECTORY *dir,
111                                                          WORD id, const void *root )
112 {
113     const IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
114     int min, max, pos;
115
116     entry = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
117     min = dir->NumberOfNamedEntries;
118     max = min + dir->NumberOfIdEntries - 1;
119     while (min <= max)
120     {
121         pos = (min + max) / 2;
122         if (entry[pos].u1.s2.Id == id)
123             return (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + entry[pos].u2.s3.OffsetToDirectory);
124         if (entry[pos].u1.s2.Id > id) max = pos - 1;
125         else min = pos + 1;
126     }
127     return NULL;
128 }
129
130 /**********************************************************************
131  *  find_entry_default
132  *
133  * Find a default entry in a resource directory
134  * Copied from loader/pe_resource.c (FIXME: should use exported resource functions)
135  */
136 static const IMAGE_RESOURCE_DIRECTORY *find_entry_default( const IMAGE_RESOURCE_DIRECTORY *dir,
137                                                            const void *root )
138 {
139     const IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
140     entry = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
141     return (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + entry->u2.s3.OffsetToDirectory);
142 }
143
144 /*************************************************************************
145  *                              USER32_GetResourceTable
146  */
147 static DWORD USER32_GetResourceTable(LPBYTE peimage,DWORD pesize,LPBYTE *retptr)
148 {
149         IMAGE_DOS_HEADER        * mz_header;
150
151         TRACE("%p %p\n", peimage, retptr);
152
153         *retptr = NULL;
154
155         mz_header = (IMAGE_DOS_HEADER*) peimage;
156
157         if (mz_header->e_magic != IMAGE_DOS_SIGNATURE)
158         {
159           if (mz_header->e_cblp == 1)   /* .ICO file ? */
160           {
161             *retptr = (LPBYTE)-1;       /* ICONHEADER.idType, must be 1 */
162             return 1;
163           }
164           else
165             return 0; /* failed */
166         }
167         if (mz_header->e_lfanew >= pesize) {
168             return 0; /* failed, happens with PKZIP DOS Exes for instance. */
169         }
170         if (*((DWORD*)(peimage + mz_header->e_lfanew)) == IMAGE_NT_SIGNATURE )
171           return IMAGE_NT_SIGNATURE;
172
173         if (*((WORD*)(peimage + mz_header->e_lfanew)) == IMAGE_OS2_SIGNATURE )
174         {
175           IMAGE_OS2_HEADER      * ne_header;
176
177           ne_header = (IMAGE_OS2_HEADER*)(peimage + mz_header->e_lfanew);
178
179           if (ne_header->ne_magic != IMAGE_OS2_SIGNATURE)
180             return 0;
181
182           if( (ne_header->ne_restab - ne_header->ne_rsrctab) <= sizeof(NE_TYPEINFO) )
183             *retptr = (LPBYTE)-1;
184           else
185             *retptr = peimage + mz_header->e_lfanew + ne_header->ne_rsrctab;
186
187           return IMAGE_OS2_SIGNATURE;
188         }
189         return 0; /* failed */
190 }
191 /*************************************************************************
192  *                      USER32_LoadResource
193  */
194 static BYTE * USER32_LoadResource( LPBYTE peimage, NE_NAMEINFO* pNInfo, WORD sizeShift, ULONG *uSize)
195 {
196         TRACE("%p %p 0x%08x\n", peimage, pNInfo, sizeShift);
197
198         *uSize = (DWORD)pNInfo->length << sizeShift;
199         return peimage + ((DWORD)pNInfo->offset << sizeShift);
200 }
201
202 /*************************************************************************
203  *                      ICO_LoadIcon
204  */
205 static BYTE * ICO_LoadIcon( LPBYTE peimage, LPicoICONDIRENTRY lpiIDE, ULONG *uSize)
206 {
207         TRACE("%p %p\n", peimage, lpiIDE);
208
209         *uSize = lpiIDE->dwBytesInRes;
210         return peimage + lpiIDE->dwImageOffset;
211 }
212
213 /*************************************************************************
214  *                      ICO_GetIconDirectory
215  *
216  * Reads .ico file and build phony ICONDIR struct
217  */
218 #define HEADER_SIZE             (sizeof(CURSORICONDIR) - sizeof (CURSORICONDIRENTRY))
219 #define HEADER_SIZE_FILE        (sizeof(icoICONDIR) - sizeof (icoICONDIRENTRY))
220
221 static BYTE * ICO_GetIconDirectory( LPBYTE peimage, LPicoICONDIR* lplpiID, ULONG *uSize )
222 {
223         CURSORICONDIR   * lpcid;        /* icon resource in resource-dir format */
224         CURSORICONDIR   * lpID;         /* icon resource in resource format */
225         int             i;
226
227         TRACE("%p %p\n", peimage, lplpiID);
228
229         lpcid = (CURSORICONDIR*)peimage;
230
231         if( lpcid->idReserved || (lpcid->idType != 1) || (!lpcid->idCount) )
232           return 0;
233
234         /* allocate the phony ICONDIR structure */
235         *uSize = lpcid->idCount * sizeof(CURSORICONDIRENTRY) + HEADER_SIZE;
236         if( (lpID = HeapAlloc(GetProcessHeap(),0, *uSize) ))
237         {
238           /* copy the header */
239           lpID->idReserved = lpcid->idReserved;
240           lpID->idType = lpcid->idType;
241           lpID->idCount = lpcid->idCount;
242
243           /* copy the entries */
244           for( i=0; i < lpcid->idCount; i++ )
245           {
246             memcpy(&lpID->idEntries[i], &lpcid->idEntries[i], sizeof(CURSORICONDIRENTRY) - 2);
247             lpID->idEntries[i].wResId = i;
248           }
249
250           *lplpiID = (LPicoICONDIR)peimage;
251           return (BYTE *)lpID;
252         }
253         return 0;
254 }
255
256 /*************************************************************************
257  *      ICO_ExtractIconExW              [internal]
258  *
259  * NOTES
260  *  nIcons = 0: returns number of Icons in file
261  *
262  * returns
263  *  invalid file: -1
264  *  failure:0;
265  *  success: number of icons in file (nIcons = 0) or nr of icons retrieved
266  */
267 static UINT ICO_ExtractIconExW(
268         LPCWSTR lpszExeFileName,
269         HICON * RetPtr,
270         INT nIconIndex,
271         UINT nIcons,
272         UINT cxDesired,
273         UINT cyDesired,
274         UINT *pIconId,
275         UINT flags)
276 {
277         UINT            ret = 0;
278         UINT            cx1, cx2, cy1, cy2;
279         LPBYTE          pData;
280         DWORD           sig;
281         HANDLE          hFile;
282         UINT16          iconDirCount = 0,iconCount = 0;
283         LPBYTE          peimage;
284         HANDLE          fmapping;
285         DWORD           fsizeh,fsizel;
286         WCHAR           szExePath[MAX_PATH];
287         DWORD           dwSearchReturn;
288
289         TRACE("%s, %d, %d %p 0x%08x\n", debugstr_w(lpszExeFileName), nIconIndex, nIcons, pIconId, flags);
290
291         dwSearchReturn = SearchPathW(NULL, lpszExeFileName, NULL, sizeof(szExePath) / sizeof(szExePath[0]), szExePath, NULL);
292         if ((dwSearchReturn == 0) || (dwSearchReturn > sizeof(szExePath) / sizeof(szExePath[0])))
293         {
294             WARN("File %s not found or path too long\n", debugstr_w(lpszExeFileName));
295             return -1;
296         }
297
298         hFile = CreateFileW(szExePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
299         if (hFile == INVALID_HANDLE_VALUE) return ret;
300         fsizel = GetFileSize(hFile,&fsizeh);
301
302         /* Map the file */
303         fmapping = CreateFileMappingW(hFile, NULL, PAGE_READONLY | SEC_COMMIT, 0, 0, NULL);
304         CloseHandle(hFile);
305         if (!fmapping)
306         {
307           WARN("CreateFileMapping error %d\n", GetLastError() );
308           return 0xFFFFFFFF;
309         }
310
311         if (!(peimage = MapViewOfFile(fmapping, FILE_MAP_READ, 0, 0, 0)))
312         {
313           WARN("MapViewOfFile error %d\n", GetLastError() );
314           CloseHandle(fmapping);
315           return 0xFFFFFFFF;
316         }
317         CloseHandle(fmapping);
318
319         cx1 = LOWORD(cxDesired);
320         cx2 = HIWORD(cxDesired);
321         cy1 = LOWORD(cyDesired);
322         cy2 = HIWORD(cyDesired);
323
324         if (pIconId) /* Invalidate first icon identifier */
325                 *pIconId = 0xFFFFFFFF;
326
327         if (!pIconId) /* if no icon identifier array present use the icon handle array as intermediate storage */
328           pIconId = (UINT*)RetPtr;
329
330         sig = USER32_GetResourceTable(peimage, fsizel, &pData);
331
332 /* ico file or NE exe/dll*/
333         if (sig==IMAGE_OS2_SIGNATURE || sig==1) /* .ICO file */
334         {
335           BYTE          *pCIDir = 0;
336           NE_TYPEINFO   *pTInfo = (NE_TYPEINFO*)(pData + 2);
337           NE_NAMEINFO   *pIconStorage = NULL;
338           NE_NAMEINFO   *pIconDir = NULL;
339           LPicoICONDIR  lpiID = NULL;
340           ULONG         uSize = 0;
341
342           TRACE("-- OS2/icon Signature (0x%08x)\n", sig);
343
344           if (pData == (BYTE*)-1)
345           {
346             pCIDir = ICO_GetIconDirectory(peimage, &lpiID, &uSize);     /* check for .ICO file */
347             if (pCIDir)
348             {
349               iconDirCount = 1; iconCount = lpiID->idCount;
350               TRACE("-- icon found %p 0x%08x 0x%08x 0x%08x\n", pCIDir, uSize, iconDirCount, iconCount);
351             }
352           }
353           else while (pTInfo->type_id && !(pIconStorage && pIconDir))
354           {
355             if (pTInfo->type_id == NE_RSCTYPE_GROUP_ICON)       /* find icon directory and icon repository */
356             {
357               iconDirCount = pTInfo->count;
358               pIconDir = ((NE_NAMEINFO*)(pTInfo + 1));
359               TRACE("\tfound directory - %i icon families\n", iconDirCount);
360             }
361             if (pTInfo->type_id == NE_RSCTYPE_ICON)
362             {
363               iconCount = pTInfo->count;
364               pIconStorage = ((NE_NAMEINFO*)(pTInfo + 1));
365               TRACE("\ttotal icons - %i\n", iconCount);
366             }
367             pTInfo = (NE_TYPEINFO *)((char*)(pTInfo+1)+pTInfo->count*sizeof(NE_NAMEINFO));
368           }
369
370           if ((pIconStorage && pIconDir) || lpiID)        /* load resources and create icons */
371           {
372             if (nIcons == 0)
373             {
374               ret = iconDirCount;
375               if (lpiID)        /* *.ico file, deallocate heap pointer*/
376                 HeapFree(GetProcessHeap(), 0, pCIDir);
377             }
378             else if (nIconIndex < iconDirCount)
379             {
380               UINT16   i, icon;
381               if (nIcons > iconDirCount - nIconIndex)
382                 nIcons = iconDirCount - nIconIndex;
383
384               for (i = 0; i < nIcons; i++)
385               {
386                 /* .ICO files have only one icon directory */
387                 if (lpiID == NULL)      /* not *.ico */
388                   pCIDir = USER32_LoadResource(peimage, pIconDir + i + nIconIndex, *(WORD*)pData, &uSize);
389                 pIconId[i] = LookupIconIdFromDirectoryEx(pCIDir, TRUE, cx1, cy1, flags);
390                 if (cx2 && cy2) pIconId[++i] = LookupIconIdFromDirectoryEx(pCIDir, TRUE,  cx2, cy2, flags);
391               }
392               if (lpiID)        /* *.ico file, deallocate heap pointer*/
393                 HeapFree(GetProcessHeap(), 0, pCIDir);
394
395               for (icon = 0; icon < nIcons; icon++)
396               {
397                 pCIDir = NULL;
398                 if (lpiID)
399                   pCIDir = ICO_LoadIcon(peimage, lpiID->idEntries + (int)pIconId[icon], &uSize);
400                 else
401                   for (i = 0; i < iconCount; i++)
402                     if (pIconStorage[i].id == ((int)pIconId[icon] | 0x8000) )
403                       pCIDir = USER32_LoadResource(peimage, pIconStorage + i, *(WORD*)pData, &uSize);
404
405                 if (pCIDir)
406                 {
407                   RetPtr[icon] = CreateIconFromResourceEx(pCIDir, uSize, TRUE, 0x00030000,
408                                                                  cx1, cy1, flags);
409                   if (cx2 && cy2)
410                       RetPtr[++icon] = CreateIconFromResourceEx(pCIDir, uSize, TRUE, 0x00030000,
411                                                                        cx2, cy2, flags);
412                 }
413                 else
414                   RetPtr[icon] = 0;
415               }
416               ret = icon;       /* return number of retrieved icons */
417             }
418           }
419         }
420 /* end ico file */
421
422 /* exe/dll */
423         else if( sig == IMAGE_NT_SIGNATURE )
424         {
425           LPBYTE                idata,igdata;
426           PIMAGE_DOS_HEADER     dheader;
427           PIMAGE_NT_HEADERS     pe_header;
428           PIMAGE_SECTION_HEADER pe_sections;
429           const IMAGE_RESOURCE_DIRECTORY *rootresdir,*iconresdir,*icongroupresdir;
430           const IMAGE_RESOURCE_DATA_ENTRY *idataent,*igdataent;
431           const IMAGE_RESOURCE_DIRECTORY_ENTRY *xresent;
432           UINT  i, j;
433
434           dheader = (PIMAGE_DOS_HEADER)peimage;
435           pe_header = (PIMAGE_NT_HEADERS)(peimage+dheader->e_lfanew);     /* it is a pe header, USER32_GetResourceTable checked that */
436           pe_sections = (PIMAGE_SECTION_HEADER)(((char*)pe_header) + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER)
437                                                 + pe_header->FileHeader.SizeOfOptionalHeader);
438           rootresdir = NULL;
439
440           /* search for the root resource directory */
441           for (i=0;i<pe_header->FileHeader.NumberOfSections;i++)
442           {
443             if (pe_sections[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
444               continue;
445             if (fsizel < pe_sections[i].PointerToRawData+pe_sections[i].SizeOfRawData) {
446               FIXME("File %s too short (section is at %d bytes, real size is %d)\n",
447                       debugstr_w(lpszExeFileName),
448                       pe_sections[i].PointerToRawData+pe_sections[i].SizeOfRawData,
449                       fsizel
450               );
451               goto end;
452             }
453             /* FIXME: doesn't work when the resources are not in a separate section */
454             if (pe_sections[i].VirtualAddress == pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress)
455             {
456               rootresdir = (PIMAGE_RESOURCE_DIRECTORY)(peimage+pe_sections[i].PointerToRawData);
457               break;
458             }
459           }
460
461           if (!rootresdir)
462           {
463             WARN("haven't found section for resource directory.\n");
464             goto end;           /* failure */
465           }
466
467           /* search for the group icon directory */
468           if (!(icongroupresdir = find_entry_by_id(rootresdir, LOWORD(RT_GROUP_ICON), rootresdir)))
469           {
470             WARN("No Icongroupresourcedirectory!\n");
471             goto end;           /* failure */
472           }
473           iconDirCount = icongroupresdir->NumberOfNamedEntries + icongroupresdir->NumberOfIdEntries;
474
475           /* only number of icons requested */
476           if( !pIconId )
477           {
478             ret = iconDirCount;
479             goto end;           /* success */
480           }
481
482           if( nIconIndex < 0 )
483           {
484             /* search resource id */
485             int n = 0;
486             int iId = abs(nIconIndex);
487             const IMAGE_RESOURCE_DIRECTORY_ENTRY* xprdeTmp = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(icongroupresdir+1);
488
489             while(n<iconDirCount && xprdeTmp)
490             {
491               if(xprdeTmp->u1.s2.Id ==  iId)
492               {
493                   nIconIndex = n;
494                   break;
495               }
496               n++;
497               xprdeTmp++;
498             }
499             if (nIconIndex < 0)
500             {
501               WARN("resource id %d not found\n", iId);
502               goto end;         /* failure */
503             }
504           }
505           else
506           {
507             /* check nIconIndex to be in range */
508             if (nIconIndex >= iconDirCount)
509             {
510               WARN("nIconIndex %d is larger than iconDirCount %d\n",nIconIndex,iconDirCount);
511               goto end;         /* failure */
512             }
513           }
514
515           /* assure we don't get too much */
516           if( nIcons > iconDirCount - nIconIndex )
517             nIcons = iconDirCount - nIconIndex;
518
519           /* starting from specified index */
520           xresent = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(icongroupresdir+1) + nIconIndex;
521
522           for (i=0; i < nIcons; i++,xresent++)
523           {
524             const IMAGE_RESOURCE_DIRECTORY *resdir;
525
526             /* go down this resource entry, name */
527             resdir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)rootresdir + xresent->u2.s3.OffsetToDirectory);
528
529             /* default language (0) */
530             resdir = find_entry_default(resdir,rootresdir);
531             igdataent = (const IMAGE_RESOURCE_DATA_ENTRY*)resdir;
532
533             /* lookup address in mapped image for virtual address */
534             igdata = NULL;
535
536             for (j=0;j<pe_header->FileHeader.NumberOfSections;j++)
537             {
538               if (igdataent->OffsetToData < pe_sections[j].VirtualAddress)
539                 continue;
540               if (igdataent->OffsetToData+igdataent->Size > pe_sections[j].VirtualAddress+pe_sections[j].SizeOfRawData)
541                 continue;
542
543               if (igdataent->OffsetToData-pe_sections[j].VirtualAddress+pe_sections[j].PointerToRawData+igdataent->Size > fsizel) {
544                 FIXME("overflow in PE lookup (%s has len %d, have offset %d), short file?\n", debugstr_w(lpszExeFileName), fsizel,
545                            igdataent->OffsetToData - pe_sections[j].VirtualAddress + pe_sections[j].PointerToRawData + igdataent->Size);
546                 goto end; /* failure */
547               }
548               igdata = peimage+(igdataent->OffsetToData-pe_sections[j].VirtualAddress+pe_sections[j].PointerToRawData);
549             }
550
551             if (!igdata)
552             {
553               FIXME("no matching real address for icongroup!\n");
554               goto end; /* failure */
555             }
556             pIconId[i] = LookupIconIdFromDirectoryEx(igdata, TRUE, cx1, cy1, flags);
557             if (cx2 && cy2) pIconId[++i] = LookupIconIdFromDirectoryEx(igdata, TRUE, cx2, cy2, flags);
558           }
559
560           if (!(iconresdir=find_entry_by_id(rootresdir,LOWORD(RT_ICON),rootresdir)))
561           {
562             WARN("No Iconresourcedirectory!\n");
563             goto end;           /* failure */
564           }
565
566           for (i=0; i<nIcons; i++)
567           {
568             const IMAGE_RESOURCE_DIRECTORY *xresdir;
569             xresdir = find_entry_by_id(iconresdir, LOWORD(pIconId[i]), rootresdir);
570             if( !xresdir )
571             {
572               WARN("icon entry %d not found\n", LOWORD(pIconId[i]));
573               RetPtr[i]=0;
574               continue;
575             }
576             xresdir = find_entry_default(xresdir, rootresdir);
577             idataent = (const IMAGE_RESOURCE_DATA_ENTRY*)xresdir;
578             idata = NULL;
579
580             /* map virtual to address in image */
581             for (j=0;j<pe_header->FileHeader.NumberOfSections;j++)
582             {
583               if (idataent->OffsetToData < pe_sections[j].VirtualAddress)
584                 continue;
585               if (idataent->OffsetToData+idataent->Size > pe_sections[j].VirtualAddress+pe_sections[j].SizeOfRawData)
586                 continue;
587               idata = peimage+(idataent->OffsetToData-pe_sections[j].VirtualAddress+pe_sections[j].PointerToRawData);
588             }
589             if (!idata)
590             {
591               WARN("no matching real address found for icondata!\n");
592               RetPtr[i]=0;
593               continue;
594             }
595             RetPtr[i] = CreateIconFromResourceEx(idata, idataent->Size, TRUE, 0x00030000, cx1, cy1, flags);
596             if (cx2 && cy2)
597                 RetPtr[++i] = CreateIconFromResourceEx(idata, idataent->Size, TRUE, 0x00030000, cx2, cy2, flags);
598           }
599           ret = i;      /* return number of retrieved icons */
600         }                       /* if(sig == IMAGE_NT_SIGNATURE) */
601
602 end:
603         UnmapViewOfFile(peimage);       /* success */
604         return ret;
605 }
606
607 /***********************************************************************
608  *           PrivateExtractIconsW                       [USER32.@]
609  *
610  * NOTES
611  *  If HIWORD(sizeX) && HIWORD(sizeY) 2 * ((nIcons + 1) MOD 2) icons are
612  *  returned, with the LOWORD size icon first and the HIWORD size icon
613  *  second.
614  *  Also the Windows equivalent does extract icons in a strange way if
615  *  nIndex is negative. Our implementation treats a negative nIndex as
616  *  looking for that resource identifier for the first icon to retrieve.
617  *
618  * FIXME:
619  *  should also support 16 bit EXE + DLLs, cursor and animated cursor as
620  *  well as bitmap files.
621  */
622
623 UINT WINAPI PrivateExtractIconsW (
624         LPCWSTR lpwstrFile,
625         int nIndex,
626         int sizeX,
627         int sizeY,
628         HICON * phicon, /* [out] pointer to array of nIcons HICON handles */
629         UINT* pIconId,  /* [out] pointer to array of nIcons icon identifiers or NULL */
630         UINT nIcons,    /* [in] number of icons to retrieve */
631         UINT flags )    /* [in] LR_* flags used by LoadImage */
632 {
633         TRACE("%s %d %dx%d %p %p %d 0x%08x\n",
634               debugstr_w(lpwstrFile), nIndex, sizeX, sizeY, phicon, pIconId, nIcons, flags);
635
636         if ((nIcons & 1) && HIWORD(sizeX) && HIWORD(sizeY))
637         {
638           WARN("Uneven number %d of icons requested for small and large icons!\n", nIcons);
639         }
640         return ICO_ExtractIconExW(lpwstrFile, phicon, nIndex, nIcons, sizeX, sizeY, pIconId, flags);
641 }
642
643 /***********************************************************************
644  *           PrivateExtractIconsA                       [USER32.@]
645  */
646
647 UINT WINAPI PrivateExtractIconsA (
648         LPCSTR lpstrFile,
649         int nIndex,
650         int sizeX,
651         int sizeY,
652         HICON * phicon, /* [out] pointer to array of nIcons HICON handles */
653         UINT* piconid,  /* [out] pointer to array of nIcons icon identifiers or NULL */
654         UINT nIcons,    /* [in] number of icons to retrieve */
655         UINT flags )    /* [in] LR_* flags used by LoadImage */
656 {
657     UINT ret;
658     INT len = MultiByteToWideChar(CP_ACP, 0, lpstrFile, -1, NULL, 0);
659     LPWSTR lpwstrFile = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
660
661     MultiByteToWideChar(CP_ACP, 0, lpstrFile, -1, lpwstrFile, len);
662     ret = PrivateExtractIconsW(lpwstrFile, nIndex, sizeX, sizeY, phicon, piconid, nIcons, flags);
663
664     HeapFree(GetProcessHeap(), 0, lpwstrFile);
665     return ret;
666 }
667
668 /***********************************************************************
669  *           PrivateExtractIconExW                      [USER32.@]
670  * NOTES
671  *  if nIndex == -1 it returns the number of icons in any case !!!
672  */
673 UINT WINAPI PrivateExtractIconExW (
674         LPCWSTR lpwstrFile,
675         int nIndex,
676         HICON * phIconLarge,
677         HICON * phIconSmall,
678         UINT nIcons )
679 {
680         DWORD cyicon, cysmicon, cxicon, cxsmicon;
681         UINT ret = 0;
682
683         TRACE("%s %d %p %p %d\n",
684         debugstr_w(lpwstrFile),nIndex,phIconLarge, phIconSmall, nIcons);
685
686         if (nIndex == -1)
687           /* get the number of icons */
688           return ICO_ExtractIconExW(lpwstrFile, NULL, 0, 0, 0, 0, NULL, LR_DEFAULTCOLOR);
689
690         if (nIcons == 1 && phIconSmall && phIconLarge)
691         {
692           HICON hIcon[2];
693           cxicon = GetSystemMetrics(SM_CXICON);
694           cyicon = GetSystemMetrics(SM_CYICON);
695           cxsmicon = GetSystemMetrics(SM_CXSMICON);
696           cysmicon = GetSystemMetrics(SM_CYSMICON);
697
698           ret = ICO_ExtractIconExW(lpwstrFile, hIcon, nIndex, 2, cxicon | (cxsmicon<<16),
699                                    cyicon | (cysmicon<<16), NULL, LR_DEFAULTCOLOR);
700           *phIconLarge = hIcon[0];
701           *phIconSmall = hIcon[1];
702           return ret;
703         }
704
705         if (phIconSmall)
706         {
707           /* extract n small icons */
708           cxsmicon = GetSystemMetrics(SM_CXSMICON);
709           cysmicon = GetSystemMetrics(SM_CYSMICON);
710           ret = ICO_ExtractIconExW(lpwstrFile, phIconSmall, nIndex, nIcons, cxsmicon,
711                                    cysmicon, NULL, LR_DEFAULTCOLOR);
712         }
713        if (phIconLarge)
714         {
715           /* extract n large icons */
716           cxicon = GetSystemMetrics(SM_CXICON);
717           cyicon = GetSystemMetrics(SM_CYICON);
718          ret = ICO_ExtractIconExW(lpwstrFile, phIconLarge, nIndex, nIcons, cxicon,
719                                    cyicon, NULL, LR_DEFAULTCOLOR);
720         }
721         return ret;
722 }
723
724 /***********************************************************************
725  *           PrivateExtractIconExA                      [USER32.@]
726  */
727 UINT WINAPI PrivateExtractIconExA (
728         LPCSTR lpstrFile,
729         int nIndex,
730         HICON * phIconLarge,
731         HICON * phIconSmall,
732         UINT nIcons )
733 {
734         UINT ret;
735         INT len = MultiByteToWideChar(CP_ACP, 0, lpstrFile, -1, NULL, 0);
736         LPWSTR lpwstrFile = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
737
738         TRACE("%s %d %p %p %d\n", lpstrFile, nIndex, phIconLarge, phIconSmall, nIcons);
739
740         MultiByteToWideChar(CP_ACP, 0, lpstrFile, -1, lpwstrFile, len);
741         ret = PrivateExtractIconExW(lpwstrFile, nIndex, phIconLarge, phIconSmall, nIcons);
742         HeapFree(GetProcessHeap(), 0, lpwstrFile);
743         return ret;
744 }