dsound: Add support for 24/32 bits input sound buffers.
[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     __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     HeapFree( GetProcessHeap(), 0, mi );
1154
1155     return NULL;
1156 }
1157
1158 static BOOL resize_mapping( struct mapping_info *mi, DWORD new_size )
1159 {
1160     if (!unmap_file_from_memory( mi ))
1161         return FALSE;
1162
1163     /* change the file size */
1164     SetFilePointer( mi->file, new_size, NULL, FILE_BEGIN );
1165     if (!SetEndOfFile( mi->file ))
1166     {
1167         ERR("failed to set file size to %08x\n", new_size );
1168         return FALSE;
1169     }
1170
1171     mi->size = new_size;
1172
1173     return map_file_into_memory( mi );
1174 }
1175
1176 static void get_resource_sizes( QUEUEDUPDATES *updates, struct resource_size_info *si )
1177 {
1178     struct resource_dir_entry *types, *names;
1179     struct resource_data *data;
1180     DWORD num_types = 0, num_names = 0, num_langs = 0, strings_size = 0, data_size = 0;
1181
1182     memset( si, 0, sizeof *si );
1183
1184     LIST_FOR_EACH_ENTRY( types, &updates->root, struct resource_dir_entry, entry )
1185     {
1186         num_types++;
1187         if (HIWORD( types->id ))
1188             strings_size += sizeof (WORD) + lstrlenW( types->id )*sizeof (WCHAR);
1189
1190         LIST_FOR_EACH_ENTRY( names, &types->children, struct resource_dir_entry, entry )
1191         {
1192             num_names++;
1193
1194             if (HIWORD( names->id ))
1195                 strings_size += sizeof (WORD) + lstrlenW( names->id )*sizeof (WCHAR);
1196
1197             LIST_FOR_EACH_ENTRY( data, &names->children, struct resource_data, entry )
1198             {
1199                 num_langs++;
1200                 data_size += (data->cbData + 3) & ~3;
1201             }
1202         }
1203     }
1204
1205     /* names are at the end of the types */
1206     si->names_ofs = sizeof (IMAGE_RESOURCE_DIRECTORY) +
1207             num_types * sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1208
1209     /* language directories are at the end of the names */
1210     si->langs_ofs = si->names_ofs +
1211             num_types * sizeof (IMAGE_RESOURCE_DIRECTORY) +
1212             num_names * sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1213
1214     si->data_entry_ofs = si->langs_ofs +
1215             num_names * sizeof (IMAGE_RESOURCE_DIRECTORY) +
1216             num_langs * sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1217
1218     si->strings_ofs = si->data_entry_ofs +
1219             num_langs * sizeof (IMAGE_RESOURCE_DATA_ENTRY);
1220
1221     si->data_ofs = si->strings_ofs + ((strings_size + 3) & ~3);
1222
1223     si->total_size = si->data_ofs + data_size;
1224
1225     TRACE("names %08x langs %08x data entries %08x strings %08x data %08x total %08x\n",
1226           si->names_ofs, si->langs_ofs, si->data_entry_ofs,
1227           si->strings_ofs, si->data_ofs, si->total_size);
1228 }
1229
1230 static void res_write_padding( BYTE *res_base, DWORD size )
1231 {
1232     static const BYTE pad[] = {
1233         'P','A','D','D','I','N','G','X','X','P','A','D','D','I','N','G' };
1234     DWORD i;
1235
1236     for ( i = 0; i < size / sizeof pad; i++ )
1237         memcpy( &res_base[i*sizeof pad], pad, sizeof pad );
1238     memcpy( &res_base[i*sizeof pad], pad, size%sizeof pad );
1239 }
1240
1241 static BOOL write_resources( QUEUEDUPDATES *updates, LPBYTE base, struct resource_size_info *si, DWORD rva )
1242 {
1243     struct resource_dir_entry *types, *names;
1244     struct resource_data *data;
1245     IMAGE_RESOURCE_DIRECTORY *root;
1246
1247     TRACE("%p %p %p %08x\n", updates, base, si, rva );
1248
1249     memset( base, 0, si->total_size );
1250
1251     /* the root entry always exists */
1252     root = (IMAGE_RESOURCE_DIRECTORY*) base;
1253     memset( root, 0, sizeof *root );
1254     root->MajorVersion = 4;
1255     si->types_ofs = sizeof *root;
1256     LIST_FOR_EACH_ENTRY( types, &updates->root, struct resource_dir_entry, entry )
1257     {
1258         IMAGE_RESOURCE_DIRECTORY_ENTRY *e1;
1259         IMAGE_RESOURCE_DIRECTORY *namedir;
1260
1261         e1 = (IMAGE_RESOURCE_DIRECTORY_ENTRY*) &base[si->types_ofs];
1262         memset( e1, 0, sizeof *e1 );
1263         if (HIWORD( types->id ))
1264         {
1265             WCHAR *strings;
1266             DWORD len;
1267
1268             root->NumberOfNamedEntries++;
1269             e1->u1.s1.NameIsString = 1;
1270             e1->u1.s1.NameOffset = si->strings_ofs;
1271
1272             strings = (WCHAR*) &base[si->strings_ofs];
1273             len = lstrlenW( types->id );
1274             strings[0] = len;
1275             memcpy( &strings[1], types->id, len * sizeof (WCHAR) );
1276             si->strings_ofs += (len + 1) * sizeof (WCHAR);
1277         }
1278         else
1279         {
1280             root->NumberOfIdEntries++;
1281             e1->u1.s2.Id = LOWORD( types->id );
1282         }
1283         e1->u2.s3.OffsetToDirectory = si->names_ofs;
1284         e1->u2.s3.DataIsDirectory = TRUE;
1285         si->types_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1286
1287         namedir = (IMAGE_RESOURCE_DIRECTORY*) &base[si->names_ofs];
1288         memset( namedir, 0, sizeof *namedir );
1289         namedir->MajorVersion = 4;
1290         si->names_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY);
1291
1292         LIST_FOR_EACH_ENTRY( names, &types->children, struct resource_dir_entry, entry )
1293         {
1294             IMAGE_RESOURCE_DIRECTORY_ENTRY *e2;
1295             IMAGE_RESOURCE_DIRECTORY *langdir;
1296
1297             e2 = (IMAGE_RESOURCE_DIRECTORY_ENTRY*) &base[si->names_ofs];
1298             memset( e2, 0, sizeof *e2 );
1299             if (HIWORD( names->id ))
1300             {
1301                 WCHAR *strings;
1302                 DWORD len;
1303
1304                 namedir->NumberOfNamedEntries++;
1305                 e2->u1.s1.NameIsString = 1;
1306                 e2->u1.s1.NameOffset = si->strings_ofs;
1307
1308                 strings = (WCHAR*) &base[si->strings_ofs];
1309                 len = lstrlenW( names->id );
1310                 strings[0] = len;
1311                 memcpy( &strings[1], names->id, len * sizeof (WCHAR) );
1312                 si->strings_ofs += (len + 1) * sizeof (WCHAR);
1313             }
1314             else
1315             {
1316                 namedir->NumberOfIdEntries++;
1317                 e2->u1.s2.Id = LOWORD( names->id );
1318             }
1319             e2->u2.s3.OffsetToDirectory = si->langs_ofs;
1320             e2->u2.s3.DataIsDirectory = TRUE;
1321             si->names_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1322
1323             langdir = (IMAGE_RESOURCE_DIRECTORY*) &base[si->langs_ofs];
1324             memset( langdir, 0, sizeof *langdir );
1325             langdir->MajorVersion = 4;
1326             si->langs_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY);
1327
1328             LIST_FOR_EACH_ENTRY( data, &names->children, struct resource_data, entry )
1329             {
1330                 IMAGE_RESOURCE_DIRECTORY_ENTRY *e3;
1331                 IMAGE_RESOURCE_DATA_ENTRY *de;
1332                 int pad_size;
1333
1334                 e3 = (IMAGE_RESOURCE_DIRECTORY_ENTRY*) &base[si->langs_ofs];
1335                 memset( e3, 0, sizeof *e3 );
1336                 langdir->NumberOfIdEntries++;
1337                 e3->u1.s2.Id = LOWORD( data->lang );
1338                 e3->u2.OffsetToData = si->data_entry_ofs;
1339
1340                 si->langs_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1341
1342                 /* write out all the data entries */
1343                 de = (IMAGE_RESOURCE_DATA_ENTRY*) &base[si->data_entry_ofs];
1344                 memset( de, 0, sizeof *de );
1345                 de->OffsetToData = si->data_ofs + rva;
1346                 de->Size = data->cbData;
1347                 de->CodePage = data->codepage;
1348                 si->data_entry_ofs += sizeof (IMAGE_RESOURCE_DATA_ENTRY);
1349
1350                 /* write out the resource data */
1351                 memcpy( &base[si->data_ofs], data->lpData, data->cbData );
1352                 si->data_ofs += data->cbData;
1353
1354                 pad_size = (-si->data_ofs)&3;
1355                 res_write_padding( &base[si->data_ofs], pad_size );
1356                 si->data_ofs += pad_size;
1357             }
1358         }
1359     }
1360
1361     return TRUE;
1362 }
1363
1364 /*
1365  *  FIXME:
1366  *  Assumes that the resources are in .rsrc
1367  *   and .rsrc is the last section in the file.
1368  *  Not sure whether updating resources will other cases on Windows.
1369  *  If the resources lie in a section containing other data,
1370  *   resizing that section could possibly cause trouble.
1371  *  If the section with the resources isn't last, the remaining
1372  *   sections need to be moved down in the file, and the section header
1373  *   would need to be adjusted.
1374  *  If we needed to add a section, what would we name it?
1375  *  If we needed to add a section and there wasn't space in the file
1376  *   header, how would that work?
1377  *  Seems that at least some of these cases can't be handled properly.
1378  */
1379 static IMAGE_SECTION_HEADER *get_resource_section( void *base, DWORD mapping_size )
1380 {
1381     IMAGE_SECTION_HEADER *sec;
1382     IMAGE_NT_HEADERS *nt;
1383     DWORD i, num_sections = 0;
1384
1385     nt = get_nt_header( base, mapping_size );
1386     if (!nt)
1387         return NULL;
1388
1389     sec = get_section_header( base, mapping_size, &num_sections );
1390     if (!sec)
1391         return NULL;
1392
1393     /* find the resources section */
1394     for (i=0; i<num_sections; i++)
1395         if (!memcmp(sec[i].Name, ".rsrc", 6))
1396             break;
1397
1398     if (i == num_sections)
1399     {
1400         FIXME(".rsrc doesn't exist\n");
1401         return NULL;
1402     }
1403
1404     /* check that the resources section is last */
1405     if (i != num_sections - 1)
1406     {
1407         FIXME(".rsrc isn't the last section\n");
1408         return NULL;
1409     }
1410
1411     return &sec[i];
1412 }
1413
1414 static DWORD get_init_data_size( void *base, DWORD mapping_size )
1415 {
1416     DWORD i, sz = 0, num_sections = 0;
1417     IMAGE_SECTION_HEADER *s;
1418
1419     s = get_section_header( base, mapping_size, &num_sections );
1420
1421     for (i=0; i<num_sections; i++)
1422         if (s[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
1423             sz += s[i].SizeOfRawData;
1424
1425     TRACE("size = %08x\n", sz);
1426
1427     return sz;
1428 }
1429
1430 static BOOL write_raw_resources( QUEUEDUPDATES *updates )
1431 {
1432     static const WCHAR prefix[] = { 'r','e','s','u',0 };
1433     WCHAR tempdir[MAX_PATH], tempfile[MAX_PATH];
1434     DWORD mapping_size, section_size, old_size;
1435     BOOL ret = FALSE;
1436     IMAGE_SECTION_HEADER *sec;
1437     IMAGE_NT_HEADERS *nt;
1438     struct resource_size_info res_size;
1439     BYTE *res_base;
1440     struct mapping_info *read_map = NULL, *write_map = NULL;
1441
1442     /* copy the exe to a temp file then update the temp file... */
1443     tempdir[0] = 0;
1444     if (!GetTempPathW( MAX_PATH, tempdir ))
1445         return ret;
1446
1447     if (!GetTempFileNameW( tempdir, prefix, 0, tempfile ))
1448         return ret;
1449
1450     if (!CopyFileW( updates->pFileName, tempfile, FALSE ))
1451         goto done;
1452
1453     TRACE("tempfile %s\n", debugstr_w(tempfile));
1454
1455     if (!updates->bDeleteExistingResources)
1456     {
1457         read_map = create_mapping( updates->pFileName, FALSE );
1458         if (!read_map)
1459             goto done;
1460
1461         ret = read_mapped_resources( updates, read_map->base, read_map->size );
1462         if (!ret)
1463         {
1464             ERR("failed to read existing resources\n");
1465             goto done;
1466         }
1467     }
1468
1469     write_map = create_mapping( tempfile, TRUE );
1470     if (!write_map)
1471         goto done;
1472
1473     nt = get_nt_header( write_map->base, write_map->size );
1474     if (!nt)
1475         goto done;
1476
1477     if (nt->OptionalHeader.SectionAlignment <= 0)
1478     {
1479         ERR("invalid section alignment %04x\n", nt->OptionalHeader.SectionAlignment);
1480         goto done;
1481     }
1482
1483     sec = get_resource_section( write_map->base, write_map->size );
1484     if (!sec)
1485         goto done;
1486
1487     if ((sec->SizeOfRawData + sec->PointerToRawData) != write_map->size)
1488     {
1489         FIXME(".rsrc isn't at the end of the image %08x + %08x != %08x\n",
1490             sec->SizeOfRawData, sec->PointerToRawData, write_map->size);
1491         goto done;
1492     }
1493
1494     TRACE("before .rsrc at %08x, size %08x\n", sec->PointerToRawData, sec->SizeOfRawData);
1495
1496     get_resource_sizes( updates, &res_size );
1497
1498     /* round up the section size */
1499     section_size = res_size.total_size;
1500     section_size += (-section_size) % nt->OptionalHeader.SectionAlignment;
1501
1502     mapping_size = sec->PointerToRawData + section_size;
1503
1504     TRACE("requires %08x (%08x) bytes\n", res_size.total_size, section_size );
1505
1506     /* check if the file size needs to be changed */
1507     if (section_size != sec->SizeOfRawData)
1508     {
1509         old_size = write_map->size;
1510
1511         TRACE("file size %08x -> %08x\n", old_size, mapping_size);
1512
1513         /* unmap the file before changing the file size */
1514         ret = resize_mapping( write_map, mapping_size );
1515
1516         /* get the pointers again - they might be different after remapping */
1517         nt = get_nt_header( write_map->base, mapping_size );
1518         if (!nt)
1519         {
1520             ERR("couldn't get NT header\n");
1521             goto done;
1522         }
1523
1524         sec = get_resource_section( write_map->base, mapping_size );
1525         if (!sec)
1526              goto done;
1527
1528         /* adjust the PE header information */
1529         nt->OptionalHeader.SizeOfImage += (mapping_size - old_size);
1530         sec->SizeOfRawData = section_size;
1531         sec->Misc.VirtualSize = section_size;
1532         nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = res_size.total_size;
1533         nt->OptionalHeader.SizeOfInitializedData = get_init_data_size( write_map->base, mapping_size );
1534     }
1535
1536     res_base = (LPBYTE) write_map->base + sec->PointerToRawData;
1537
1538     TRACE("base = %p offset = %08x\n", write_map->base, sec->PointerToRawData);
1539
1540     ret = write_resources( updates, res_base, &res_size, sec->VirtualAddress );
1541
1542     res_write_padding( res_base + res_size.total_size, section_size - res_size.total_size );
1543
1544     TRACE("after  .rsrc at %08x, size %08x\n", sec->PointerToRawData, sec->SizeOfRawData);
1545
1546 done:
1547     destroy_mapping( read_map );
1548     destroy_mapping( write_map );
1549
1550     if (ret)
1551         ret = CopyFileW( tempfile, updates->pFileName, FALSE );
1552
1553     DeleteFileW( tempfile );
1554
1555     return ret;
1556 }
1557
1558 /***********************************************************************
1559  *          BeginUpdateResourceW                 (KERNEL32.@)
1560  */
1561 HANDLE WINAPI BeginUpdateResourceW( LPCWSTR pFileName, BOOL bDeleteExistingResources )
1562 {
1563     QUEUEDUPDATES *updates = NULL;
1564     HANDLE hUpdate, file, ret = NULL;
1565
1566     TRACE("%s, %d\n", debugstr_w(pFileName), bDeleteExistingResources);
1567
1568     hUpdate = GlobalAlloc(GHND, sizeof(QUEUEDUPDATES));
1569     if (!hUpdate)
1570         return ret;
1571
1572     updates = GlobalLock(hUpdate);
1573     if (updates)
1574     {
1575         list_init( &updates->root );
1576         updates->bDeleteExistingResources = bDeleteExistingResources;
1577         updates->pFileName = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(pFileName)+1)*sizeof(WCHAR));
1578         if (updates->pFileName)
1579         {
1580             lstrcpyW(updates->pFileName, pFileName);
1581
1582             file = CreateFileW( pFileName, GENERIC_READ | GENERIC_WRITE,
1583                                 0, NULL, OPEN_EXISTING, 0, 0 );
1584
1585             /* if resources are deleted, only the file's presence is checked */
1586             if (file != INVALID_HANDLE_VALUE &&
1587                 (bDeleteExistingResources || check_pe_exe( file, updates )))
1588                 ret = hUpdate;
1589             else
1590                 HeapFree( GetProcessHeap(), 0, updates->pFileName );
1591
1592             CloseHandle( file );
1593         }
1594         GlobalUnlock(hUpdate);
1595     }
1596
1597     if (!ret)
1598         GlobalFree(hUpdate);
1599
1600     return ret;
1601 }
1602
1603
1604 /***********************************************************************
1605  *          BeginUpdateResourceA                 (KERNEL32.@)
1606  */
1607 HANDLE WINAPI BeginUpdateResourceA( LPCSTR pFileName, BOOL bDeleteExistingResources )
1608 {
1609     UNICODE_STRING FileNameW;
1610     HANDLE ret;
1611     RtlCreateUnicodeStringFromAsciiz(&FileNameW, pFileName);
1612     ret = BeginUpdateResourceW(FileNameW.Buffer, bDeleteExistingResources);
1613     RtlFreeUnicodeString(&FileNameW);
1614     return ret;
1615 }
1616
1617
1618 /***********************************************************************
1619  *          EndUpdateResourceW                 (KERNEL32.@)
1620  */
1621 BOOL WINAPI EndUpdateResourceW( HANDLE hUpdate, BOOL fDiscard )
1622 {
1623     QUEUEDUPDATES *updates;
1624     BOOL ret;
1625
1626     TRACE("%p %d\n", hUpdate, fDiscard);
1627
1628     updates = GlobalLock(hUpdate);
1629     if (!updates)
1630         return FALSE;
1631
1632     ret = fDiscard || write_raw_resources( updates );
1633
1634     free_resource_directory( &updates->root, 2 );
1635
1636     HeapFree( GetProcessHeap(), 0, updates->pFileName );
1637     GlobalUnlock( hUpdate );
1638     GlobalFree( hUpdate );
1639
1640     return ret;
1641 }
1642
1643
1644 /***********************************************************************
1645  *          EndUpdateResourceA                 (KERNEL32.@)
1646  */
1647 BOOL WINAPI EndUpdateResourceA( HANDLE hUpdate, BOOL fDiscard )
1648 {
1649     return EndUpdateResourceW(hUpdate, fDiscard);
1650 }
1651
1652
1653 /***********************************************************************
1654  *           UpdateResourceW                 (KERNEL32.@)
1655  */
1656 BOOL WINAPI UpdateResourceW( HANDLE hUpdate, LPCWSTR lpType, LPCWSTR lpName,
1657                              WORD wLanguage, LPVOID lpData, DWORD cbData)
1658 {
1659     QUEUEDUPDATES *updates;
1660     BOOL ret = FALSE;
1661
1662     TRACE("%p %s %s %08x %p %d\n", hUpdate,
1663           debugstr_w(lpType), debugstr_w(lpName), wLanguage, lpData, cbData);
1664
1665     updates = GlobalLock(hUpdate);
1666     if (updates)
1667     {
1668         struct resource_data *data;
1669         data = allocate_resource_data( wLanguage, 0, lpData, cbData, TRUE );
1670         if (data)
1671             ret = update_add_resource( updates, lpType, lpName, data, TRUE );
1672         GlobalUnlock(hUpdate);
1673     }
1674     return ret;
1675 }
1676
1677
1678 /***********************************************************************
1679  *           UpdateResourceA                 (KERNEL32.@)
1680  */
1681 BOOL WINAPI UpdateResourceA( HANDLE hUpdate, LPCSTR lpType, LPCSTR lpName,
1682                              WORD wLanguage, LPVOID lpData, DWORD cbData)
1683 {
1684     BOOL ret;
1685     UNICODE_STRING TypeW;
1686     UNICODE_STRING NameW;
1687     if(!HIWORD(lpType))
1688         TypeW.Buffer = ULongToPtr(LOWORD(lpType));
1689     else
1690         RtlCreateUnicodeStringFromAsciiz(&TypeW, lpType);
1691     if(!HIWORD(lpName))
1692         NameW.Buffer = ULongToPtr(LOWORD(lpName));
1693     else
1694         RtlCreateUnicodeStringFromAsciiz(&NameW, lpName);
1695     ret = UpdateResourceW(hUpdate, TypeW.Buffer, NameW.Buffer, wLanguage, lpData, cbData);
1696     if(HIWORD(lpType)) RtlFreeUnicodeString(&TypeW);
1697     if(HIWORD(lpName)) RtlFreeUnicodeString(&NameW);
1698     return ret;
1699 }