user32: Remove some explicit LPARAM/WPARAM casts.
[wine] / dlls / kernel32 / resource.c
1 /*
2  * Resources
3  *
4  * Copyright 1993 Robert J. Amstadt
5  * Copyright 1995, 2003 Alexandre Julliard
6  * Copyright 2006 Mike McCormack
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include <stdarg.h>
27
28 #define NONAMELESSUNION
29 #define NONAMELESSSTRUCT
30 #include "ntstatus.h"
31 #define WIN32_NO_STATUS
32 #include "windef.h"
33 #include "winbase.h"
34 #include "winternl.h"
35 #include "wine/winbase16.h"
36 #include "wine/debug.h"
37 #include "wine/exception.h"
38 #include "wine/unicode.h"
39 #include "wine/list.h"
40
41 WINE_DEFAULT_DEBUG_CHANNEL(resource);
42
43 /* handle conversions */
44 #define HRSRC_32(h16)   ((HRSRC)(ULONG_PTR)(h16))
45 #define HRSRC_16(h32)   (LOWORD(h32))
46 #define HGLOBAL_32(h16) ((HGLOBAL)(ULONG_PTR)(h16))
47 #define HGLOBAL_16(h32) (LOWORD(h32))
48 #define HMODULE_16(h32) (LOWORD(h32))
49
50 /* retrieve the resource name to pass to the ntdll functions */
51 static NTSTATUS get_res_nameA( LPCSTR name, UNICODE_STRING *str )
52 {
53     if (!HIWORD(name))
54     {
55         str->Buffer = ULongToPtr(LOWORD(name));
56         return STATUS_SUCCESS;
57     }
58     if (name[0] == '#')
59     {
60         ULONG value;
61         if (RtlCharToInteger( name + 1, 10, &value ) != STATUS_SUCCESS || HIWORD(value))
62             return STATUS_INVALID_PARAMETER;
63         str->Buffer = ULongToPtr(value);
64         return STATUS_SUCCESS;
65     }
66     RtlCreateUnicodeStringFromAsciiz( str, name );
67     RtlUpcaseUnicodeString( str, str, FALSE );
68     return STATUS_SUCCESS;
69 }
70
71 /* retrieve the resource name to pass to the ntdll functions */
72 static NTSTATUS get_res_nameW( LPCWSTR name, UNICODE_STRING *str )
73 {
74     if (!HIWORD(name))
75     {
76         str->Buffer = ULongToPtr(LOWORD(name));
77         return STATUS_SUCCESS;
78     }
79     if (name[0] == '#')
80     {
81         ULONG value;
82         RtlInitUnicodeString( str, name + 1 );
83         if (RtlUnicodeStringToInteger( str, 10, &value ) != STATUS_SUCCESS || HIWORD(value))
84             return STATUS_INVALID_PARAMETER;
85         str->Buffer = ULongToPtr(value);
86         return STATUS_SUCCESS;
87     }
88     RtlCreateUnicodeString( str, name );
89     RtlUpcaseUnicodeString( str, str, FALSE );
90     return STATUS_SUCCESS;
91 }
92
93 /* retrieve the resource names for the 16-bit FindResource function */
94 static BOOL get_res_name_type_WtoA( LPCWSTR name, LPCWSTR type, LPSTR *nameA, LPSTR *typeA )
95 {
96     *nameA = *typeA = NULL;
97
98     __TRY
99     {
100         if (HIWORD(name))
101         {
102             DWORD len = WideCharToMultiByte( CP_ACP, 0, name, -1, NULL, 0, NULL, NULL );
103             *nameA = HeapAlloc( GetProcessHeap(), 0, len );
104             if (*nameA) WideCharToMultiByte( CP_ACP, 0, name, -1, *nameA, len, NULL, NULL );
105         }
106         else *nameA = ULongToPtr(LOWORD(name));
107
108         if (HIWORD(type))
109         {
110             DWORD len = WideCharToMultiByte( CP_ACP, 0, type, -1, NULL, 0, NULL, NULL );
111             *typeA = HeapAlloc( GetProcessHeap(), 0, len );
112             if (*typeA) WideCharToMultiByte( CP_ACP, 0, type, -1, *typeA, len, NULL, NULL );
113         }
114         else *typeA = ULongToPtr(LOWORD(type));
115     }
116     __EXCEPT_PAGE_FAULT
117     {
118         if (HIWORD(*nameA)) HeapFree( GetProcessHeap(), 0, *nameA );
119         if (HIWORD(*typeA)) HeapFree( GetProcessHeap(), 0, *typeA );
120         SetLastError( ERROR_INVALID_PARAMETER );
121         return FALSE;
122     }
123     __ENDTRY
124     return TRUE;
125 }
126
127 /* implementation of FindResourceExA */
128 static HRSRC find_resourceA( HMODULE hModule, LPCSTR type, LPCSTR name, WORD lang )
129 {
130     NTSTATUS status;
131     UNICODE_STRING nameW, typeW;
132     LDR_RESOURCE_INFO info;
133     const IMAGE_RESOURCE_DATA_ENTRY *entry = NULL;
134
135     nameW.Buffer = NULL;
136     typeW.Buffer = NULL;
137
138     __TRY
139     {
140         if ((status = get_res_nameA( name, &nameW )) != STATUS_SUCCESS) goto done;
141         if ((status = get_res_nameA( type, &typeW )) != STATUS_SUCCESS) goto done;
142         info.Type = (ULONG_PTR)typeW.Buffer;
143         info.Name = (ULONG_PTR)nameW.Buffer;
144         info.Language = lang;
145         status = LdrFindResource_U( hModule, &info, 3, &entry );
146     done:
147         if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
148     }
149     __EXCEPT_PAGE_FAULT
150     {
151         SetLastError( ERROR_INVALID_PARAMETER );
152     }
153     __ENDTRY
154
155     if (HIWORD(nameW.Buffer)) HeapFree( GetProcessHeap(), 0, nameW.Buffer );
156     if (HIWORD(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
157     return (HRSRC)entry;
158 }
159
160
161 /* implementation of FindResourceExW */
162 static HRSRC find_resourceW( HMODULE hModule, LPCWSTR type, LPCWSTR name, WORD lang )
163 {
164     NTSTATUS status;
165     UNICODE_STRING nameW, typeW;
166     LDR_RESOURCE_INFO info;
167     const IMAGE_RESOURCE_DATA_ENTRY *entry = NULL;
168
169     nameW.Buffer = typeW.Buffer = NULL;
170
171     __TRY
172     {
173         if ((status = get_res_nameW( name, &nameW )) != STATUS_SUCCESS) goto done;
174         if ((status = get_res_nameW( type, &typeW )) != STATUS_SUCCESS) goto done;
175         info.Type = (ULONG_PTR)typeW.Buffer;
176         info.Name = (ULONG_PTR)nameW.Buffer;
177         info.Language = lang;
178         status = LdrFindResource_U( hModule, &info, 3, &entry );
179     done:
180         if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
181     }
182     __EXCEPT_PAGE_FAULT
183     {
184         SetLastError( ERROR_INVALID_PARAMETER );
185     }
186     __ENDTRY
187
188     if (HIWORD(nameW.Buffer)) HeapFree( GetProcessHeap(), 0, nameW.Buffer );
189     if (HIWORD(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
190     return (HRSRC)entry;
191 }
192
193 /**********************************************************************
194  *          FindResourceExA  (KERNEL32.@)
195  */
196 HRSRC WINAPI FindResourceExA( HMODULE hModule, LPCSTR type, LPCSTR name, WORD lang )
197 {
198     TRACE( "%p %s %s %04x\n", hModule, debugstr_a(type), debugstr_a(name), lang );
199
200     if (!hModule) hModule = GetModuleHandleW(0);
201     else if (!HIWORD(hModule))
202     {
203         return HRSRC_32( FindResource16( HMODULE_16(hModule), name, type ) );
204     }
205     return find_resourceA( hModule, type, name, lang );
206 }
207
208
209 /**********************************************************************
210  *          FindResourceA    (KERNEL32.@)
211  */
212 HRSRC WINAPI FindResourceA( HMODULE hModule, LPCSTR name, LPCSTR type )
213 {
214     return FindResourceExA( hModule, type, name, MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL ) );
215 }
216
217
218 /**********************************************************************
219  *          FindResourceExW  (KERNEL32.@)
220  */
221 HRSRC WINAPI FindResourceExW( HMODULE hModule, LPCWSTR type, LPCWSTR name, WORD lang )
222 {
223     TRACE( "%p %s %s %04x\n", hModule, debugstr_w(type), debugstr_w(name), lang );
224
225     if (!hModule) hModule = GetModuleHandleW(0);
226     else if (!HIWORD(hModule))
227     {
228         LPSTR nameA, typeA;
229         HRSRC16 ret;
230
231         if (!get_res_name_type_WtoA( name, type, &nameA, &typeA )) return NULL;
232
233         ret = FindResource16( HMODULE_16(hModule), nameA, typeA );
234         if (HIWORD(nameA)) HeapFree( GetProcessHeap(), 0, nameA );
235         if (HIWORD(typeA)) HeapFree( GetProcessHeap(), 0, typeA );
236         return HRSRC_32(ret);
237     }
238
239     return find_resourceW( hModule, type, name, lang );
240 }
241
242
243 /**********************************************************************
244  *          FindResourceW    (KERNEL32.@)
245  */
246 HRSRC WINAPI FindResourceW( HINSTANCE hModule, LPCWSTR name, LPCWSTR type )
247 {
248     return FindResourceExW( hModule, type, name, MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL ) );
249 }
250
251
252 /**********************************************************************
253  *      EnumResourceTypesA      (KERNEL32.@)
254  */
255 BOOL WINAPI EnumResourceTypesA( HMODULE hmod, ENUMRESTYPEPROCA lpfun, LONG_PTR lparam )
256 {
257     int i;
258     BOOL ret = FALSE;
259     LPSTR type = NULL;
260     DWORD len = 0, newlen;
261     NTSTATUS status;
262     const IMAGE_RESOURCE_DIRECTORY *resdir;
263     const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
264     const IMAGE_RESOURCE_DIR_STRING_U *str;
265
266     TRACE( "%p %p %lx\n", hmod, lpfun, lparam );
267
268     if (!hmod) hmod = GetModuleHandleA( NULL );
269
270     if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &resdir )) != STATUS_SUCCESS)
271     {
272         SetLastError( RtlNtStatusToDosError(status) );
273         return FALSE;
274     }
275     et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
276     for (i = 0; i < resdir->NumberOfNamedEntries+resdir->NumberOfIdEntries; i++)
277     {
278         if (et[i].u1.s1.NameIsString)
279         {
280             str = (const IMAGE_RESOURCE_DIR_STRING_U *)((const BYTE *)resdir + et[i].u1.s1.NameOffset);
281             newlen = WideCharToMultiByte( CP_ACP, 0, str->NameString, str->Length, NULL, 0, NULL, NULL);
282             if (newlen + 1 > len)
283             {
284                 len = newlen + 1;
285                 HeapFree( GetProcessHeap(), 0, type );
286                 if (!(type = HeapAlloc( GetProcessHeap(), 0, len ))) return FALSE;
287             }
288             WideCharToMultiByte( CP_ACP, 0, str->NameString, str->Length, type, len, NULL, NULL);
289             type[newlen] = 0;
290             ret = lpfun(hmod,type,lparam);
291         }
292         else
293         {
294             ret = lpfun( hmod, UIntToPtr(et[i].u1.s2.Id), lparam );
295         }
296         if (!ret) break;
297     }
298     HeapFree( GetProcessHeap(), 0, type );
299     return ret;
300 }
301
302
303 /**********************************************************************
304  *      EnumResourceTypesW      (KERNEL32.@)
305  */
306 BOOL WINAPI EnumResourceTypesW( HMODULE hmod, ENUMRESTYPEPROCW lpfun, LONG_PTR lparam )
307 {
308     int i, len = 0;
309     BOOL ret = FALSE;
310     LPWSTR type = NULL;
311     NTSTATUS status;
312     const IMAGE_RESOURCE_DIRECTORY *resdir;
313     const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
314     const IMAGE_RESOURCE_DIR_STRING_U *str;
315
316     TRACE( "%p %p %lx\n", hmod, lpfun, lparam );
317
318     if (!hmod) hmod = GetModuleHandleW( NULL );
319
320     if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &resdir )) != STATUS_SUCCESS)
321     {
322         SetLastError( RtlNtStatusToDosError(status) );
323         return FALSE;
324     }
325     et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
326     for (i = 0; i < resdir->NumberOfNamedEntries + resdir->NumberOfIdEntries; i++)
327     {
328         if (et[i].u1.s1.NameIsString)
329         {
330             str = (const IMAGE_RESOURCE_DIR_STRING_U *)((const BYTE *)resdir + et[i].u1.s1.NameOffset);
331             if (str->Length + 1 > len)
332             {
333                 len = str->Length + 1;
334                 HeapFree( GetProcessHeap(), 0, type );
335                 if (!(type = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) ))) return FALSE;
336             }
337             memcpy(type, str->NameString, str->Length * sizeof (WCHAR));
338             type[str->Length] = 0;
339             ret = lpfun(hmod,type,lparam);
340         }
341         else
342         {
343             ret = lpfun( hmod, UIntToPtr(et[i].u1.s2.Id), lparam );
344         }
345         if (!ret) break;
346     }
347     HeapFree( GetProcessHeap(), 0, type );
348     return ret;
349 }
350
351
352 /**********************************************************************
353  *      EnumResourceNamesA      (KERNEL32.@)
354  */
355 BOOL WINAPI EnumResourceNamesA( HMODULE hmod, LPCSTR type, ENUMRESNAMEPROCA lpfun, LONG_PTR lparam )
356 {
357     int i;
358     BOOL ret = FALSE;
359     DWORD len = 0, newlen;
360     LPSTR name = NULL;
361     NTSTATUS status;
362     UNICODE_STRING typeW;
363     LDR_RESOURCE_INFO info;
364     const IMAGE_RESOURCE_DIRECTORY *basedir, *resdir;
365     const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
366     const IMAGE_RESOURCE_DIR_STRING_U *str;
367
368     TRACE( "%p %s %p %lx\n", hmod, debugstr_a(type), lpfun, lparam );
369
370     if (!hmod) hmod = GetModuleHandleA( NULL );
371     typeW.Buffer = NULL;
372     if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &basedir )) != STATUS_SUCCESS)
373         goto done;
374     if ((status = get_res_nameA( type, &typeW )) != STATUS_SUCCESS)
375         goto done;
376     info.Type = (ULONG_PTR)typeW.Buffer;
377     if ((status = LdrFindResourceDirectory_U( hmod, &info, 1, &resdir )) != STATUS_SUCCESS)
378         goto done;
379
380     et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
381     __TRY
382     {
383         for (i = 0; i < resdir->NumberOfNamedEntries+resdir->NumberOfIdEntries; i++)
384         {
385             if (et[i].u1.s1.NameIsString)
386             {
387                 str = (const IMAGE_RESOURCE_DIR_STRING_U *)((const BYTE *)basedir + et[i].u1.s1.NameOffset);
388                 newlen = WideCharToMultiByte(CP_ACP, 0, str->NameString, str->Length, NULL, 0, NULL, NULL);
389                 if (newlen + 1 > len)
390                 {
391                     len = newlen + 1;
392                     HeapFree( GetProcessHeap(), 0, name );
393                     if (!(name = HeapAlloc(GetProcessHeap(), 0, len + 1 )))
394                     {
395                         ret = FALSE;
396                         break;
397                     }
398                 }
399                 WideCharToMultiByte( CP_ACP, 0, str->NameString, str->Length, name, len, NULL, NULL );
400                 name[newlen] = 0;
401                 ret = lpfun(hmod,type,name,lparam);
402             }
403             else
404             {
405                 ret = lpfun( hmod, type, UIntToPtr(et[i].u1.s2.Id), lparam );
406             }
407             if (!ret) break;
408         }
409     }
410     __EXCEPT_PAGE_FAULT
411     {
412         ret = FALSE;
413         status = STATUS_ACCESS_VIOLATION;
414     }
415     __ENDTRY
416
417 done:
418     HeapFree( GetProcessHeap(), 0, name );
419     if (HIWORD(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
420     if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
421     return ret;
422 }
423
424
425 /**********************************************************************
426  *      EnumResourceNamesW      (KERNEL32.@)
427  */
428 BOOL WINAPI EnumResourceNamesW( HMODULE hmod, LPCWSTR type, ENUMRESNAMEPROCW lpfun, LONG_PTR lparam )
429 {
430     int i, len = 0;
431     BOOL ret = FALSE;
432     LPWSTR name = NULL;
433     NTSTATUS status;
434     UNICODE_STRING typeW;
435     LDR_RESOURCE_INFO info;
436     const IMAGE_RESOURCE_DIRECTORY *basedir, *resdir;
437     const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
438     const IMAGE_RESOURCE_DIR_STRING_U *str;
439
440     TRACE( "%p %s %p %lx\n", hmod, debugstr_w(type), lpfun, lparam );
441
442     if (!hmod) hmod = GetModuleHandleW( NULL );
443     typeW.Buffer = NULL;
444     if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &basedir )) != STATUS_SUCCESS)
445         goto done;
446     if ((status = get_res_nameW( type, &typeW )) != STATUS_SUCCESS)
447         goto done;
448     info.Type = (ULONG_PTR)typeW.Buffer;
449     if ((status = LdrFindResourceDirectory_U( hmod, &info, 1, &resdir )) != STATUS_SUCCESS)
450         goto done;
451
452     et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
453     __TRY
454     {
455         for (i = 0; i < resdir->NumberOfNamedEntries+resdir->NumberOfIdEntries; i++)
456         {
457             if (et[i].u1.s1.NameIsString)
458             {
459                 str = (const IMAGE_RESOURCE_DIR_STRING_U *)((const BYTE *)basedir + et[i].u1.s1.NameOffset);
460                 if (str->Length + 1 > len)
461                 {
462                     len = str->Length + 1;
463                     HeapFree( GetProcessHeap(), 0, name );
464                     if (!(name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
465                     {
466                         ret = FALSE;
467                         break;
468                     }
469                 }
470                 memcpy(name, str->NameString, str->Length * sizeof (WCHAR));
471                 name[str->Length] = 0;
472                 ret = lpfun(hmod,type,name,lparam);
473             }
474             else
475             {
476                 ret = lpfun( hmod, type, UIntToPtr(et[i].u1.s2.Id), lparam );
477             }
478             if (!ret) break;
479         }
480     }
481     __EXCEPT_PAGE_FAULT
482     {
483         ret = FALSE;
484         status = STATUS_ACCESS_VIOLATION;
485     }
486     __ENDTRY
487 done:
488     HeapFree( GetProcessHeap(), 0, name );
489     if (HIWORD(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
490     if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
491     return ret;
492 }
493
494
495 /**********************************************************************
496  *      EnumResourceLanguagesA  (KERNEL32.@)
497  */
498 BOOL WINAPI EnumResourceLanguagesA( HMODULE hmod, LPCSTR type, LPCSTR name,
499                                     ENUMRESLANGPROCA lpfun, LONG_PTR lparam )
500 {
501     int i;
502     BOOL ret = FALSE;
503     NTSTATUS status;
504     UNICODE_STRING typeW, nameW;
505     LDR_RESOURCE_INFO info;
506     const IMAGE_RESOURCE_DIRECTORY *basedir, *resdir;
507     const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
508
509     TRACE( "%p %s %s %p %lx\n", hmod, debugstr_a(type), debugstr_a(name), lpfun, lparam );
510
511     if (!hmod) hmod = GetModuleHandleA( NULL );
512     typeW.Buffer = nameW.Buffer = NULL;
513     if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &basedir )) != STATUS_SUCCESS)
514         goto done;
515     if ((status = get_res_nameA( type, &typeW )) != STATUS_SUCCESS)
516         goto done;
517     if ((status = get_res_nameA( name, &nameW )) != STATUS_SUCCESS)
518         goto done;
519     info.Type = (ULONG_PTR)typeW.Buffer;
520     info.Name = (ULONG_PTR)nameW.Buffer;
521     if ((status = LdrFindResourceDirectory_U( hmod, &info, 2, &resdir )) != STATUS_SUCCESS)
522         goto done;
523
524     et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
525     __TRY
526     {
527         for (i = 0; i < resdir->NumberOfNamedEntries + resdir->NumberOfIdEntries; i++)
528         {
529             ret = lpfun( hmod, type, name, et[i].u1.s2.Id, lparam );
530             if (!ret) break;
531         }
532     }
533     __EXCEPT_PAGE_FAULT
534     {
535         ret = FALSE;
536         status = STATUS_ACCESS_VIOLATION;
537     }
538     __ENDTRY
539 done:
540     if (HIWORD(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
541     if (HIWORD(nameW.Buffer)) HeapFree( GetProcessHeap(), 0, nameW.Buffer );
542     if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
543     return ret;
544 }
545
546
547 /**********************************************************************
548  *      EnumResourceLanguagesW  (KERNEL32.@)
549  */
550 BOOL WINAPI EnumResourceLanguagesW( HMODULE hmod, LPCWSTR type, LPCWSTR name,
551                                     ENUMRESLANGPROCW lpfun, LONG_PTR lparam )
552 {
553     int i;
554     BOOL ret = FALSE;
555     NTSTATUS status;
556     UNICODE_STRING typeW, nameW;
557     LDR_RESOURCE_INFO info;
558     const IMAGE_RESOURCE_DIRECTORY *basedir, *resdir;
559     const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
560
561     TRACE( "%p %s %s %p %lx\n", hmod, debugstr_w(type), debugstr_w(name), lpfun, lparam );
562
563     if (!hmod) hmod = GetModuleHandleW( NULL );
564     typeW.Buffer = nameW.Buffer = NULL;
565     if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &basedir )) != STATUS_SUCCESS)
566         goto done;
567     if ((status = get_res_nameW( type, &typeW )) != STATUS_SUCCESS)
568         goto done;
569     if ((status = get_res_nameW( name, &nameW )) != STATUS_SUCCESS)
570         goto done;
571     info.Type = (ULONG_PTR)typeW.Buffer;
572     info.Name = (ULONG_PTR)nameW.Buffer;
573     if ((status = LdrFindResourceDirectory_U( hmod, &info, 2, &resdir )) != STATUS_SUCCESS)
574         goto done;
575
576     et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
577     __TRY
578     {
579         for (i = 0; i < resdir->NumberOfNamedEntries + resdir->NumberOfIdEntries; i++)
580         {
581             ret = lpfun( hmod, type, name, et[i].u1.s2.Id, lparam );
582             if (!ret) break;
583         }
584     }
585     __EXCEPT_PAGE_FAULT
586     {
587         ret = FALSE;
588         status = STATUS_ACCESS_VIOLATION;
589     }
590     __ENDTRY
591 done:
592     if (HIWORD(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
593     if (HIWORD(nameW.Buffer)) HeapFree( GetProcessHeap(), 0, nameW.Buffer );
594     if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
595     return ret;
596 }
597
598
599 /**********************************************************************
600  *          LoadResource     (KERNEL32.@)
601  */
602 HGLOBAL WINAPI LoadResource( HINSTANCE hModule, HRSRC hRsrc )
603 {
604     NTSTATUS status;
605     void *ret = NULL;
606
607     TRACE( "%p %p\n", hModule, hRsrc );
608
609     if (hModule && !HIWORD(hModule))
610         /* FIXME: should convert return to 32-bit resource */
611         return HGLOBAL_32( LoadResource16( HMODULE_16(hModule), HRSRC_16(hRsrc) ) );
612
613     if (!hRsrc) return 0;
614     if (!hModule) hModule = GetModuleHandleA( NULL );
615     status = LdrAccessResource( hModule, (IMAGE_RESOURCE_DATA_ENTRY *)hRsrc, &ret, NULL );
616     if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
617     return ret;
618 }
619
620
621 /**********************************************************************
622  *          LockResource     (KERNEL32.@)
623  */
624 LPVOID WINAPI LockResource( HGLOBAL handle )
625 {
626     TRACE("(%p)\n", handle );
627
628     if (HIWORD( handle ))  /* 32-bit memory handle */
629         return handle;
630
631     /* 16-bit memory handle */
632     return LockResource16( HGLOBAL_16(handle) );
633 }
634
635
636 /**********************************************************************
637  *          FreeResource     (KERNEL32.@)
638  */
639 BOOL WINAPI FreeResource( HGLOBAL handle )
640 {
641     if (HIWORD(handle)) return 0; /* 32-bit memory handle: nothing to do */
642     return FreeResource16( HGLOBAL_16(handle) );
643 }
644
645
646 /**********************************************************************
647  *          SizeofResource   (KERNEL32.@)
648  */
649 DWORD WINAPI SizeofResource( HINSTANCE hModule, HRSRC hRsrc )
650 {
651     if (hModule && !HIWORD(hModule))
652         return SizeofResource16( HMODULE_16(hModule), HRSRC_16(hRsrc) );
653
654     if (!hRsrc) return 0;
655     return ((PIMAGE_RESOURCE_DATA_ENTRY)hRsrc)->Size;
656 }
657
658 /*
659  *  Data structure for updating resources.
660  *  Type/Name/Language is a keyset for accessing resource data.
661  *
662  *  QUEUEDUPDATES (root) ->
663  *    list of struct resource_dir_entry    (Type) ->
664  *      list of struct resource_dir_entry  (Name)   ->
665  *         list of struct resource_data    Language + Data
666  */
667
668 typedef struct
669 {
670     LPWSTR pFileName;
671     BOOL bDeleteExistingResources;
672     struct list root;
673 } QUEUEDUPDATES;
674
675 /* this structure is shared for types and names */
676 struct resource_dir_entry {
677     struct list entry;
678     LPWSTR id;
679     struct list children;
680 };
681
682 /* this structure is the leaf */
683 struct resource_data {
684     struct list entry;
685     LANGID lang;
686     DWORD codepage;
687     DWORD cbData;
688     void *lpData;
689 };
690
691 static int resource_strcmp( LPCWSTR a, LPCWSTR b )
692 {
693     if ( a == b )
694         return 0;
695     if (HIWORD( a ) && HIWORD( b ) )
696         return lstrcmpW( a, b );
697     /* strings come before ids */
698     if (HIWORD( a ) && !HIWORD( b ))
699         return -1;
700     if (HIWORD( b ) && !HIWORD( a ))
701         return 1;
702     return ( a < b ) ? -1 : 1;
703 }
704
705 static struct resource_dir_entry *find_resource_dir_entry( struct list *dir, LPCWSTR id )
706 {
707     struct resource_dir_entry *ent;
708
709     /* match either IDs or strings */
710     LIST_FOR_EACH_ENTRY( ent, dir, struct resource_dir_entry, entry )
711         if (!resource_strcmp( id, ent->id ))
712             return ent;
713
714     return NULL;
715 }
716
717 static struct resource_data *find_resource_data( struct list *dir, LANGID lang )
718 {
719     struct resource_data *res_data;
720
721     /* match only languages here */
722     LIST_FOR_EACH_ENTRY( res_data, dir, struct resource_data, entry )
723         if ( lang == res_data->lang )
724              return res_data;
725
726     return NULL;
727 }
728
729 static void add_resource_dir_entry( struct list *dir, struct resource_dir_entry *resdir )
730 {
731     struct resource_dir_entry *ent;
732
733     LIST_FOR_EACH_ENTRY( ent, dir, struct resource_dir_entry, entry )
734     {
735         if (0>resource_strcmp( ent->id, resdir->id ))
736             continue;
737
738         list_add_before( &ent->entry, &resdir->entry );
739         return;
740     }
741     list_add_tail( dir, &resdir->entry );
742 }
743
744 static void add_resource_data_entry( struct list *dir, struct resource_data *resdata )
745 {
746     struct resource_data *ent;
747
748     LIST_FOR_EACH_ENTRY( ent, dir, struct resource_data, entry )
749     {
750         if (ent->lang < resdata->lang)
751             continue;
752
753         list_add_before( &ent->entry, &resdata->entry );
754         return;
755     }
756     list_add_tail( dir, &resdata->entry );
757 }
758
759 static LPWSTR res_strdupW( LPCWSTR str )
760 {
761     LPWSTR ret;
762     UINT len;
763
764     if (HIWORD(str) == 0)
765         return (LPWSTR) (UINT_PTR) LOWORD(str);
766     len = (lstrlenW( str ) + 1) * sizeof (WCHAR);
767     ret = HeapAlloc( GetProcessHeap(), 0, len );
768     memcpy( ret, str, len );
769     return ret;
770 }
771
772 static void res_free_str( LPWSTR str )
773 {
774     if (HIWORD(str))
775         HeapFree( GetProcessHeap(), 0, str );
776 }
777
778 static BOOL update_add_resource( QUEUEDUPDATES *updates, LPCWSTR Type, LPCWSTR Name,
779                                  struct resource_data *resdata, BOOL overwrite_existing )
780 {
781     struct resource_dir_entry *restype, *resname;
782     struct resource_data *existing;
783
784     TRACE("%p %s %s %p %d\n", updates,
785           debugstr_w(Type), debugstr_w(Name), resdata, overwrite_existing );
786
787     restype = find_resource_dir_entry( &updates->root, Type );
788     if (!restype)
789     {
790         restype = HeapAlloc( GetProcessHeap(), 0, sizeof *restype );
791         restype->id = res_strdupW( Type );
792         list_init( &restype->children );
793         add_resource_dir_entry( &updates->root, restype );
794     }
795
796     resname = find_resource_dir_entry( &restype->children, Name );
797     if (!resname)
798     {
799         resname = HeapAlloc( GetProcessHeap(), 0, sizeof *resname );
800         resname->id = res_strdupW( Name );
801         list_init( &resname->children );
802         add_resource_dir_entry( &restype->children, resname );
803     }
804
805     /*
806      * If there's an existing resource entry with matching (Type,Name,Language)
807      *  it needs to be removed before adding the new data.
808      */
809     existing = find_resource_data( &resname->children, resdata->lang );
810     if (existing)
811     {
812         if (!overwrite_existing)
813             return FALSE;
814         list_remove( &existing->entry );
815         HeapFree( GetProcessHeap(), 0, existing );
816     }
817
818     add_resource_data_entry( &resname->children, resdata );
819
820     return TRUE;
821 }
822
823 static struct resource_data *allocate_resource_data( WORD Language, DWORD codepage,
824                                                      LPVOID lpData, DWORD cbData, BOOL copy_data )
825 {
826     struct resource_data *resdata;
827
828     if (!lpData || !cbData)
829         return NULL;
830
831     resdata = HeapAlloc( GetProcessHeap(), 0, sizeof *resdata + (copy_data ? cbData : 0) );
832     if (resdata)
833     {
834         resdata->lang = Language;
835         resdata->codepage = codepage;
836         resdata->cbData = cbData;
837         if (copy_data)
838         {
839             resdata->lpData = &resdata[1];
840             memcpy( resdata->lpData, lpData, cbData );
841         }
842         else
843             resdata->lpData = lpData;
844     }
845
846     return resdata;
847 }
848
849 static void free_resource_directory( struct list *head, int level )
850 {
851     struct list *ptr = NULL;
852
853     while ((ptr = list_head( head )))
854     {
855         list_remove( ptr );
856         if (level)
857         {
858             struct resource_dir_entry *ent;
859
860             ent = LIST_ENTRY( ptr, struct resource_dir_entry, entry );
861             res_free_str( ent->id );
862             free_resource_directory( &ent->children, level - 1 );
863             HeapFree(GetProcessHeap(), 0, ent);
864         }
865         else
866         {
867             struct resource_data *data;
868
869             data = LIST_ENTRY( ptr, struct resource_data, entry );
870             HeapFree( GetProcessHeap(), 0, data );
871         }
872     }
873 }
874
875 static IMAGE_NT_HEADERS *get_nt_header( void *base, DWORD mapping_size )
876 {
877     IMAGE_NT_HEADERS *nt;
878     IMAGE_DOS_HEADER *dos;
879
880     if (mapping_size<sizeof (*dos))
881         return NULL;
882
883     dos = base;
884     if (dos->e_magic != IMAGE_DOS_SIGNATURE)
885         return NULL;
886
887     if ((dos->e_lfanew + sizeof (*nt)) > mapping_size)
888         return NULL;
889
890     nt = (void*) ((BYTE*)base + dos->e_lfanew);
891
892     if (nt->Signature != IMAGE_NT_SIGNATURE)
893         return NULL;
894
895     return nt;
896 }
897
898 static IMAGE_SECTION_HEADER *get_section_header( void *base, DWORD mapping_size, DWORD *num_sections )
899 {
900     IMAGE_NT_HEADERS *nt;
901     IMAGE_SECTION_HEADER *sec;
902     DWORD section_ofs;
903
904     nt = get_nt_header( base, mapping_size );
905     if (!nt)
906         return NULL;
907
908     /* check that we don't go over the end of the file accessing the sections */
909     section_ofs = FIELD_OFFSET(IMAGE_NT_HEADERS, OptionalHeader) + nt->FileHeader.SizeOfOptionalHeader;
910     if ((nt->FileHeader.NumberOfSections * sizeof (*sec) + section_ofs) > mapping_size)
911         return NULL;
912
913     if (num_sections)
914         *num_sections = nt->FileHeader.NumberOfSections;
915
916     /* from here we have a valid PE exe to update */
917     return (void*) ((BYTE*)nt + section_ofs);
918 }
919
920 static BOOL check_pe_exe( HANDLE file, QUEUEDUPDATES *updates )
921 {
922     const IMAGE_NT_HEADERS *nt;
923     const IMAGE_SECTION_HEADER *sec;
924     BOOL ret = FALSE;
925     HANDLE mapping;
926     DWORD mapping_size, num_sections = 0;
927     void *base = NULL;
928
929     mapping_size = GetFileSize( file, NULL );
930
931     mapping = CreateFileMappingW( file, NULL, PAGE_READONLY, 0, 0, NULL );
932     if (!mapping)
933         goto done;
934
935     base = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, mapping_size );
936     if (!base)
937         goto done;
938
939     nt = get_nt_header( base, mapping_size );
940     if (!nt)
941         goto done;
942
943     TRACE("resources: %08x %08x\n",
944           nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress,
945           nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size);
946
947     sec = get_section_header( base, mapping_size, &num_sections );
948     if (!sec)
949         goto done;
950
951     ret = TRUE;
952
953 done:
954     if (base)
955         UnmapViewOfFile( base );
956     if (mapping)
957         CloseHandle( mapping );
958
959     return ret;
960 }
961
962 struct resource_size_info {
963     DWORD types_ofs;
964     DWORD names_ofs;
965     DWORD langs_ofs;
966     DWORD data_entry_ofs;
967     DWORD strings_ofs;
968     DWORD data_ofs;
969     DWORD total_size;
970 };
971
972 struct mapping_info {
973     HANDLE file;
974     HANDLE mapping;
975     void *base;
976     DWORD size;
977     BOOL read_write;
978 };
979
980 static const IMAGE_SECTION_HEADER *section_from_rva( void *base, DWORD mapping_size, DWORD rva )
981 {
982     const IMAGE_SECTION_HEADER *sec;
983     DWORD num_sections = 0;
984     int i;
985
986     sec = get_section_header( base, mapping_size, &num_sections );
987     if (!sec)
988         return NULL;
989
990     for (i=num_sections-1; i>=0; i--)
991     {
992         if (sec[i].VirtualAddress <= rva &&
993             rva <= (DWORD)sec[i].VirtualAddress + sec[i].SizeOfRawData)
994         {
995             return &sec[i];
996         }
997     }
998
999     return NULL;
1000 }
1001
1002 static void *address_from_rva( void *base, DWORD mapping_size, DWORD rva, DWORD len )
1003 {
1004     const IMAGE_SECTION_HEADER *sec;
1005
1006     sec = section_from_rva( base, mapping_size, rva );
1007     if (!sec)
1008         return NULL;
1009
1010     if (rva + len <= (DWORD)sec->VirtualAddress + sec->SizeOfRawData)
1011         return (void*)((LPBYTE) base + (sec->PointerToRawData + rva - sec->VirtualAddress));
1012
1013     return NULL;
1014 }
1015
1016 static LPWSTR resource_dup_string( const IMAGE_RESOURCE_DIRECTORY *root, const IMAGE_RESOURCE_DIRECTORY_ENTRY *entry )
1017 {
1018     const IMAGE_RESOURCE_DIR_STRING_U* string;
1019     LPWSTR s;
1020
1021     if (!entry->u1.s1.NameIsString)
1022         return UIntToPtr(entry->u1.s2.Id);
1023
1024     string = (const IMAGE_RESOURCE_DIR_STRING_U*) (((const char *)root) + entry->u1.s1.NameOffset);
1025     s = HeapAlloc(GetProcessHeap(), 0, (string->Length + 1)*sizeof (WCHAR) );
1026     memcpy( s, string->NameString, (string->Length + 1)*sizeof (WCHAR) );
1027     s[string->Length] = 0;
1028
1029     return s;
1030 }
1031
1032 /* this function is based on the code in winedump's pe.c */
1033 static BOOL enumerate_mapped_resources( QUEUEDUPDATES *updates,
1034                              void *base, DWORD mapping_size,
1035                              const IMAGE_RESOURCE_DIRECTORY *root )
1036 {
1037     const IMAGE_RESOURCE_DIRECTORY *namedir, *langdir;
1038     const IMAGE_RESOURCE_DIRECTORY_ENTRY *e1, *e2, *e3;
1039     const IMAGE_RESOURCE_DATA_ENTRY *data;
1040     DWORD i, j, k;
1041
1042     TRACE("version (%d.%d) %d named %d id entries\n",
1043           root->MajorVersion, root->MinorVersion, root->NumberOfNamedEntries, root->NumberOfIdEntries);
1044
1045     for (i = 0; i< root->NumberOfNamedEntries + root->NumberOfIdEntries; i++)
1046     {
1047         LPWSTR Type;
1048
1049         e1 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(root + 1) + i;
1050
1051         Type = resource_dup_string( root, e1 );
1052
1053         namedir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e1->u2.s3.OffsetToDirectory);
1054         for (j = 0; j < namedir->NumberOfNamedEntries + namedir->NumberOfIdEntries; j++)
1055         {
1056             LPWSTR Name;
1057
1058             e2 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(namedir + 1) + j;
1059
1060             Name = resource_dup_string( root, e2 );
1061
1062             langdir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e2->u2.s3.OffsetToDirectory);
1063             for (k = 0; k < langdir->NumberOfNamedEntries + langdir->NumberOfIdEntries; k++)
1064             {
1065                 LANGID Lang;
1066                 void *p;
1067                 struct resource_data *resdata;
1068
1069                 e3 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(langdir + 1) + k;
1070
1071                 Lang = e3->u1.s2.Id;
1072
1073                 data = (const IMAGE_RESOURCE_DATA_ENTRY *)((const char *)root + e3->u2.OffsetToData);
1074
1075                 p = address_from_rva( base, mapping_size, data->OffsetToData, data->Size );
1076
1077                 resdata = allocate_resource_data( Lang, data->CodePage, p, data->Size, FALSE );
1078                 if (resdata)
1079                 {
1080                     if (!update_add_resource( updates, Type, Name, resdata, FALSE ))
1081                         HeapFree( GetProcessHeap(), 0, resdata );
1082                 }
1083             }
1084             res_free_str( Name );
1085         }
1086         res_free_str( Type );
1087     }
1088
1089     return TRUE;
1090 }
1091
1092 static BOOL read_mapped_resources( QUEUEDUPDATES *updates, void *base, DWORD mapping_size )
1093 {
1094     const IMAGE_RESOURCE_DIRECTORY *root;
1095     const IMAGE_NT_HEADERS *nt;
1096     const IMAGE_SECTION_HEADER *sec;
1097     DWORD num_sections = 0, i;
1098
1099     nt = get_nt_header( base, mapping_size );
1100     if (!nt)
1101         return FALSE;
1102
1103     sec = get_section_header( base, mapping_size, &num_sections );
1104     if (!sec)
1105         return FALSE;
1106
1107     for (i=0; i<num_sections; i++)
1108         if (!memcmp(sec[i].Name, ".rsrc", 6))
1109             break;
1110
1111     if (i == num_sections)
1112         return TRUE;
1113
1114     /* check the resource data is inside the mapping */
1115     if (sec[i].PointerToRawData > mapping_size ||
1116         (sec[i].PointerToRawData + sec[i].SizeOfRawData) > mapping_size)
1117         return TRUE;
1118
1119     TRACE("found .rsrc at %08x, size %08x\n", sec[i].PointerToRawData, sec[i].SizeOfRawData);
1120
1121     if (!sec[i].PointerToRawData || sec[i].SizeOfRawData < sizeof(IMAGE_RESOURCE_DIRECTORY))
1122         return TRUE;
1123
1124     root = (void*) ((BYTE*)base + sec[i].PointerToRawData);
1125     enumerate_mapped_resources( updates, base, mapping_size, root );
1126
1127     return TRUE;
1128 }
1129
1130 static BOOL map_file_into_memory( struct mapping_info *mi )
1131 {
1132     DWORD page_attr, perm;
1133
1134     if (mi->read_write)
1135     {
1136         page_attr = PAGE_READWRITE;
1137         perm = FILE_MAP_WRITE | FILE_MAP_READ;
1138     }
1139     else
1140     {
1141         page_attr = PAGE_READONLY;
1142         perm = FILE_MAP_READ;
1143     }
1144
1145     mi->mapping = CreateFileMappingW( mi->file, NULL, page_attr, 0, 0, NULL );
1146     if (!mi->mapping)
1147         return FALSE;
1148
1149     mi->base = MapViewOfFile( mi->mapping, perm, 0, 0, mi->size );
1150     if (!mi->base)
1151         return FALSE;
1152
1153     return TRUE;
1154 }
1155
1156 static BOOL unmap_file_from_memory( struct mapping_info *mi )
1157 {
1158     if (mi->base)
1159         UnmapViewOfFile( mi->base );
1160     mi->base = NULL;
1161     if (mi->mapping)
1162         CloseHandle( mi->mapping );
1163     mi->mapping = NULL;
1164     return TRUE;
1165 }
1166
1167 static void destroy_mapping( struct mapping_info *mi )
1168 {
1169     if (!mi)
1170         return;
1171     unmap_file_from_memory( mi );
1172     if (mi->file)
1173         CloseHandle( mi->file );
1174     HeapFree( GetProcessHeap(), 0, mi );
1175 }
1176
1177 static struct mapping_info *create_mapping( LPCWSTR name, BOOL rw )
1178 {
1179     struct mapping_info *mi;
1180
1181     mi = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof *mi );
1182     if (!mi)
1183         return NULL;
1184
1185     mi->read_write = rw;
1186
1187     mi->file = CreateFileW( name, GENERIC_READ | (rw ? GENERIC_WRITE : 0),
1188                             0, NULL, OPEN_EXISTING, 0, 0 );
1189
1190     if (mi->file != INVALID_HANDLE_VALUE)
1191     {
1192         mi->size = GetFileSize( mi->file, NULL );
1193
1194         if (map_file_into_memory( mi ))
1195             return mi;
1196     }
1197
1198     unmap_file_from_memory( mi );
1199     HeapFree( GetProcessHeap(), 0, mi );
1200
1201     return NULL;
1202 }
1203
1204 static BOOL resize_mapping( struct mapping_info *mi, DWORD new_size )
1205 {
1206     if (!unmap_file_from_memory( mi ))
1207         return FALSE;
1208
1209     /* change the file size */
1210     SetFilePointer( mi->file, new_size, NULL, FILE_BEGIN );
1211     if (!SetEndOfFile( mi->file ))
1212     {
1213         ERR("failed to set file size to %08x\n", new_size );
1214         return FALSE;
1215     }
1216
1217     mi->size = new_size;
1218
1219     return map_file_into_memory( mi );
1220 }
1221
1222 static void get_resource_sizes( QUEUEDUPDATES *updates, struct resource_size_info *si )
1223 {
1224     struct resource_dir_entry *types, *names;
1225     struct resource_data *data;
1226     DWORD num_types = 0, num_names = 0, num_langs = 0, strings_size = 0, data_size = 0;
1227
1228     memset( si, 0, sizeof *si );
1229
1230     LIST_FOR_EACH_ENTRY( types, &updates->root, struct resource_dir_entry, entry )
1231     {
1232         num_types++;
1233         if (HIWORD( types->id ))
1234             strings_size += sizeof (WORD) + lstrlenW( types->id )*sizeof (WCHAR);
1235
1236         LIST_FOR_EACH_ENTRY( names, &types->children, struct resource_dir_entry, entry )
1237         {
1238             num_names++;
1239
1240             if (HIWORD( names->id ))
1241                 strings_size += sizeof (WORD) + lstrlenW( names->id )*sizeof (WCHAR);
1242
1243             LIST_FOR_EACH_ENTRY( data, &names->children, struct resource_data, entry )
1244             {
1245                 num_langs++;
1246                 data_size += (data->cbData + 3) & ~3;
1247             }
1248         }
1249     }
1250
1251     /* names are at the end of the types */
1252     si->names_ofs = sizeof (IMAGE_RESOURCE_DIRECTORY) +
1253             num_types * sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1254
1255     /* language directories are at the end of the names */
1256     si->langs_ofs = si->names_ofs +
1257             num_types * sizeof (IMAGE_RESOURCE_DIRECTORY) +
1258             num_names * sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1259
1260     si->data_entry_ofs = si->langs_ofs +
1261             num_names * sizeof (IMAGE_RESOURCE_DIRECTORY) +
1262             num_langs * sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1263
1264     si->strings_ofs = si->data_entry_ofs +
1265             num_langs * sizeof (IMAGE_RESOURCE_DATA_ENTRY);
1266
1267     si->data_ofs = si->strings_ofs + ((strings_size + 3) & ~3);
1268
1269     si->total_size = si->data_ofs + data_size;
1270
1271     TRACE("names %08x langs %08x data entries %08x strings %08x data %08x total %08x\n",
1272           si->names_ofs, si->langs_ofs, si->data_entry_ofs,
1273           si->strings_ofs, si->data_ofs, si->total_size);
1274 }
1275
1276 static void res_write_padding( BYTE *res_base, DWORD size )
1277 {
1278     static const BYTE pad[] = {
1279         'P','A','D','D','I','N','G','X','X','P','A','D','D','I','N','G' };
1280     DWORD i;
1281
1282     for ( i = 0; i < size / sizeof pad; i++ )
1283         memcpy( &res_base[i*sizeof pad], pad, sizeof pad );
1284     memcpy( &res_base[i*sizeof pad], pad, size%sizeof pad );
1285 }
1286
1287 static BOOL write_resources( QUEUEDUPDATES *updates, LPBYTE base, struct resource_size_info *si, DWORD rva )
1288 {
1289     struct resource_dir_entry *types, *names;
1290     struct resource_data *data;
1291     IMAGE_RESOURCE_DIRECTORY *root;
1292
1293     TRACE("%p %p %p %08x\n", updates, base, si, rva );
1294
1295     memset( base, 0, si->total_size );
1296
1297     /* the root entry always exists */
1298     root = (IMAGE_RESOURCE_DIRECTORY*) base;
1299     memset( root, 0, sizeof *root );
1300     root->MajorVersion = 4;
1301     si->types_ofs = sizeof *root;
1302     LIST_FOR_EACH_ENTRY( types, &updates->root, struct resource_dir_entry, entry )
1303     {
1304         IMAGE_RESOURCE_DIRECTORY_ENTRY *e1;
1305         IMAGE_RESOURCE_DIRECTORY *namedir;
1306
1307         e1 = (IMAGE_RESOURCE_DIRECTORY_ENTRY*) &base[si->types_ofs];
1308         memset( e1, 0, sizeof *e1 );
1309         if (HIWORD( types->id ))
1310         {
1311             WCHAR *strings;
1312             DWORD len;
1313
1314             root->NumberOfNamedEntries++;
1315             e1->u1.s1.NameIsString = 1;
1316             e1->u1.s1.NameOffset = si->strings_ofs;
1317
1318             strings = (WCHAR*) &base[si->strings_ofs];
1319             len = lstrlenW( types->id );
1320             strings[0] = len;
1321             memcpy( &strings[1], types->id, len * sizeof (WCHAR) );
1322             si->strings_ofs += (len + 1) * sizeof (WCHAR);
1323         }
1324         else
1325         {
1326             root->NumberOfIdEntries++;
1327             e1->u1.s2.Id = LOWORD( types->id );
1328         }
1329         e1->u2.s3.OffsetToDirectory = si->names_ofs;
1330         e1->u2.s3.DataIsDirectory = TRUE;
1331         si->types_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1332
1333         namedir = (IMAGE_RESOURCE_DIRECTORY*) &base[si->names_ofs];
1334         memset( namedir, 0, sizeof *namedir );
1335         namedir->MajorVersion = 4;
1336         si->names_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY);
1337
1338         LIST_FOR_EACH_ENTRY( names, &types->children, struct resource_dir_entry, entry )
1339         {
1340             IMAGE_RESOURCE_DIRECTORY_ENTRY *e2;
1341             IMAGE_RESOURCE_DIRECTORY *langdir;
1342
1343             e2 = (IMAGE_RESOURCE_DIRECTORY_ENTRY*) &base[si->names_ofs];
1344             memset( e2, 0, sizeof *e2 );
1345             if (HIWORD( names->id ))
1346             {
1347                 WCHAR *strings;
1348                 DWORD len;
1349
1350                 namedir->NumberOfNamedEntries++;
1351                 e2->u1.s1.NameIsString = 1;
1352                 e2->u1.s1.NameOffset = si->strings_ofs;
1353
1354                 strings = (WCHAR*) &base[si->strings_ofs];
1355                 len = lstrlenW( names->id );
1356                 strings[0] = len;
1357                 memcpy( &strings[1], names->id, len * sizeof (WCHAR) );
1358                 si->strings_ofs += (len + 1) * sizeof (WCHAR);
1359             }
1360             else
1361             {
1362                 namedir->NumberOfIdEntries++;
1363                 e2->u1.s2.Id = LOWORD( names->id );
1364             }
1365             e2->u2.s3.OffsetToDirectory = si->langs_ofs;
1366             e2->u2.s3.DataIsDirectory = TRUE;
1367             si->names_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1368
1369             langdir = (IMAGE_RESOURCE_DIRECTORY*) &base[si->langs_ofs];
1370             memset( langdir, 0, sizeof *langdir );
1371             langdir->MajorVersion = 4;
1372             si->langs_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY);
1373
1374             LIST_FOR_EACH_ENTRY( data, &names->children, struct resource_data, entry )
1375             {
1376                 IMAGE_RESOURCE_DIRECTORY_ENTRY *e3;
1377                 IMAGE_RESOURCE_DATA_ENTRY *de;
1378                 int pad_size;
1379
1380                 e3 = (IMAGE_RESOURCE_DIRECTORY_ENTRY*) &base[si->langs_ofs];
1381                 memset( e3, 0, sizeof *e3 );
1382                 langdir->NumberOfIdEntries++;
1383                 e3->u1.s2.Id = LOWORD( data->lang );
1384                 e3->u2.OffsetToData = si->data_entry_ofs;
1385
1386                 si->langs_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1387
1388                 /* write out all the data entries */
1389                 de = (IMAGE_RESOURCE_DATA_ENTRY*) &base[si->data_entry_ofs];
1390                 memset( de, 0, sizeof *de );
1391                 de->OffsetToData = si->data_ofs + rva;
1392                 de->Size = data->cbData;
1393                 de->CodePage = data->codepage;
1394                 si->data_entry_ofs += sizeof (IMAGE_RESOURCE_DATA_ENTRY);
1395
1396                 /* write out the resource data */
1397                 memcpy( &base[si->data_ofs], data->lpData, data->cbData );
1398                 si->data_ofs += data->cbData;
1399
1400                 pad_size = (-si->data_ofs)&3;
1401                 res_write_padding( &base[si->data_ofs], pad_size );
1402                 si->data_ofs += pad_size;
1403             }
1404         }
1405     }
1406
1407     return TRUE;
1408 }
1409
1410 /*
1411  *  FIXME:
1412  *  Assumes that the resources are in .rsrc
1413  *   and .rsrc is the last section in the file.
1414  *  Not sure whether updating resources will other cases on Windows.
1415  *  If the resources lie in a section containing other data,
1416  *   resizing that section could possibly cause trouble.
1417  *  If the section with the resources isn't last, the remaining
1418  *   sections need to be moved down in the file, and the section header
1419  *   would need to be adjusted.
1420  *  If we needed to add a section, what would we name it?
1421  *  If we needed to add a section and there wasn't space in the file
1422  *   header, how would that work?
1423  *  Seems that at least some of these cases can't be handled properly.
1424  */
1425 static IMAGE_SECTION_HEADER *get_resource_section( void *base, DWORD mapping_size )
1426 {
1427     IMAGE_SECTION_HEADER *sec;
1428     IMAGE_NT_HEADERS *nt;
1429     DWORD i, num_sections = 0;
1430
1431     nt = get_nt_header( base, mapping_size );
1432     if (!nt)
1433         return NULL;
1434
1435     sec = get_section_header( base, mapping_size, &num_sections );
1436     if (!sec)
1437         return NULL;
1438
1439     /* find the resources section */
1440     for (i=0; i<num_sections; i++)
1441         if (!memcmp(sec[i].Name, ".rsrc", 6))
1442             break;
1443
1444     if (i == num_sections)
1445     {
1446         FIXME(".rsrc doesn't exist\n");
1447         return NULL;
1448     }
1449
1450     return &sec[i];
1451 }
1452
1453 static DWORD get_init_data_size( void *base, DWORD mapping_size )
1454 {
1455     DWORD i, sz = 0, num_sections = 0;
1456     IMAGE_SECTION_HEADER *s;
1457
1458     s = get_section_header( base, mapping_size, &num_sections );
1459
1460     for (i=0; i<num_sections; i++)
1461         if (s[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
1462             sz += s[i].SizeOfRawData;
1463
1464     TRACE("size = %08x\n", sz);
1465
1466     return sz;
1467 }
1468
1469 static BOOL write_raw_resources( QUEUEDUPDATES *updates )
1470 {
1471     static const WCHAR prefix[] = { 'r','e','s','u',0 };
1472     WCHAR tempdir[MAX_PATH], tempfile[MAX_PATH];
1473     DWORD mapping_size, section_size, old_size;
1474     BOOL ret = FALSE;
1475     IMAGE_SECTION_HEADER *sec;
1476     IMAGE_NT_HEADERS *nt;
1477     struct resource_size_info res_size;
1478     BYTE *res_base;
1479     struct mapping_info *read_map = NULL, *write_map = NULL;
1480
1481     /* copy the exe to a temp file then update the temp file... */
1482     tempdir[0] = 0;
1483     if (!GetTempPathW( MAX_PATH, tempdir ))
1484         return ret;
1485
1486     if (!GetTempFileNameW( tempdir, prefix, 0, tempfile ))
1487         return ret;
1488
1489     if (!CopyFileW( updates->pFileName, tempfile, FALSE ))
1490         goto done;
1491
1492     TRACE("tempfile %s\n", debugstr_w(tempfile));
1493
1494     if (!updates->bDeleteExistingResources)
1495     {
1496         read_map = create_mapping( updates->pFileName, FALSE );
1497         if (!read_map)
1498             goto done;
1499
1500         ret = read_mapped_resources( updates, read_map->base, read_map->size );
1501         if (!ret)
1502         {
1503             ERR("failed to read existing resources\n");
1504             goto done;
1505         }
1506     }
1507
1508     write_map = create_mapping( tempfile, TRUE );
1509     if (!write_map)
1510         goto done;
1511
1512     nt = get_nt_header( write_map->base, write_map->size );
1513     if (!nt)
1514         goto done;
1515
1516     if (nt->OptionalHeader.SectionAlignment <= 0)
1517     {
1518         ERR("invalid section alignment %04x\n", nt->OptionalHeader.SectionAlignment);
1519         goto done;
1520     }
1521
1522     sec = get_resource_section( write_map->base, write_map->size );
1523     if (!sec)
1524         goto done;
1525
1526     if (!sec->PointerToRawData)  /* empty section */
1527     {
1528         sec->PointerToRawData = write_map->size;
1529         sec->SizeOfRawData = 0;
1530     }
1531     else if ((sec->SizeOfRawData + sec->PointerToRawData) != write_map->size)
1532     {
1533         FIXME(".rsrc isn't at the end of the image %08x + %08x != %08x for %s\n",
1534               sec->SizeOfRawData, sec->PointerToRawData, write_map->size, debugstr_w(updates->pFileName));
1535         goto done;
1536     }
1537
1538     TRACE("before .rsrc at %08x, size %08x\n", sec->PointerToRawData, sec->SizeOfRawData);
1539
1540     get_resource_sizes( updates, &res_size );
1541
1542     /* round up the section size */
1543     section_size = res_size.total_size;
1544     section_size += (-section_size) % nt->OptionalHeader.SectionAlignment;
1545
1546     mapping_size = sec->PointerToRawData + section_size;
1547
1548     TRACE("requires %08x (%08x) bytes\n", res_size.total_size, section_size );
1549
1550     /* check if the file size needs to be changed */
1551     if (section_size != sec->SizeOfRawData)
1552     {
1553         old_size = write_map->size;
1554
1555         TRACE("file size %08x -> %08x\n", old_size, mapping_size);
1556
1557         /* unmap the file before changing the file size */
1558         ret = resize_mapping( write_map, mapping_size );
1559
1560         /* get the pointers again - they might be different after remapping */
1561         nt = get_nt_header( write_map->base, mapping_size );
1562         if (!nt)
1563         {
1564             ERR("couldn't get NT header\n");
1565             goto done;
1566         }
1567
1568         sec = get_resource_section( write_map->base, mapping_size );
1569         if (!sec)
1570              goto done;
1571
1572         /* adjust the PE header information */
1573         nt->OptionalHeader.SizeOfImage += (mapping_size - old_size);
1574         sec->SizeOfRawData = section_size;
1575         sec->Misc.VirtualSize = section_size;
1576         nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = res_size.total_size;
1577         nt->OptionalHeader.SizeOfInitializedData = get_init_data_size( write_map->base, mapping_size );
1578     }
1579
1580     res_base = (LPBYTE) write_map->base + sec->PointerToRawData;
1581
1582     TRACE("base = %p offset = %08x\n", write_map->base, sec->PointerToRawData);
1583
1584     ret = write_resources( updates, res_base, &res_size, sec->VirtualAddress );
1585
1586     res_write_padding( res_base + res_size.total_size, section_size - res_size.total_size );
1587
1588     TRACE("after  .rsrc at %08x, size %08x\n", sec->PointerToRawData, sec->SizeOfRawData);
1589
1590 done:
1591     destroy_mapping( read_map );
1592     destroy_mapping( write_map );
1593
1594     if (ret)
1595         ret = CopyFileW( tempfile, updates->pFileName, FALSE );
1596
1597     DeleteFileW( tempfile );
1598
1599     return ret;
1600 }
1601
1602 /***********************************************************************
1603  *          BeginUpdateResourceW                 (KERNEL32.@)
1604  */
1605 HANDLE WINAPI BeginUpdateResourceW( LPCWSTR pFileName, BOOL bDeleteExistingResources )
1606 {
1607     QUEUEDUPDATES *updates = NULL;
1608     HANDLE hUpdate, file, ret = NULL;
1609
1610     TRACE("%s, %d\n", debugstr_w(pFileName), bDeleteExistingResources);
1611
1612     hUpdate = GlobalAlloc(GHND, sizeof(QUEUEDUPDATES));
1613     if (!hUpdate)
1614         return ret;
1615
1616     updates = GlobalLock(hUpdate);
1617     if (updates)
1618     {
1619         list_init( &updates->root );
1620         updates->bDeleteExistingResources = bDeleteExistingResources;
1621         updates->pFileName = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(pFileName)+1)*sizeof(WCHAR));
1622         if (updates->pFileName)
1623         {
1624             lstrcpyW(updates->pFileName, pFileName);
1625
1626             file = CreateFileW( pFileName, GENERIC_READ | GENERIC_WRITE,
1627                                 0, NULL, OPEN_EXISTING, 0, 0 );
1628
1629             /* if resources are deleted, only the file's presence is checked */
1630             if (file != INVALID_HANDLE_VALUE &&
1631                 (bDeleteExistingResources || check_pe_exe( file, updates )))
1632                 ret = hUpdate;
1633             else
1634                 HeapFree( GetProcessHeap(), 0, updates->pFileName );
1635
1636             CloseHandle( file );
1637         }
1638         GlobalUnlock(hUpdate);
1639     }
1640
1641     if (!ret)
1642         GlobalFree(hUpdate);
1643
1644     return ret;
1645 }
1646
1647
1648 /***********************************************************************
1649  *          BeginUpdateResourceA                 (KERNEL32.@)
1650  */
1651 HANDLE WINAPI BeginUpdateResourceA( LPCSTR pFileName, BOOL bDeleteExistingResources )
1652 {
1653     UNICODE_STRING FileNameW;
1654     HANDLE ret;
1655     RtlCreateUnicodeStringFromAsciiz(&FileNameW, pFileName);
1656     ret = BeginUpdateResourceW(FileNameW.Buffer, bDeleteExistingResources);
1657     RtlFreeUnicodeString(&FileNameW);
1658     return ret;
1659 }
1660
1661
1662 /***********************************************************************
1663  *          EndUpdateResourceW                 (KERNEL32.@)
1664  */
1665 BOOL WINAPI EndUpdateResourceW( HANDLE hUpdate, BOOL fDiscard )
1666 {
1667     QUEUEDUPDATES *updates;
1668     BOOL ret;
1669
1670     TRACE("%p %d\n", hUpdate, fDiscard);
1671
1672     updates = GlobalLock(hUpdate);
1673     if (!updates)
1674         return FALSE;
1675
1676     ret = fDiscard || write_raw_resources( updates );
1677
1678     free_resource_directory( &updates->root, 2 );
1679
1680     HeapFree( GetProcessHeap(), 0, updates->pFileName );
1681     GlobalUnlock( hUpdate );
1682     GlobalFree( hUpdate );
1683
1684     return ret;
1685 }
1686
1687
1688 /***********************************************************************
1689  *          EndUpdateResourceA                 (KERNEL32.@)
1690  */
1691 BOOL WINAPI EndUpdateResourceA( HANDLE hUpdate, BOOL fDiscard )
1692 {
1693     return EndUpdateResourceW(hUpdate, fDiscard);
1694 }
1695
1696
1697 /***********************************************************************
1698  *           UpdateResourceW                 (KERNEL32.@)
1699  */
1700 BOOL WINAPI UpdateResourceW( HANDLE hUpdate, LPCWSTR lpType, LPCWSTR lpName,
1701                              WORD wLanguage, LPVOID lpData, DWORD cbData)
1702 {
1703     QUEUEDUPDATES *updates;
1704     BOOL ret = FALSE;
1705
1706     TRACE("%p %s %s %08x %p %d\n", hUpdate,
1707           debugstr_w(lpType), debugstr_w(lpName), wLanguage, lpData, cbData);
1708
1709     updates = GlobalLock(hUpdate);
1710     if (updates)
1711     {
1712         struct resource_data *data;
1713         data = allocate_resource_data( wLanguage, 0, lpData, cbData, TRUE );
1714         if (data)
1715             ret = update_add_resource( updates, lpType, lpName, data, TRUE );
1716         GlobalUnlock(hUpdate);
1717     }
1718     return ret;
1719 }
1720
1721
1722 /***********************************************************************
1723  *           UpdateResourceA                 (KERNEL32.@)
1724  */
1725 BOOL WINAPI UpdateResourceA( HANDLE hUpdate, LPCSTR lpType, LPCSTR lpName,
1726                              WORD wLanguage, LPVOID lpData, DWORD cbData)
1727 {
1728     BOOL ret;
1729     UNICODE_STRING TypeW;
1730     UNICODE_STRING NameW;
1731     if(!HIWORD(lpType))
1732         TypeW.Buffer = ULongToPtr(LOWORD(lpType));
1733     else
1734         RtlCreateUnicodeStringFromAsciiz(&TypeW, lpType);
1735     if(!HIWORD(lpName))
1736         NameW.Buffer = ULongToPtr(LOWORD(lpName));
1737     else
1738         RtlCreateUnicodeStringFromAsciiz(&NameW, lpName);
1739     ret = UpdateResourceW(hUpdate, TypeW.Buffer, NameW.Buffer, wLanguage, lpData, cbData);
1740     if(HIWORD(lpType)) RtlFreeUnicodeString(&TypeW);
1741     if(HIWORD(lpName)) RtlFreeUnicodeString(&NameW);
1742     return ret;
1743 }