comctl32/tests: We can now store binary files in the repository.
[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 "wine/winbase16.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 #include "poppack.h"
69
70 #if 0
71 static void dumpIcoDirEnty ( LPicoICONDIRENTRY entry )
72 {
73         TRACE("width = 0x%08x height = 0x%08x\n", entry->bWidth, entry->bHeight);
74         TRACE("colors = 0x%08x planes = 0x%08x\n", entry->bColorCount, entry->wPlanes);
75         TRACE("bitcount = 0x%08x bytesinres = 0x%08lx offset = 0x%08lx\n",
76         entry->wBitCount, entry->dwBytesInRes, entry->dwImageOffset);
77 }
78 static void dumpIcoDir ( LPicoICONDIR entry )
79 {
80         TRACE("type = 0x%08x count = 0x%08x\n", entry->idType, entry->idCount);
81 }
82 #endif
83
84 /**********************************************************************
85  *  find_entry_by_id
86  *
87  * Find an entry by id in a resource directory
88  * Copied from loader/pe_resource.c (FIXME: should use exported resource functions)
89  */
90 static const IMAGE_RESOURCE_DIRECTORY *find_entry_by_id( const IMAGE_RESOURCE_DIRECTORY *dir,
91                                                          WORD id, const void *root )
92 {
93     const IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
94     int min, max, pos;
95
96     entry = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
97     min = dir->NumberOfNamedEntries;
98     max = min + dir->NumberOfIdEntries - 1;
99     while (min <= max)
100     {
101         pos = (min + max) / 2;
102         if (entry[pos].u1.s2.Id == id)
103             return (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + entry[pos].u2.s3.OffsetToDirectory);
104         if (entry[pos].u1.s2.Id > id) max = pos - 1;
105         else min = pos + 1;
106     }
107     return NULL;
108 }
109
110 /**********************************************************************
111  *  find_entry_default
112  *
113  * Find a default entry in a resource directory
114  * Copied from loader/pe_resource.c (FIXME: should use exported resource functions)
115  */
116 static const IMAGE_RESOURCE_DIRECTORY *find_entry_default( const IMAGE_RESOURCE_DIRECTORY *dir,
117                                                            const void *root )
118 {
119     const IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
120     entry = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
121     return (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + entry->u2.s3.OffsetToDirectory);
122 }
123
124 /*************************************************************************
125  *                              USER32_GetResourceTable
126  */
127 static DWORD USER32_GetResourceTable(LPBYTE peimage,DWORD pesize,LPBYTE *retptr)
128 {
129         IMAGE_DOS_HEADER        * mz_header;
130
131         TRACE("%p %p\n", peimage, retptr);
132
133         *retptr = NULL;
134
135         mz_header = (IMAGE_DOS_HEADER*) peimage;
136
137         if (mz_header->e_magic != IMAGE_DOS_SIGNATURE)
138         {
139           if (mz_header->e_cblp == 1)   /* .ICO file ? */
140           {
141             *retptr = (LPBYTE)-1;       /* ICONHEADER.idType, must be 1 */
142             return 1;
143           }
144           else
145             return 0; /* failed */
146         }
147         if (mz_header->e_lfanew >= pesize) {
148             return 0; /* failed, happens with PKZIP DOS Exes for instance. */
149         }
150         if (*((DWORD*)(peimage + mz_header->e_lfanew)) == IMAGE_NT_SIGNATURE )
151           return IMAGE_NT_SIGNATURE;
152
153         if (*((WORD*)(peimage + mz_header->e_lfanew)) == IMAGE_OS2_SIGNATURE )
154         {
155           IMAGE_OS2_HEADER      * ne_header;
156
157           ne_header = (IMAGE_OS2_HEADER*)(peimage + mz_header->e_lfanew);
158
159           if (ne_header->ne_magic != IMAGE_OS2_SIGNATURE)
160             return 0;
161
162           if( (ne_header->ne_restab - ne_header->ne_rsrctab) <= sizeof(NE_TYPEINFO) )
163             *retptr = (LPBYTE)-1;
164           else
165             *retptr = peimage + mz_header->e_lfanew + ne_header->ne_rsrctab;
166
167           return IMAGE_OS2_SIGNATURE;
168         }
169         return 0; /* failed */
170 }
171 /*************************************************************************
172  *                      USER32_LoadResource
173  */
174 static BYTE * USER32_LoadResource( LPBYTE peimage, NE_NAMEINFO* pNInfo, WORD sizeShift, ULONG *uSize)
175 {
176         TRACE("%p %p 0x%08x\n", peimage, pNInfo, sizeShift);
177
178         *uSize = (DWORD)pNInfo->length << sizeShift;
179         return peimage + ((DWORD)pNInfo->offset << sizeShift);
180 }
181
182 /*************************************************************************
183  *                      ICO_LoadIcon
184  */
185 static BYTE * ICO_LoadIcon( LPBYTE peimage, LPicoICONDIRENTRY lpiIDE, ULONG *uSize)
186 {
187         TRACE("%p %p\n", peimage, lpiIDE);
188
189         *uSize = lpiIDE->dwBytesInRes;
190         return peimage + lpiIDE->dwImageOffset;
191 }
192
193 /*************************************************************************
194  *                      ICO_GetIconDirectory
195  *
196  * Reads .ico file and build phony ICONDIR struct
197  * see http://www.microsoft.com/win32dev/ui/icons.htm
198  */
199 #define HEADER_SIZE             (sizeof(CURSORICONDIR) - sizeof (CURSORICONDIRENTRY))
200 #define HEADER_SIZE_FILE        (sizeof(icoICONDIR) - sizeof (icoICONDIRENTRY))
201
202 static BYTE * ICO_GetIconDirectory( LPBYTE peimage, LPicoICONDIR* lplpiID, ULONG *uSize )
203 {
204         CURSORICONDIR   * lpcid;        /* icon resource in resource-dir format */
205         CURSORICONDIR   * lpID;         /* icon resource in resource format */
206         int             i;
207
208         TRACE("%p %p\n", peimage, lplpiID);
209
210         lpcid = (CURSORICONDIR*)peimage;
211
212         if( lpcid->idReserved || (lpcid->idType != 1) || (!lpcid->idCount) )
213           return 0;
214
215         /* allocate the phony ICONDIR structure */
216         *uSize = lpcid->idCount * sizeof(CURSORICONDIRENTRY) + HEADER_SIZE;
217         if( (lpID = HeapAlloc(GetProcessHeap(),0, *uSize) ))
218         {
219           /* copy the header */
220           lpID->idReserved = lpcid->idReserved;
221           lpID->idType = lpcid->idType;
222           lpID->idCount = lpcid->idCount;
223
224           /* copy the entries */
225           for( i=0; i < lpcid->idCount; i++ )
226           {
227             memcpy((void*)&(lpID->idEntries[i]),(void*)&(lpcid->idEntries[i]), sizeof(CURSORICONDIRENTRY) - 2);
228             lpID->idEntries[i].wResId = i;
229           }
230
231           *lplpiID = (LPicoICONDIR)peimage;
232           return (BYTE *)lpID;
233         }
234         return 0;
235 }
236
237 /******************************************************************************
238  *  struct extract_icons_state [internal]
239  *
240  * Used to carry params and state through the iterations of EnumResourceNames in ICO_ExtractIconExW 
241  */
242 struct extract_icons_state {
243     INT     nBaseIndex; /* Zero based index or negated integer id of the first icon to extract. */
244     UINT    nIcons;     /* Number of icons to extract. */
245     UINT    cxDesired;  /* Desired horizontal size in pixels (Might be two sizes in HI/LOWORD). */
246     UINT    cyDesired;  /* Desired vertical size in pixels (Might be two sizes in HI/LOWORD). */
247     UINT    fuLoad;     /* Flags passed to LoadImage. */
248     INT     cIter;      /* Iteration counter. */
249     HICON   *pahIcon;   /* Pointer to an array where the icon handles will be stored. */
250     UINT    *paIconId;  /* Pointer to an array where the icon identifiers will be stored. */ 
251 };
252
253 /******************************************************************************
254  *  extract_icons_callback [internal] 
255  *
256  * Callback function of type ENUMRESNAMEPROC for EnumResourceNames. Used in
257  * ICO_ExtractIconsExW.
258  */
259 static BOOL CALLBACK extract_icons_callback(HMODULE hModule, LPCWSTR pwszType, LPWSTR pwszName,
260     LONG_PTR lParam) 
261 {
262     struct extract_icons_state *pState = (struct extract_icons_state *)lParam;
263     INT idCurrent = (INT)pwszName;
264
265     /* If the handle array pointer is NULL, we just count the number of icons in the module. */
266     if (!pState->pahIcon) {
267         pState->cIter++;
268         return TRUE;
269     }
270    
271     /* If we didn't already start extracting icons (cIter == 0), we look if the current
272      * icon is the one we should start with. That's the case if nBaseIndex is negative and
273      * it's absolute value matches the current icon's identifier. Or if nBaseIndex is positive
274      * and we already omitted the first nBaseIndex icons. */
275     if (pState->cIter == 0) {
276         if (pState->nBaseIndex < 0) {
277             if (!IS_INTRESOURCE(pwszName) || idCurrent != -pState->nBaseIndex) {
278                 return TRUE;
279             }
280         } else if (pState->nBaseIndex > 0) {
281             pState->nBaseIndex--;
282             return TRUE;
283         }
284     }
285
286     if (pState->cIter < pState->nIcons) {
287         /* Load the current icon with the size given in the LOWORD of cx/cyDesired */
288         pState->pahIcon[pState->cIter] = 
289             LoadImageW(hModule, pwszName, IMAGE_ICON, LOWORD(pState->cxDesired), 
290                        LOWORD(pState->cyDesired), pState->fuLoad);
291         /* FIXME: The resource's identifier (that is not idCurrent, which is the
292          * identifier of the icon directory) should be stored in paIconId, but I don't
293          * know how to query for it. */ 
294         if (pState->paIconId) pState->paIconId[pState->cIter] = 0;
295         pState->cIter++;
296
297         /* If there is a second desired size given in the HIWORDs of cx/cyDesired, load too. 
298          * There seems to be an off-by-one error here, since pState->cIter might now be equal
299          * to pState->nIcons, but this is in fact how it works on windows. */
300         if (HIWORD(pState->cxDesired) && HIWORD(pState->cyDesired)) {
301             pState->pahIcon[pState->cIter] = 
302                 LoadImageW(hModule, pwszName, IMAGE_ICON, HIWORD(pState->cxDesired), 
303                            HIWORD(pState->cyDesired), pState->fuLoad);
304             if (pState->paIconId) pState->paIconId[pState->cIter] = 0;
305             pState->cIter++;
306         }
307     }
308
309     return pState->cIter < pState->nIcons;
310 }
311
312 /*************************************************************************
313  *      ICO_ExtractIconExW              [internal]
314  *
315  * NOTES
316  *  nIcons = 0: returns number of Icons in file
317  *
318  * returns
319  *  invalid file: -1
320  *  failure:0;
321  *  success: number of icons in file (nIcons = 0) or nr of icons retrieved
322  */
323 static UINT ICO_ExtractIconExW(
324         LPCWSTR lpszExeFileName,
325         HICON * RetPtr,
326         INT nIconIndex,
327         UINT nIcons,
328         UINT cxDesired,
329         UINT cyDesired,
330         UINT *pIconId,
331         UINT flags)
332 {
333         UINT            ret = 0;
334         UINT            cx1, cx2, cy1, cy2;
335         LPBYTE          pData;
336         DWORD           sig;
337         HANDLE          hFile;
338         UINT16          iconDirCount = 0,iconCount = 0;
339         LPBYTE          peimage;
340         HANDLE          fmapping;
341         ULONG           uSize;
342         DWORD           fsizeh,fsizel;
343         WCHAR           szExePath[MAX_PATH];
344         DWORD           dwSearchReturn;
345
346         TRACE("%s, %d, %d %p 0x%08x\n", debugstr_w(lpszExeFileName), nIconIndex, nIcons, pIconId, flags);
347
348         dwSearchReturn = SearchPathW(NULL, lpszExeFileName, NULL, sizeof(szExePath) / sizeof(szExePath[0]), szExePath, NULL);
349         if ((dwSearchReturn == 0) || (dwSearchReturn > sizeof(szExePath) / sizeof(szExePath[0])))
350         {
351           /* This is very wine specific: If the user tries to extract icons from system dlls, 
352            * wine's builtin *.dll.so's will not be found (Even if they would be found it wouldn't 
353            * work, since they are not in PE-format). Thus, if the SearchPath call fails, we try
354            * to load the file with LoadLibrary and extract the icons with LoadImage (via
355            * EnumResourceNames).
356            */
357           struct extract_icons_state state;
358           HMODULE hDllSo = LoadLibraryW(lpszExeFileName);
359           
360           if (!hDllSo) {
361             WARN("File %s not found or path too long\n", debugstr_w(lpszExeFileName));
362             return -1;
363           }
364
365           state.nBaseIndex = nIconIndex;
366           state.nIcons = nIcons;
367           state.cxDesired = cxDesired;
368           state.cyDesired = cyDesired;
369           state.fuLoad = flags;
370           state.cIter = 0;
371           state.pahIcon = RetPtr;
372           state.paIconId = pIconId;
373           
374           EnumResourceNamesW(hDllSo, MAKEINTRESOURCEW(RT_GROUP_ICON), extract_icons_callback, 
375                              (LONG_PTR)&state);
376           FreeLibrary(hDllSo);
377   
378           return state.cIter;
379         }
380
381         hFile = CreateFileW(szExePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
382         if (hFile == INVALID_HANDLE_VALUE) return ret;
383         fsizel = GetFileSize(hFile,&fsizeh);
384
385         /* Map the file */
386         fmapping = CreateFileMappingW(hFile, NULL, PAGE_READONLY | SEC_COMMIT, 0, 0, NULL);
387         CloseHandle(hFile);
388         if (!fmapping)
389         {
390           WARN("CreateFileMapping error %d\n", GetLastError() );
391           return 0xFFFFFFFF;
392         }
393
394         if (!(peimage = MapViewOfFile(fmapping, FILE_MAP_READ, 0, 0, 0)))
395         {
396           WARN("MapViewOfFile error %d\n", GetLastError() );
397           CloseHandle(fmapping);
398           return 0xFFFFFFFF;
399         }
400         CloseHandle(fmapping);
401
402         cx1 = LOWORD(cxDesired);
403         cx2 = HIWORD(cxDesired);
404         cy1 = LOWORD(cyDesired);
405         cy2 = HIWORD(cyDesired);
406
407         if (pIconId) /* Invalidate first icon identifier */
408                 *pIconId = 0xFFFFFFFF;
409
410         if (!pIconId) /* if no icon identifier array present use the icon handle array as intermediate storage */
411           pIconId = (UINT*)RetPtr;
412
413         sig = USER32_GetResourceTable(peimage, fsizel, &pData);
414
415 /* ico file or NE exe/dll*/
416         if (sig==IMAGE_OS2_SIGNATURE || sig==1) /* .ICO file */
417         {
418           BYTE          *pCIDir = 0;
419           NE_TYPEINFO   *pTInfo = (NE_TYPEINFO*)(pData + 2);
420           NE_NAMEINFO   *pIconStorage = NULL;
421           NE_NAMEINFO   *pIconDir = NULL;
422           LPicoICONDIR  lpiID = NULL;
423
424           TRACE("-- OS2/icon Signature (0x%08x)\n", sig);
425
426           if (pData == (BYTE*)-1)
427           {
428             pCIDir = ICO_GetIconDirectory(peimage, &lpiID, &uSize);     /* check for .ICO file */
429             if (pCIDir)
430             {
431               iconDirCount = 1; iconCount = lpiID->idCount;
432               TRACE("-- icon found %p 0x%08x 0x%08x 0x%08x\n", pCIDir, uSize, iconDirCount, iconCount);
433             }
434           }
435           else while (pTInfo->type_id && !(pIconStorage && pIconDir))
436           {
437             if (pTInfo->type_id == NE_RSCTYPE_GROUP_ICON)       /* find icon directory and icon repository */
438             {
439               iconDirCount = pTInfo->count;
440               pIconDir = ((NE_NAMEINFO*)(pTInfo + 1));
441               TRACE("\tfound directory - %i icon families\n", iconDirCount);
442             }
443             if (pTInfo->type_id == NE_RSCTYPE_ICON)
444             {
445               iconCount = pTInfo->count;
446               pIconStorage = ((NE_NAMEINFO*)(pTInfo + 1));
447               TRACE("\ttotal icons - %i\n", iconCount);
448             }
449             pTInfo = (NE_TYPEINFO *)((char*)(pTInfo+1)+pTInfo->count*sizeof(NE_NAMEINFO));
450           }
451
452           if ((pIconStorage && pIconDir) || lpiID)        /* load resources and create icons */
453           {
454             if (nIcons == 0)
455             {
456               ret = iconDirCount;
457               if (lpiID)        /* *.ico file, deallocate heap pointer*/
458                 HeapFree(GetProcessHeap(), 0, pCIDir);
459             }
460             else if (nIconIndex < iconDirCount)
461             {
462               UINT16   i, icon;
463               if (nIcons > iconDirCount - nIconIndex)
464                 nIcons = iconDirCount - nIconIndex;
465
466               for (i = 0; i < nIcons; i++)
467               {
468                 /* .ICO files have only one icon directory */
469                 if (lpiID == NULL)      /* not *.ico */
470                   pCIDir = USER32_LoadResource(peimage, pIconDir + i + nIconIndex, *(WORD*)pData, &uSize);
471                 pIconId[i] = LookupIconIdFromDirectoryEx(pCIDir, TRUE, cx1, cy1, flags);
472                 if (cx2 && cy2) pIconId[++i] = LookupIconIdFromDirectoryEx(pCIDir, TRUE,  cx2, cy2, flags);
473               }
474               if (lpiID)        /* *.ico file, deallocate heap pointer*/
475                 HeapFree(GetProcessHeap(), 0, pCIDir);
476
477               for (icon = 0; icon < nIcons; icon++)
478               {
479                 pCIDir = NULL;
480                 if (lpiID)
481                   pCIDir = ICO_LoadIcon(peimage, lpiID->idEntries + (int)pIconId[icon], &uSize);
482                 else
483                   for (i = 0; i < iconCount; i++)
484                     if (pIconStorage[i].id == ((int)pIconId[icon] | 0x8000) )
485                       pCIDir = USER32_LoadResource(peimage, pIconStorage + i, *(WORD*)pData, &uSize);
486
487                 if (pCIDir)
488                 {
489                   RetPtr[icon] = (HICON)CreateIconFromResourceEx(pCIDir, uSize, TRUE, 0x00030000,
490                                                                  cx1, cy1, flags);
491                   if (cx2 && cy2)
492                       RetPtr[++icon] = (HICON)CreateIconFromResourceEx(pCIDir, uSize, TRUE, 0x00030000,
493                                                                        cx2, cy2, flags);
494                 }
495                 else
496                   RetPtr[icon] = 0;
497               }
498               ret = icon;       /* return number of retrieved icons */
499             }
500           }
501         }
502 /* end ico file */
503
504 /* exe/dll */
505         else if( sig == IMAGE_NT_SIGNATURE )
506         {
507           LPBYTE                idata,igdata;
508           PIMAGE_DOS_HEADER     dheader;
509           PIMAGE_NT_HEADERS     pe_header;
510           PIMAGE_SECTION_HEADER pe_sections;
511           const IMAGE_RESOURCE_DIRECTORY *rootresdir,*iconresdir,*icongroupresdir;
512           const IMAGE_RESOURCE_DATA_ENTRY *idataent,*igdataent;
513           const IMAGE_RESOURCE_DIRECTORY_ENTRY *xresent;
514           UINT  i, j;
515
516           dheader = (PIMAGE_DOS_HEADER)peimage;
517           pe_header = (PIMAGE_NT_HEADERS)(peimage+dheader->e_lfanew);     /* it is a pe header, USER32_GetResourceTable checked that */
518           pe_sections = (PIMAGE_SECTION_HEADER)(((char*)pe_header) + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER)
519                                                 + pe_header->FileHeader.SizeOfOptionalHeader);
520           rootresdir = NULL;
521
522           /* search for the root resource directory */
523           for (i=0;i<pe_header->FileHeader.NumberOfSections;i++)
524           {
525             if (pe_sections[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
526               continue;
527             if (fsizel < pe_sections[i].PointerToRawData+pe_sections[i].SizeOfRawData) {
528               FIXME("File %s too short (section is at %d bytes, real size is %d)\n",
529                       debugstr_w(lpszExeFileName),
530                       pe_sections[i].PointerToRawData+pe_sections[i].SizeOfRawData,
531                       fsizel
532               );
533               goto end;
534             }
535             /* FIXME: doesn't work when the resources are not in a separate section */
536             if (pe_sections[i].VirtualAddress == pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress)
537             {
538               rootresdir = (PIMAGE_RESOURCE_DIRECTORY)(peimage+pe_sections[i].PointerToRawData);
539               break;
540             }
541           }
542
543           if (!rootresdir)
544           {
545             WARN("haven't found section for resource directory.\n");
546             goto end;           /* failure */
547           }
548
549           /* search for the group icon directory */
550           if (!(icongroupresdir = find_entry_by_id(rootresdir, LOWORD(RT_GROUP_ICON), rootresdir)))
551           {
552             WARN("No Icongroupresourcedirectory!\n");
553             goto end;           /* failure */
554           }
555           iconDirCount = icongroupresdir->NumberOfNamedEntries + icongroupresdir->NumberOfIdEntries;
556
557           /* only number of icons requested */
558           if( !pIconId )
559           {
560             ret = iconDirCount;
561             goto end;           /* success */
562           }
563
564           if( nIconIndex < 0 )
565           {
566             /* search resource id */
567             int n = 0;
568             int iId = abs(nIconIndex);
569             const IMAGE_RESOURCE_DIRECTORY_ENTRY* xprdeTmp = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(icongroupresdir+1);
570
571             while(n<iconDirCount && xprdeTmp)
572             {
573               if(xprdeTmp->u1.s2.Id ==  iId)
574               {
575                   nIconIndex = n;
576                   break;
577               }
578               n++;
579               xprdeTmp++;
580             }
581             if (nIconIndex < 0)
582             {
583               WARN("resource id %d not found\n", iId);
584               goto end;         /* failure */
585             }
586           }
587           else
588           {
589             /* check nIconIndex to be in range */
590             if (nIconIndex >= iconDirCount)
591             {
592               WARN("nIconIndex %d is larger than iconDirCount %d\n",nIconIndex,iconDirCount);
593               goto end;         /* failure */
594             }
595           }
596
597           /* assure we don't get too much */
598           if( nIcons > iconDirCount - nIconIndex )
599             nIcons = iconDirCount - nIconIndex;
600
601           /* starting from specified index */
602           xresent = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(icongroupresdir+1) + nIconIndex;
603
604           for (i=0; i < nIcons; i++,xresent++)
605           {
606             const IMAGE_RESOURCE_DIRECTORY *resdir;
607
608             /* go down this resource entry, name */
609             resdir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)rootresdir + xresent->u2.s3.OffsetToDirectory);
610
611             /* default language (0) */
612             resdir = find_entry_default(resdir,rootresdir);
613             igdataent = (const IMAGE_RESOURCE_DATA_ENTRY*)resdir;
614
615             /* lookup address in mapped image for virtual address */
616             igdata = NULL;
617
618             for (j=0;j<pe_header->FileHeader.NumberOfSections;j++)
619             {
620               if (igdataent->OffsetToData < pe_sections[j].VirtualAddress)
621                 continue;
622               if (igdataent->OffsetToData+igdataent->Size > pe_sections[j].VirtualAddress+pe_sections[j].SizeOfRawData)
623                 continue;
624
625               if (igdataent->OffsetToData-pe_sections[j].VirtualAddress+pe_sections[j].PointerToRawData+igdataent->Size > fsizel) {
626                 FIXME("overflow in PE lookup (%s has len %d, have offset %d), short file?\n", debugstr_w(lpszExeFileName), fsizel,
627                            igdataent->OffsetToData - pe_sections[j].VirtualAddress + pe_sections[j].PointerToRawData + igdataent->Size);
628                 goto end; /* failure */
629               }
630               igdata = peimage+(igdataent->OffsetToData-pe_sections[j].VirtualAddress+pe_sections[j].PointerToRawData);
631             }
632
633             if (!igdata)
634             {
635               FIXME("no matching real address for icongroup!\n");
636               goto end; /* failure */
637             }
638             pIconId[i] = LookupIconIdFromDirectoryEx(igdata, TRUE, cx1, cy1, flags);
639             if (cx2 && cy2) pIconId[++i] = LookupIconIdFromDirectoryEx(igdata, TRUE, cx2, cy2, flags);
640           }
641
642           if (!(iconresdir=find_entry_by_id(rootresdir,LOWORD(RT_ICON),rootresdir)))
643           {
644             WARN("No Iconresourcedirectory!\n");
645             goto end;           /* failure */
646           }
647
648           for (i=0; i<nIcons; i++)
649           {
650             const IMAGE_RESOURCE_DIRECTORY *xresdir;
651             xresdir = find_entry_by_id(iconresdir, LOWORD(pIconId[i]), rootresdir);
652             if( !xresdir )
653             {
654               WARN("icon entry %d not found\n", LOWORD(pIconId[i]));
655               RetPtr[i]=0;
656               continue;
657             }
658             xresdir = find_entry_default(xresdir, rootresdir);
659             idataent = (const IMAGE_RESOURCE_DATA_ENTRY*)xresdir;
660             idata = NULL;
661
662             /* map virtual to address in image */
663             for (j=0;j<pe_header->FileHeader.NumberOfSections;j++)
664             {
665               if (idataent->OffsetToData < pe_sections[j].VirtualAddress)
666                 continue;
667               if (idataent->OffsetToData+idataent->Size > pe_sections[j].VirtualAddress+pe_sections[j].SizeOfRawData)
668                 continue;
669               idata = peimage+(idataent->OffsetToData-pe_sections[j].VirtualAddress+pe_sections[j].PointerToRawData);
670             }
671             if (!idata)
672             {
673               WARN("no matching real address found for icondata!\n");
674               RetPtr[i]=0;
675               continue;
676             }
677             RetPtr[i] = (HICON) CreateIconFromResourceEx(idata,idataent->Size,TRUE,0x00030000,
678                                                          cx1, cy1, flags);
679             if (cx2 && cy2)
680                 RetPtr[++i] = (HICON) CreateIconFromResourceEx(idata,idataent->Size,TRUE,0x00030000,
681                                                                cx2, cy2, flags);
682           }
683           ret = i;      /* return number of retrieved icons */
684         }                       /* if(sig == IMAGE_NT_SIGNATURE) */
685
686 end:
687         UnmapViewOfFile(peimage);       /* success */
688         return ret;
689 }
690
691 /***********************************************************************
692  *           PrivateExtractIconsW                       [USER32.@]
693  *
694  * NOTES
695  *  If HIWORD(sizeX) && HIWORD(sizeY) 2 * ((nIcons + 1) MOD 2) icons are
696  *  returned, with the LOWORD size icon first and the HIWORD size icon
697  *  second.
698  *  Also the Windows equivalent does extract icons in a strange way if
699  *  nIndex is negative. Our implementation treats a negative nIndex as
700  *  looking for that resource identifier for the first icon to retrieve.
701  *
702  * FIXME:
703  *  should also support 16 bit EXE + DLLs, cursor and animated cursor as
704  *  well as bitmap files.
705  */
706
707 UINT WINAPI PrivateExtractIconsW (
708         LPCWSTR lpwstrFile,
709         int nIndex,
710         int sizeX,
711         int sizeY,
712         HICON * phicon, /* [out] pointer to array of nIcons HICON handles */
713         UINT* pIconId,  /* [out] pointer to array of nIcons icon identifiers or NULL */
714         UINT nIcons,    /* [in] number of icons to retrieve */
715         UINT flags )    /* [in] LR_* flags used by LoadImage */
716 {
717         TRACE("%s %d %dx%d %p %p %d 0x%08x\n",
718               debugstr_w(lpwstrFile), nIndex, sizeX, sizeY, phicon, pIconId, nIcons, flags);
719
720         if ((nIcons & 1) && HIWORD(sizeX) && HIWORD(sizeY))
721         {
722           WARN("Uneven number %d of icons requested for small and large icons!\n", nIcons);
723         }
724         return ICO_ExtractIconExW(lpwstrFile, phicon, nIndex, nIcons, sizeX, sizeY, pIconId, flags);
725 }
726
727 /***********************************************************************
728  *           PrivateExtractIconsA                       [USER32.@]
729  */
730
731 UINT WINAPI PrivateExtractIconsA (
732         LPCSTR lpstrFile,
733         int nIndex,
734         int sizeX,
735         int sizeY,
736         HICON * phicon, /* [out] pointer to array of nIcons HICON handles */
737         UINT* piconid,  /* [out] pointer to array of nIcons icon identifiers or NULL */
738         UINT nIcons,    /* [in] number of icons to retrieve */
739         UINT flags )    /* [in] LR_* flags used by LoadImage */
740 {
741     UINT ret;
742     INT len = MultiByteToWideChar(CP_ACP, 0, lpstrFile, -1, NULL, 0);
743     LPWSTR lpwstrFile = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
744
745     MultiByteToWideChar(CP_ACP, 0, lpstrFile, -1, lpwstrFile, len);
746     ret = PrivateExtractIconsW(lpwstrFile, nIndex, sizeX, sizeY, phicon, piconid, nIcons, flags);
747
748     HeapFree(GetProcessHeap(), 0, lpwstrFile);
749     return ret;
750 }
751
752 /***********************************************************************
753  *           PrivateExtractIconExW                      [USER32.@]
754  * NOTES
755  *  if nIndex == -1 it returns the number of icons in any case !!!
756  */
757 UINT WINAPI PrivateExtractIconExW (
758         LPCWSTR lpwstrFile,
759         int nIndex,
760         HICON * phIconLarge,
761         HICON * phIconSmall,
762         UINT nIcons )
763 {
764         DWORD cyicon, cysmicon, cxicon, cxsmicon;
765         UINT ret = 0;
766
767         TRACE("%s %d %p %p %d\n",
768         debugstr_w(lpwstrFile),nIndex,phIconLarge, phIconSmall, nIcons);
769
770         if (nIndex == -1)
771           /* get the number of icons */
772           return ICO_ExtractIconExW(lpwstrFile, NULL, 0, 0, 0, 0, NULL, LR_DEFAULTCOLOR);
773
774         if (nIcons == 1 && phIconSmall && phIconLarge)
775         {
776           HICON hIcon[2];
777           cxicon = GetSystemMetrics(SM_CXICON);
778           cyicon = GetSystemMetrics(SM_CYICON);
779           cxsmicon = GetSystemMetrics(SM_CXSMICON);
780           cysmicon = GetSystemMetrics(SM_CYSMICON);
781
782           ret = ICO_ExtractIconExW(lpwstrFile, (HICON*) &hIcon, nIndex, 2, cxicon | (cxsmicon<<16),
783                                    cyicon | (cysmicon<<16), NULL, LR_DEFAULTCOLOR);
784           *phIconLarge = hIcon[0];
785           *phIconSmall = hIcon[1];
786           return ret;
787         }
788
789         if (phIconSmall)
790         {
791           /* extract n small icons */
792           cxsmicon = GetSystemMetrics(SM_CXSMICON);
793           cysmicon = GetSystemMetrics(SM_CYSMICON);
794           ret = ICO_ExtractIconExW(lpwstrFile, phIconSmall, nIndex, nIcons, cxsmicon,
795                                    cysmicon, NULL, LR_DEFAULTCOLOR);
796         }
797        if (phIconLarge)
798         {
799           /* extract n large icons */
800           cxicon = GetSystemMetrics(SM_CXICON);
801           cyicon = GetSystemMetrics(SM_CYICON);
802          ret = ICO_ExtractIconExW(lpwstrFile, phIconLarge, nIndex, nIcons, cxicon,
803                                    cyicon, NULL, LR_DEFAULTCOLOR);
804         }
805         return ret;
806 }
807
808 /***********************************************************************
809  *           PrivateExtractIconExA                      [USER32.@]
810  */
811 UINT WINAPI PrivateExtractIconExA (
812         LPCSTR lpstrFile,
813         int nIndex,
814         HICON * phIconLarge,
815         HICON * phIconSmall,
816         UINT nIcons )
817 {
818         UINT ret;
819         INT len = MultiByteToWideChar(CP_ACP, 0, lpstrFile, -1, NULL, 0);
820         LPWSTR lpwstrFile = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR));
821
822         TRACE("%s %d %p %p %d\n", lpstrFile, nIndex, phIconLarge, phIconSmall, nIcons);
823
824         MultiByteToWideChar(CP_ACP, 0, lpstrFile, -1, lpwstrFile, len);
825         ret = PrivateExtractIconExW(lpwstrFile, nIndex, phIconLarge, phIconSmall, nIcons);
826         HeapFree(GetProcessHeap(), 0, lpwstrFile);
827         return ret;
828 }