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