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