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