push 97f44e0adb27fff75ba63d8fb97c65db9edfbe82
[wine/hacks.git] / dlls / kernel32 / resource.c
blobff2ec956b9d67fe0bf40d8d9c78dc5a9365e8701
1 /*
2 * Resources
4 * Copyright 1993 Robert J. Amstadt
5 * Copyright 1995, 2003 Alexandre Julliard
6 * Copyright 2006 Mike McCormack
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.
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.
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
23 #include "config.h"
24 #include "wine/port.h"
26 #include <stdarg.h>
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"
41 WINE_DEFAULT_DEBUG_CHANNEL(resource);
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))
50 /* retrieve the resource name to pass to the ntdll functions */
51 static NTSTATUS get_res_nameA( LPCSTR name, UNICODE_STRING *str )
53 if (!HIWORD(name))
55 str->Buffer = ULongToPtr(LOWORD(name));
56 return STATUS_SUCCESS;
58 if (name[0] == '#')
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;
66 RtlCreateUnicodeStringFromAsciiz( str, name );
67 RtlUpcaseUnicodeString( str, str, FALSE );
68 return STATUS_SUCCESS;
71 /* retrieve the resource name to pass to the ntdll functions */
72 static NTSTATUS get_res_nameW( LPCWSTR name, UNICODE_STRING *str )
74 if (!HIWORD(name))
76 str->Buffer = ULongToPtr(LOWORD(name));
77 return STATUS_SUCCESS;
79 if (name[0] == '#')
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;
88 RtlCreateUnicodeString( str, name );
89 RtlUpcaseUnicodeString( str, str, FALSE );
90 return STATUS_SUCCESS;
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 )
96 *nameA = *typeA = NULL;
98 __TRY
100 if (HIWORD(name))
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 );
106 else *nameA = ULongToPtr(LOWORD(name));
108 if (HIWORD(type))
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 );
114 else *typeA = ULongToPtr(LOWORD(type));
116 __EXCEPT_PAGE_FAULT
118 if (HIWORD(*nameA)) HeapFree( GetProcessHeap(), 0, *nameA );
119 if (HIWORD(*typeA)) HeapFree( GetProcessHeap(), 0, *typeA );
120 SetLastError( ERROR_INVALID_PARAMETER );
121 return FALSE;
123 __ENDTRY
124 return TRUE;
127 /* implementation of FindResourceExA */
128 static HRSRC find_resourceA( HMODULE hModule, LPCSTR type, LPCSTR name, WORD lang )
130 NTSTATUS status;
131 UNICODE_STRING nameW, typeW;
132 LDR_RESOURCE_INFO info;
133 const IMAGE_RESOURCE_DATA_ENTRY *entry = NULL;
135 __TRY
137 if ((status = get_res_nameA( name, &nameW )) != STATUS_SUCCESS) goto done;
138 if ((status = get_res_nameA( type, &typeW )) != STATUS_SUCCESS) goto done;
139 info.Type = (ULONG_PTR)typeW.Buffer;
140 info.Name = (ULONG_PTR)nameW.Buffer;
141 info.Language = lang;
142 status = LdrFindResource_U( hModule, &info, 3, &entry );
143 done:
144 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
146 __EXCEPT_PAGE_FAULT
148 SetLastError( ERROR_INVALID_PARAMETER );
150 __ENDTRY
152 if (HIWORD(nameW.Buffer)) HeapFree( GetProcessHeap(), 0, nameW.Buffer );
153 if (HIWORD(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
154 return (HRSRC)entry;
158 /* implementation of FindResourceExW */
159 static HRSRC find_resourceW( HMODULE hModule, LPCWSTR type, LPCWSTR name, WORD lang )
161 NTSTATUS status;
162 UNICODE_STRING nameW, typeW;
163 LDR_RESOURCE_INFO info;
164 const IMAGE_RESOURCE_DATA_ENTRY *entry = NULL;
166 nameW.Buffer = typeW.Buffer = NULL;
168 __TRY
170 if ((status = get_res_nameW( name, &nameW )) != STATUS_SUCCESS) goto done;
171 if ((status = get_res_nameW( type, &typeW )) != STATUS_SUCCESS) goto done;
172 info.Type = (ULONG_PTR)typeW.Buffer;
173 info.Name = (ULONG_PTR)nameW.Buffer;
174 info.Language = lang;
175 status = LdrFindResource_U( hModule, &info, 3, &entry );
176 done:
177 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
179 __EXCEPT_PAGE_FAULT
181 SetLastError( ERROR_INVALID_PARAMETER );
183 __ENDTRY
185 if (HIWORD(nameW.Buffer)) HeapFree( GetProcessHeap(), 0, nameW.Buffer );
186 if (HIWORD(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
187 return (HRSRC)entry;
190 /**********************************************************************
191 * FindResourceExA (KERNEL32.@)
193 HRSRC WINAPI FindResourceExA( HMODULE hModule, LPCSTR type, LPCSTR name, WORD lang )
195 TRACE( "%p %s %s %04x\n", hModule, debugstr_a(type), debugstr_a(name), lang );
197 if (!hModule) hModule = GetModuleHandleW(0);
198 else if (!HIWORD(hModule))
200 return HRSRC_32( FindResource16( HMODULE_16(hModule), name, type ) );
202 return find_resourceA( hModule, type, name, lang );
206 /**********************************************************************
207 * FindResourceA (KERNEL32.@)
209 HRSRC WINAPI FindResourceA( HMODULE hModule, LPCSTR name, LPCSTR type )
211 return FindResourceExA( hModule, type, name, MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL ) );
215 /**********************************************************************
216 * FindResourceExW (KERNEL32.@)
218 HRSRC WINAPI FindResourceExW( HMODULE hModule, LPCWSTR type, LPCWSTR name, WORD lang )
220 TRACE( "%p %s %s %04x\n", hModule, debugstr_w(type), debugstr_w(name), lang );
222 if (!hModule) hModule = GetModuleHandleW(0);
223 else if (!HIWORD(hModule))
225 LPSTR nameA, typeA;
226 HRSRC16 ret;
228 if (!get_res_name_type_WtoA( name, type, &nameA, &typeA )) return NULL;
230 ret = FindResource16( HMODULE_16(hModule), nameA, typeA );
231 if (HIWORD(nameA)) HeapFree( GetProcessHeap(), 0, nameA );
232 if (HIWORD(typeA)) HeapFree( GetProcessHeap(), 0, typeA );
233 return HRSRC_32(ret);
236 return find_resourceW( hModule, type, name, lang );
240 /**********************************************************************
241 * FindResourceW (KERNEL32.@)
243 HRSRC WINAPI FindResourceW( HINSTANCE hModule, LPCWSTR name, LPCWSTR type )
245 return FindResourceExW( hModule, type, name, MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL ) );
249 /**********************************************************************
250 * EnumResourceTypesA (KERNEL32.@)
252 BOOL WINAPI EnumResourceTypesA( HMODULE hmod, ENUMRESTYPEPROCA lpfun, LONG_PTR lparam )
254 int i;
255 BOOL ret = FALSE;
256 LPSTR type = NULL;
257 DWORD len = 0, newlen;
258 NTSTATUS status;
259 const IMAGE_RESOURCE_DIRECTORY *resdir;
260 const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
261 const IMAGE_RESOURCE_DIR_STRING_U *str;
263 TRACE( "%p %p %lx\n", hmod, lpfun, lparam );
265 if (!hmod) hmod = GetModuleHandleA( NULL );
267 if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &resdir )) != STATUS_SUCCESS)
269 SetLastError( RtlNtStatusToDosError(status) );
270 return FALSE;
272 et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
273 for (i = 0; i < resdir->NumberOfNamedEntries+resdir->NumberOfIdEntries; i++)
275 if (et[i].u1.s1.NameIsString)
277 str = (const IMAGE_RESOURCE_DIR_STRING_U *)((const BYTE *)resdir + et[i].u1.s1.NameOffset);
278 newlen = WideCharToMultiByte( CP_ACP, 0, str->NameString, str->Length, NULL, 0, NULL, NULL);
279 if (newlen + 1 > len)
281 len = newlen + 1;
282 HeapFree( GetProcessHeap(), 0, type );
283 if (!(type = HeapAlloc( GetProcessHeap(), 0, len ))) return FALSE;
285 WideCharToMultiByte( CP_ACP, 0, str->NameString, str->Length, type, len, NULL, NULL);
286 type[newlen] = 0;
287 ret = lpfun(hmod,type,lparam);
289 else
291 ret = lpfun( hmod, UIntToPtr(et[i].u1.s2.Id), lparam );
293 if (!ret) break;
295 HeapFree( GetProcessHeap(), 0, type );
296 return ret;
300 /**********************************************************************
301 * EnumResourceTypesW (KERNEL32.@)
303 BOOL WINAPI EnumResourceTypesW( HMODULE hmod, ENUMRESTYPEPROCW lpfun, LONG_PTR lparam )
305 int i, len = 0;
306 BOOL ret = FALSE;
307 LPWSTR type = NULL;
308 NTSTATUS status;
309 const IMAGE_RESOURCE_DIRECTORY *resdir;
310 const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
311 const IMAGE_RESOURCE_DIR_STRING_U *str;
313 TRACE( "%p %p %lx\n", hmod, lpfun, lparam );
315 if (!hmod) hmod = GetModuleHandleW( NULL );
317 if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &resdir )) != STATUS_SUCCESS)
319 SetLastError( RtlNtStatusToDosError(status) );
320 return FALSE;
322 et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
323 for (i = 0; i < resdir->NumberOfNamedEntries + resdir->NumberOfIdEntries; i++)
325 if (et[i].u1.s1.NameIsString)
327 str = (const IMAGE_RESOURCE_DIR_STRING_U *)((const BYTE *)resdir + et[i].u1.s1.NameOffset);
328 if (str->Length + 1 > len)
330 len = str->Length + 1;
331 HeapFree( GetProcessHeap(), 0, type );
332 if (!(type = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) ))) return FALSE;
334 memcpy(type, str->NameString, str->Length * sizeof (WCHAR));
335 type[str->Length] = 0;
336 ret = lpfun(hmod,type,lparam);
338 else
340 ret = lpfun( hmod, UIntToPtr(et[i].u1.s2.Id), lparam );
342 if (!ret) break;
344 HeapFree( GetProcessHeap(), 0, type );
345 return ret;
349 /**********************************************************************
350 * EnumResourceNamesA (KERNEL32.@)
352 BOOL WINAPI EnumResourceNamesA( HMODULE hmod, LPCSTR type, ENUMRESNAMEPROCA lpfun, LONG_PTR lparam )
354 int i;
355 BOOL ret = FALSE;
356 DWORD len = 0, newlen;
357 LPSTR name = NULL;
358 NTSTATUS status;
359 UNICODE_STRING typeW;
360 LDR_RESOURCE_INFO info;
361 const IMAGE_RESOURCE_DIRECTORY *basedir, *resdir;
362 const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
363 const IMAGE_RESOURCE_DIR_STRING_U *str;
365 TRACE( "%p %s %p %lx\n", hmod, debugstr_a(type), lpfun, lparam );
367 if (!hmod) hmod = GetModuleHandleA( NULL );
368 typeW.Buffer = NULL;
369 if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &basedir )) != STATUS_SUCCESS)
370 goto done;
371 if ((status = get_res_nameA( type, &typeW )) != STATUS_SUCCESS)
372 goto done;
373 info.Type = (ULONG_PTR)typeW.Buffer;
374 if ((status = LdrFindResourceDirectory_U( hmod, &info, 1, &resdir )) != STATUS_SUCCESS)
375 goto done;
377 et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
378 for (i = 0; i < resdir->NumberOfNamedEntries+resdir->NumberOfIdEntries; i++)
380 if (et[i].u1.s1.NameIsString)
382 str = (const IMAGE_RESOURCE_DIR_STRING_U *)((const BYTE *)basedir + et[i].u1.s1.NameOffset);
383 newlen = WideCharToMultiByte(CP_ACP, 0, str->NameString, str->Length, NULL, 0, NULL, NULL);
384 if (newlen + 1 > len)
386 len = newlen + 1;
387 HeapFree( GetProcessHeap(), 0, name );
388 if (!(name = HeapAlloc(GetProcessHeap(), 0, len + 1 )))
390 ret = FALSE;
391 break;
394 WideCharToMultiByte( CP_ACP, 0, str->NameString, str->Length, name, len, NULL, NULL );
395 name[newlen] = 0;
396 ret = lpfun(hmod,type,name,lparam);
398 else
400 ret = lpfun( hmod, type, UIntToPtr(et[i].u1.s2.Id), lparam );
402 if (!ret) break;
404 done:
405 HeapFree( GetProcessHeap(), 0, name );
406 if (HIWORD(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
407 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
408 return ret;
412 /**********************************************************************
413 * EnumResourceNamesW (KERNEL32.@)
415 BOOL WINAPI EnumResourceNamesW( HMODULE hmod, LPCWSTR type, ENUMRESNAMEPROCW lpfun, LONG_PTR lparam )
417 int i, len = 0;
418 BOOL ret = FALSE;
419 LPWSTR name = NULL;
420 NTSTATUS status;
421 UNICODE_STRING typeW;
422 LDR_RESOURCE_INFO info;
423 const IMAGE_RESOURCE_DIRECTORY *basedir, *resdir;
424 const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
425 const IMAGE_RESOURCE_DIR_STRING_U *str;
427 TRACE( "%p %s %p %lx\n", hmod, debugstr_w(type), lpfun, lparam );
429 if (!hmod) hmod = GetModuleHandleW( NULL );
430 typeW.Buffer = NULL;
431 if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &basedir )) != STATUS_SUCCESS)
432 goto done;
433 if ((status = get_res_nameW( type, &typeW )) != STATUS_SUCCESS)
434 goto done;
435 info.Type = (ULONG_PTR)typeW.Buffer;
436 if ((status = LdrFindResourceDirectory_U( hmod, &info, 1, &resdir )) != STATUS_SUCCESS)
437 goto done;
439 et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
440 for (i = 0; i < resdir->NumberOfNamedEntries+resdir->NumberOfIdEntries; i++)
442 if (et[i].u1.s1.NameIsString)
444 str = (const IMAGE_RESOURCE_DIR_STRING_U *)((const BYTE *)basedir + et[i].u1.s1.NameOffset);
445 if (str->Length + 1 > len)
447 len = str->Length + 1;
448 HeapFree( GetProcessHeap(), 0, name );
449 if (!(name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
451 ret = FALSE;
452 break;
455 memcpy(name, str->NameString, str->Length * sizeof (WCHAR));
456 name[str->Length] = 0;
457 ret = lpfun(hmod,type,name,lparam);
459 else
461 ret = lpfun( hmod, type, UIntToPtr(et[i].u1.s2.Id), lparam );
463 if (!ret) break;
465 done:
466 HeapFree( GetProcessHeap(), 0, name );
467 if (HIWORD(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
468 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
469 return ret;
473 /**********************************************************************
474 * EnumResourceLanguagesA (KERNEL32.@)
476 BOOL WINAPI EnumResourceLanguagesA( HMODULE hmod, LPCSTR type, LPCSTR name,
477 ENUMRESLANGPROCA lpfun, LONG_PTR lparam )
479 int i;
480 BOOL ret = FALSE;
481 NTSTATUS status;
482 UNICODE_STRING typeW, nameW;
483 LDR_RESOURCE_INFO info;
484 const IMAGE_RESOURCE_DIRECTORY *basedir, *resdir;
485 const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
487 TRACE( "%p %s %s %p %lx\n", hmod, debugstr_a(type), debugstr_a(name), lpfun, lparam );
489 if (!hmod) hmod = GetModuleHandleA( NULL );
490 typeW.Buffer = nameW.Buffer = NULL;
491 if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &basedir )) != STATUS_SUCCESS)
492 goto done;
493 if ((status = get_res_nameA( type, &typeW )) != STATUS_SUCCESS)
494 goto done;
495 if ((status = get_res_nameA( name, &nameW )) != STATUS_SUCCESS)
496 goto done;
497 info.Type = (ULONG_PTR)typeW.Buffer;
498 info.Name = (ULONG_PTR)nameW.Buffer;
499 if ((status = LdrFindResourceDirectory_U( hmod, &info, 2, &resdir )) != STATUS_SUCCESS)
500 goto done;
502 et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
503 for (i = 0; i < resdir->NumberOfNamedEntries + resdir->NumberOfIdEntries; i++)
505 ret = lpfun( hmod, type, name, et[i].u1.s2.Id, lparam );
506 if (!ret) break;
508 done:
509 if (HIWORD(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
510 if (HIWORD(nameW.Buffer)) HeapFree( GetProcessHeap(), 0, nameW.Buffer );
511 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
512 return ret;
516 /**********************************************************************
517 * EnumResourceLanguagesW (KERNEL32.@)
519 BOOL WINAPI EnumResourceLanguagesW( HMODULE hmod, LPCWSTR type, LPCWSTR name,
520 ENUMRESLANGPROCW lpfun, LONG_PTR lparam )
522 int i;
523 BOOL ret = FALSE;
524 NTSTATUS status;
525 UNICODE_STRING typeW, nameW;
526 LDR_RESOURCE_INFO info;
527 const IMAGE_RESOURCE_DIRECTORY *basedir, *resdir;
528 const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
530 TRACE( "%p %s %s %p %lx\n", hmod, debugstr_w(type), debugstr_w(name), lpfun, lparam );
532 if (!hmod) hmod = GetModuleHandleW( NULL );
533 typeW.Buffer = nameW.Buffer = NULL;
534 if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &basedir )) != STATUS_SUCCESS)
535 goto done;
536 if ((status = get_res_nameW( type, &typeW )) != STATUS_SUCCESS)
537 goto done;
538 if ((status = get_res_nameW( name, &nameW )) != STATUS_SUCCESS)
539 goto done;
540 info.Type = (ULONG_PTR)typeW.Buffer;
541 info.Name = (ULONG_PTR)nameW.Buffer;
542 if ((status = LdrFindResourceDirectory_U( hmod, &info, 2, &resdir )) != STATUS_SUCCESS)
543 goto done;
545 et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
546 for (i = 0; i < resdir->NumberOfNamedEntries + resdir->NumberOfIdEntries; i++)
548 ret = lpfun( hmod, type, name, et[i].u1.s2.Id, lparam );
549 if (!ret) break;
551 done:
552 if (HIWORD(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
553 if (HIWORD(nameW.Buffer)) HeapFree( GetProcessHeap(), 0, nameW.Buffer );
554 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
555 return ret;
559 /**********************************************************************
560 * LoadResource (KERNEL32.@)
562 HGLOBAL WINAPI LoadResource( HINSTANCE hModule, HRSRC hRsrc )
564 NTSTATUS status;
565 void *ret = NULL;
567 TRACE( "%p %p\n", hModule, hRsrc );
569 if (hModule && !HIWORD(hModule))
570 /* FIXME: should convert return to 32-bit resource */
571 return HGLOBAL_32( LoadResource16( HMODULE_16(hModule), HRSRC_16(hRsrc) ) );
573 if (!hRsrc) return 0;
574 if (!hModule) hModule = GetModuleHandleA( NULL );
575 status = LdrAccessResource( hModule, (IMAGE_RESOURCE_DATA_ENTRY *)hRsrc, &ret, NULL );
576 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
577 return ret;
581 /**********************************************************************
582 * LockResource (KERNEL32.@)
584 LPVOID WINAPI LockResource( HGLOBAL handle )
586 TRACE("(%p)\n", handle );
588 if (HIWORD( handle )) /* 32-bit memory handle */
589 return (LPVOID)handle;
591 /* 16-bit memory handle */
592 return LockResource16( HGLOBAL_16(handle) );
596 /**********************************************************************
597 * FreeResource (KERNEL32.@)
599 BOOL WINAPI FreeResource( HGLOBAL handle )
601 if (HIWORD(handle)) return 0; /* 32-bit memory handle: nothing to do */
602 return FreeResource16( HGLOBAL_16(handle) );
606 /**********************************************************************
607 * SizeofResource (KERNEL32.@)
609 DWORD WINAPI SizeofResource( HINSTANCE hModule, HRSRC hRsrc )
611 if (hModule && !HIWORD(hModule))
612 return SizeofResource16( HMODULE_16(hModule), HRSRC_16(hRsrc) );
614 if (!hRsrc) return 0;
615 return ((PIMAGE_RESOURCE_DATA_ENTRY)hRsrc)->Size;
619 * Data structure for updating resources.
620 * Type/Name/Language is a keyset for accessing resource data.
622 * QUEUEDUPDATES (root) ->
623 * list of struct resource_dir_entry (Type) ->
624 * list of struct resource_dir_entry (Name) ->
625 * list of struct resource_data Language + Data
628 typedef struct
630 LPWSTR pFileName;
631 BOOL bDeleteExistingResources;
632 struct list root;
633 } QUEUEDUPDATES;
635 /* this structure is shared for types and names */
636 struct resource_dir_entry {
637 struct list entry;
638 LPWSTR id;
639 struct list children;
642 /* this structure is the leaf */
643 struct resource_data {
644 struct list entry;
645 LANGID lang;
646 DWORD codepage;
647 DWORD cbData;
648 void *lpData;
651 static int resource_strcmp( LPCWSTR a, LPCWSTR b )
653 if ( a == b )
654 return 0;
655 if (HIWORD( a ) && HIWORD( b ) )
656 return lstrcmpW( a, b );
657 /* strings come before ids */
658 if (HIWORD( a ) && !HIWORD( b ))
659 return -1;
660 if (HIWORD( b ) && !HIWORD( a ))
661 return 1;
662 return ( a < b ) ? -1 : 1;
665 static struct resource_dir_entry *find_resource_dir_entry( struct list *dir, LPCWSTR id )
667 struct resource_dir_entry *ent;
669 /* match either IDs or strings */
670 LIST_FOR_EACH_ENTRY( ent, dir, struct resource_dir_entry, entry )
671 if (!resource_strcmp( id, ent->id ))
672 return ent;
674 return NULL;
677 static struct resource_data *find_resource_data( struct list *dir, LANGID lang )
679 struct resource_data *res_data;
681 /* match only languages here */
682 LIST_FOR_EACH_ENTRY( res_data, dir, struct resource_data, entry )
683 if ( lang == res_data->lang )
684 return res_data;
686 return NULL;
689 static void add_resource_dir_entry( struct list *dir, struct resource_dir_entry *resdir )
691 struct resource_dir_entry *ent;
693 LIST_FOR_EACH_ENTRY( ent, dir, struct resource_dir_entry, entry )
695 if (0>resource_strcmp( ent->id, resdir->id ))
696 continue;
698 list_add_before( &ent->entry, &resdir->entry );
699 return;
701 list_add_tail( dir, &resdir->entry );
704 static void add_resource_data_entry( struct list *dir, struct resource_data *resdata )
706 struct resource_data *ent;
708 LIST_FOR_EACH_ENTRY( ent, dir, struct resource_data, entry )
710 if (ent->lang < resdata->lang)
711 continue;
713 list_add_before( &ent->entry, &resdata->entry );
714 return;
716 list_add_tail( dir, &resdata->entry );
719 static LPWSTR res_strdupW( LPCWSTR str )
721 LPWSTR ret;
722 UINT len;
724 if (HIWORD(str) == 0)
725 return (LPWSTR) (UINT_PTR) LOWORD(str);
726 len = (lstrlenW( str ) + 1) * sizeof (WCHAR);
727 ret = HeapAlloc( GetProcessHeap(), 0, len );
728 memcpy( ret, str, len );
729 return ret;
732 static void res_free_str( LPWSTR str )
734 if (HIWORD(str))
735 HeapFree( GetProcessHeap(), 0, str );
738 static BOOL update_add_resource( QUEUEDUPDATES *updates, LPCWSTR Type, LPCWSTR Name,
739 struct resource_data *resdata, BOOL overwrite_existing )
741 struct resource_dir_entry *restype, *resname;
742 struct resource_data *existing;
744 TRACE("%p %s %s %p %d\n", updates,
745 debugstr_w(Type), debugstr_w(Name), resdata, overwrite_existing );
747 restype = find_resource_dir_entry( &updates->root, Type );
748 if (!restype)
750 restype = HeapAlloc( GetProcessHeap(), 0, sizeof *restype );
751 restype->id = res_strdupW( Type );
752 list_init( &restype->children );
753 add_resource_dir_entry( &updates->root, restype );
756 resname = find_resource_dir_entry( &restype->children, Name );
757 if (!resname)
759 resname = HeapAlloc( GetProcessHeap(), 0, sizeof *resname );
760 resname->id = res_strdupW( Name );
761 list_init( &resname->children );
762 add_resource_dir_entry( &restype->children, resname );
766 * If there's an existing resource entry with matching (Type,Name,Language)
767 * it needs to be removed before adding the new data.
769 existing = find_resource_data( &resname->children, resdata->lang );
770 if (existing)
772 if (!overwrite_existing)
773 return TRUE;
774 list_remove( &existing->entry );
775 HeapFree( GetProcessHeap(), 0, existing );
778 add_resource_data_entry( &resname->children, resdata );
780 return TRUE;
783 static struct resource_data *allocate_resource_data( WORD Language, DWORD codepage,
784 LPVOID lpData, DWORD cbData, BOOL copy_data )
786 struct resource_data *resdata;
788 if (!lpData || !cbData)
789 return NULL;
791 resdata = HeapAlloc( GetProcessHeap(), 0, sizeof *resdata + (copy_data ? cbData : 0) );
792 if (resdata)
794 resdata->lang = Language;
795 resdata->codepage = codepage;
796 resdata->cbData = cbData;
797 if (copy_data)
799 resdata->lpData = &resdata[1];
800 memcpy( resdata->lpData, lpData, cbData );
802 else
803 resdata->lpData = lpData;
806 return resdata;
809 static void free_resource_directory( struct list *head, int level )
811 struct list *ptr = NULL;
813 while ((ptr = list_head( head )))
815 list_remove( ptr );
816 if (level)
818 struct resource_dir_entry *ent;
820 ent = LIST_ENTRY( ptr, struct resource_dir_entry, entry );
821 res_free_str( ent->id );
822 free_resource_directory( &ent->children, level - 1 );
823 HeapFree(GetProcessHeap(), 0, ent);
825 else
827 struct resource_data *data;
829 data = LIST_ENTRY( ptr, struct resource_data, entry );
830 HeapFree( GetProcessHeap(), 0, data );
835 static IMAGE_NT_HEADERS *get_nt_header( void *base, DWORD mapping_size )
837 IMAGE_NT_HEADERS *nt;
838 IMAGE_DOS_HEADER *dos;
840 if (mapping_size<sizeof (*dos))
841 return NULL;
843 dos = base;
844 if (dos->e_magic != IMAGE_DOS_SIGNATURE)
845 return NULL;
847 if ((dos->e_lfanew + sizeof (*nt)) > mapping_size)
848 return NULL;
850 nt = (void*) ((BYTE*)base + dos->e_lfanew);
852 if (nt->Signature != IMAGE_NT_SIGNATURE)
853 return NULL;
855 return nt;
858 static IMAGE_SECTION_HEADER *get_section_header( void *base, DWORD mapping_size, DWORD *num_sections )
860 IMAGE_NT_HEADERS *nt;
861 IMAGE_SECTION_HEADER *sec;
862 DWORD section_ofs;
864 nt = get_nt_header( base, mapping_size );
865 if (!nt)
866 return NULL;
868 /* check that we don't go over the end of the file accessing the sections */
869 section_ofs = FIELD_OFFSET(IMAGE_NT_HEADERS, OptionalHeader) + nt->FileHeader.SizeOfOptionalHeader;
870 if ((nt->FileHeader.NumberOfSections * sizeof (*sec) + section_ofs) > mapping_size)
871 return NULL;
873 if (num_sections)
874 *num_sections = nt->FileHeader.NumberOfSections;
876 /* from here we have a valid PE exe to update */
877 return (void*) ((BYTE*)nt + section_ofs);
880 static BOOL check_pe_exe( HANDLE file, QUEUEDUPDATES *updates )
882 const IMAGE_NT_HEADERS *nt;
883 const IMAGE_SECTION_HEADER *sec;
884 BOOL ret = FALSE;
885 HANDLE mapping;
886 DWORD mapping_size, num_sections = 0;
887 void *base = NULL;
889 mapping_size = GetFileSize( file, NULL );
891 mapping = CreateFileMappingW( file, NULL, PAGE_READONLY, 0, 0, NULL );
892 if (!mapping)
893 goto done;
895 base = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, mapping_size );
896 if (!base)
897 goto done;
899 nt = get_nt_header( base, mapping_size );
900 if (!nt)
901 goto done;
903 TRACE("resources: %08x %08x\n",
904 nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress,
905 nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size);
907 sec = get_section_header( base, mapping_size, &num_sections );
908 if (!sec)
909 goto done;
911 ret = TRUE;
913 done:
914 if (base)
915 UnmapViewOfFile( base );
916 if (mapping)
917 CloseHandle( mapping );
919 return ret;
922 struct resource_size_info {
923 DWORD types_ofs;
924 DWORD names_ofs;
925 DWORD langs_ofs;
926 DWORD data_entry_ofs;
927 DWORD strings_ofs;
928 DWORD data_ofs;
929 DWORD total_size;
932 struct mapping_info {
933 HANDLE file;
934 HANDLE mapping;
935 void *base;
936 DWORD size;
937 BOOL read_write;
940 static const IMAGE_SECTION_HEADER *section_from_rva( void *base, DWORD mapping_size, DWORD rva )
942 const IMAGE_SECTION_HEADER *sec;
943 DWORD num_sections = 0;
944 int i;
946 sec = get_section_header( base, mapping_size, &num_sections );
947 if (!sec)
948 return NULL;
950 for (i=num_sections-1; i>=0; i--)
952 if (sec[i].VirtualAddress <= rva &&
953 rva <= (DWORD)sec[i].VirtualAddress + sec[i].SizeOfRawData)
955 return &sec[i];
959 return NULL;
962 static void *address_from_rva( void *base, DWORD mapping_size, DWORD rva, DWORD len )
964 const IMAGE_SECTION_HEADER *sec;
966 sec = section_from_rva( base, mapping_size, rva );
967 if (!sec)
968 return NULL;
970 if (rva + len <= (DWORD)sec->VirtualAddress + sec->SizeOfRawData)
971 return (void*)((LPBYTE) base + (sec->PointerToRawData + rva - sec->VirtualAddress));
973 return NULL;
976 static LPWSTR resource_dup_string( const IMAGE_RESOURCE_DIRECTORY *root, const IMAGE_RESOURCE_DIRECTORY_ENTRY *entry )
978 const IMAGE_RESOURCE_DIR_STRING_U* string;
979 LPWSTR s;
981 if (!entry->u1.s1.NameIsString)
982 return UIntToPtr(entry->u1.s2.Id);
984 string = (const IMAGE_RESOURCE_DIR_STRING_U*) (((const char *)root) + entry->u1.s1.NameOffset);
985 s = HeapAlloc(GetProcessHeap(), 0, (string->Length + 1)*sizeof (WCHAR) );
986 memcpy( s, string->NameString, (string->Length + 1)*sizeof (WCHAR) );
987 s[string->Length] = 0;
989 return s;
992 /* this function is based on the code in winedump's pe.c */
993 static BOOL enumerate_mapped_resources( QUEUEDUPDATES *updates,
994 void *base, DWORD mapping_size,
995 const IMAGE_RESOURCE_DIRECTORY *root )
997 const IMAGE_RESOURCE_DIRECTORY *namedir, *langdir;
998 const IMAGE_RESOURCE_DIRECTORY_ENTRY *e1, *e2, *e3;
999 const IMAGE_RESOURCE_DATA_ENTRY *data;
1000 DWORD i, j, k;
1002 TRACE("version (%d.%d) %d named %d id entries\n",
1003 root->MajorVersion, root->MinorVersion, root->NumberOfNamedEntries, root->NumberOfIdEntries);
1005 for (i = 0; i< root->NumberOfNamedEntries + root->NumberOfIdEntries; i++)
1007 LPWSTR Type;
1009 e1 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(root + 1) + i;
1011 Type = resource_dup_string( root, e1 );
1013 namedir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e1->u2.s3.OffsetToDirectory);
1014 for (j = 0; j < namedir->NumberOfNamedEntries + namedir->NumberOfIdEntries; j++)
1016 LPWSTR Name;
1018 e2 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(namedir + 1) + j;
1020 Name = resource_dup_string( root, e2 );
1022 langdir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e2->u2.s3.OffsetToDirectory);
1023 for (k = 0; k < langdir->NumberOfNamedEntries + langdir->NumberOfIdEntries; k++)
1025 LANGID Lang;
1026 void *p;
1027 struct resource_data *resdata;
1029 e3 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(langdir + 1) + k;
1031 Lang = e3->u1.s2.Id;
1033 data = (const IMAGE_RESOURCE_DATA_ENTRY *)((const char *)root + e3->u2.OffsetToData);
1035 p = address_from_rva( base, mapping_size, data->OffsetToData, data->Size );
1037 resdata = allocate_resource_data( Lang, data->CodePage, p, data->Size, FALSE );
1038 if (resdata)
1039 update_add_resource( updates, Type, Name, resdata, FALSE );
1041 res_free_str( Name );
1043 res_free_str( Type );
1046 return TRUE;
1049 static BOOL read_mapped_resources( QUEUEDUPDATES *updates, void *base, DWORD mapping_size )
1051 const IMAGE_RESOURCE_DIRECTORY *root;
1052 const IMAGE_NT_HEADERS *nt;
1053 const IMAGE_SECTION_HEADER *sec;
1054 DWORD num_sections = 0, i;
1056 nt = get_nt_header( base, mapping_size );
1057 if (!nt)
1058 return FALSE;
1060 sec = get_section_header( base, mapping_size, &num_sections );
1061 if (!sec)
1062 return FALSE;
1064 for (i=0; i<num_sections; i++)
1065 if (!memcmp(sec[i].Name, ".rsrc", 6))
1066 break;
1068 if (i == num_sections)
1069 return TRUE;
1071 /* check the resource data is inside the mapping */
1072 if (sec[i].PointerToRawData > mapping_size ||
1073 (sec[i].PointerToRawData + sec[i].SizeOfRawData) > mapping_size)
1074 return TRUE;
1076 TRACE("found .rsrc at %08x, size %08x\n", sec[i].PointerToRawData, sec[i].SizeOfRawData);
1078 root = (void*) ((BYTE*)base + sec[i].PointerToRawData);
1079 enumerate_mapped_resources( updates, base, mapping_size, root );
1081 return TRUE;
1084 static BOOL map_file_into_memory( struct mapping_info *mi )
1086 DWORD page_attr, perm;
1088 if (mi->read_write)
1090 page_attr = PAGE_READWRITE;
1091 perm = FILE_MAP_WRITE | FILE_MAP_READ;
1093 else
1095 page_attr = PAGE_READONLY;
1096 perm = FILE_MAP_READ;
1099 mi->mapping = CreateFileMappingW( mi->file, NULL, page_attr, 0, 0, NULL );
1100 if (!mi->mapping)
1101 return FALSE;
1103 mi->base = MapViewOfFile( mi->mapping, perm, 0, 0, mi->size );
1104 if (!mi->base)
1105 return FALSE;
1107 return TRUE;
1110 static BOOL unmap_file_from_memory( struct mapping_info *mi )
1112 if (mi->base)
1113 UnmapViewOfFile( mi->base );
1114 mi->base = NULL;
1115 if (mi->mapping)
1116 CloseHandle( mi->mapping );
1117 mi->mapping = NULL;
1118 return TRUE;
1121 static void destroy_mapping( struct mapping_info *mi )
1123 if (!mi)
1124 return;
1125 unmap_file_from_memory( mi );
1126 if (mi->file)
1127 CloseHandle( mi->file );
1128 HeapFree( GetProcessHeap(), 0, mi );
1131 static struct mapping_info *create_mapping( LPCWSTR name, BOOL rw )
1133 struct mapping_info *mi;
1135 mi = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof *mi );
1136 if (!mi)
1137 return NULL;
1139 mi->read_write = rw;
1141 mi->file = CreateFileW( name, GENERIC_READ | (rw ? GENERIC_WRITE : 0),
1142 0, NULL, OPEN_EXISTING, 0, 0 );
1144 if (mi->file != INVALID_HANDLE_VALUE)
1146 mi->size = GetFileSize( mi->file, NULL );
1148 if (map_file_into_memory( mi ))
1149 return mi;
1152 unmap_file_from_memory( mi );
1153 HeapFree( GetProcessHeap(), 0, mi );
1155 return NULL;
1158 static BOOL resize_mapping( struct mapping_info *mi, DWORD new_size )
1160 if (!unmap_file_from_memory( mi ))
1161 return FALSE;
1163 /* change the file size */
1164 SetFilePointer( mi->file, new_size, NULL, FILE_BEGIN );
1165 if (!SetEndOfFile( mi->file ))
1167 ERR("failed to set file size to %08x\n", new_size );
1168 return FALSE;
1171 mi->size = new_size;
1173 return map_file_into_memory( mi );
1176 static void get_resource_sizes( QUEUEDUPDATES *updates, struct resource_size_info *si )
1178 struct resource_dir_entry *types, *names;
1179 struct resource_data *data;
1180 DWORD num_types = 0, num_names = 0, num_langs = 0, strings_size = 0, data_size = 0;
1182 memset( si, 0, sizeof *si );
1184 LIST_FOR_EACH_ENTRY( types, &updates->root, struct resource_dir_entry, entry )
1186 num_types++;
1187 if (HIWORD( types->id ))
1188 strings_size += sizeof (WORD) + lstrlenW( types->id )*sizeof (WCHAR);
1190 LIST_FOR_EACH_ENTRY( names, &types->children, struct resource_dir_entry, entry )
1192 num_names++;
1194 if (HIWORD( names->id ))
1195 strings_size += sizeof (WORD) + lstrlenW( names->id )*sizeof (WCHAR);
1197 LIST_FOR_EACH_ENTRY( data, &names->children, struct resource_data, entry )
1199 num_langs++;
1200 data_size += (data->cbData + 3) & ~3;
1205 /* names are at the end of the types */
1206 si->names_ofs = sizeof (IMAGE_RESOURCE_DIRECTORY) +
1207 num_types * sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1209 /* language directories are at the end of the names */
1210 si->langs_ofs = si->names_ofs +
1211 num_types * sizeof (IMAGE_RESOURCE_DIRECTORY) +
1212 num_names * sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1214 si->data_entry_ofs = si->langs_ofs +
1215 num_names * sizeof (IMAGE_RESOURCE_DIRECTORY) +
1216 num_langs * sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1218 si->strings_ofs = si->data_entry_ofs +
1219 num_langs * sizeof (IMAGE_RESOURCE_DATA_ENTRY);
1221 si->data_ofs = si->strings_ofs + ((strings_size + 3) & ~3);
1223 si->total_size = si->data_ofs + data_size;
1225 TRACE("names %08x langs %08x data entries %08x strings %08x data %08x total %08x\n",
1226 si->names_ofs, si->langs_ofs, si->data_entry_ofs,
1227 si->strings_ofs, si->data_ofs, si->total_size);
1230 static void res_write_padding( BYTE *res_base, DWORD size )
1232 static const BYTE pad[] = {
1233 'P','A','D','D','I','N','G','X','X','P','A','D','D','I','N','G' };
1234 DWORD i;
1236 for ( i = 0; i < size / sizeof pad; i++ )
1237 memcpy( &res_base[i*sizeof pad], pad, sizeof pad );
1238 memcpy( &res_base[i*sizeof pad], pad, size%sizeof pad );
1241 static BOOL write_resources( QUEUEDUPDATES *updates, LPBYTE base, struct resource_size_info *si, DWORD rva )
1243 struct resource_dir_entry *types, *names;
1244 struct resource_data *data;
1245 IMAGE_RESOURCE_DIRECTORY *root;
1247 TRACE("%p %p %p %08x\n", updates, base, si, rva );
1249 memset( base, 0, si->total_size );
1251 /* the root entry always exists */
1252 root = (IMAGE_RESOURCE_DIRECTORY*) base;
1253 memset( root, 0, sizeof *root );
1254 root->MajorVersion = 4;
1255 si->types_ofs = sizeof *root;
1256 LIST_FOR_EACH_ENTRY( types, &updates->root, struct resource_dir_entry, entry )
1258 IMAGE_RESOURCE_DIRECTORY_ENTRY *e1;
1259 IMAGE_RESOURCE_DIRECTORY *namedir;
1261 e1 = (IMAGE_RESOURCE_DIRECTORY_ENTRY*) &base[si->types_ofs];
1262 memset( e1, 0, sizeof *e1 );
1263 if (HIWORD( types->id ))
1265 WCHAR *strings;
1266 DWORD len;
1268 root->NumberOfNamedEntries++;
1269 e1->u1.s1.NameIsString = 1;
1270 e1->u1.s1.NameOffset = si->strings_ofs;
1272 strings = (WCHAR*) &base[si->strings_ofs];
1273 len = lstrlenW( types->id );
1274 strings[0] = len;
1275 memcpy( &strings[1], types->id, len * sizeof (WCHAR) );
1276 si->strings_ofs += (len + 1) * sizeof (WCHAR);
1278 else
1280 root->NumberOfIdEntries++;
1281 e1->u1.s2.Id = LOWORD( types->id );
1283 e1->u2.s3.OffsetToDirectory = si->names_ofs;
1284 e1->u2.s3.DataIsDirectory = TRUE;
1285 si->types_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1287 namedir = (IMAGE_RESOURCE_DIRECTORY*) &base[si->names_ofs];
1288 memset( namedir, 0, sizeof *namedir );
1289 namedir->MajorVersion = 4;
1290 si->names_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY);
1292 LIST_FOR_EACH_ENTRY( names, &types->children, struct resource_dir_entry, entry )
1294 IMAGE_RESOURCE_DIRECTORY_ENTRY *e2;
1295 IMAGE_RESOURCE_DIRECTORY *langdir;
1297 e2 = (IMAGE_RESOURCE_DIRECTORY_ENTRY*) &base[si->names_ofs];
1298 memset( e2, 0, sizeof *e2 );
1299 if (HIWORD( names->id ))
1301 WCHAR *strings;
1302 DWORD len;
1304 namedir->NumberOfNamedEntries++;
1305 e2->u1.s1.NameIsString = 1;
1306 e2->u1.s1.NameOffset = si->strings_ofs;
1308 strings = (WCHAR*) &base[si->strings_ofs];
1309 len = lstrlenW( names->id );
1310 strings[0] = len;
1311 memcpy( &strings[1], names->id, len * sizeof (WCHAR) );
1312 si->strings_ofs += (len + 1) * sizeof (WCHAR);
1314 else
1316 namedir->NumberOfIdEntries++;
1317 e2->u1.s2.Id = LOWORD( names->id );
1319 e2->u2.s3.OffsetToDirectory = si->langs_ofs;
1320 e2->u2.s3.DataIsDirectory = TRUE;
1321 si->names_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1323 langdir = (IMAGE_RESOURCE_DIRECTORY*) &base[si->langs_ofs];
1324 memset( langdir, 0, sizeof *langdir );
1325 langdir->MajorVersion = 4;
1326 si->langs_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY);
1328 LIST_FOR_EACH_ENTRY( data, &names->children, struct resource_data, entry )
1330 IMAGE_RESOURCE_DIRECTORY_ENTRY *e3;
1331 IMAGE_RESOURCE_DATA_ENTRY *de;
1332 int pad_size;
1334 e3 = (IMAGE_RESOURCE_DIRECTORY_ENTRY*) &base[si->langs_ofs];
1335 memset( e3, 0, sizeof *e3 );
1336 langdir->NumberOfIdEntries++;
1337 e3->u1.s2.Id = LOWORD( data->lang );
1338 e3->u2.OffsetToData = si->data_entry_ofs;
1340 si->langs_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1342 /* write out all the data entries */
1343 de = (IMAGE_RESOURCE_DATA_ENTRY*) &base[si->data_entry_ofs];
1344 memset( de, 0, sizeof *de );
1345 de->OffsetToData = si->data_ofs + rva;
1346 de->Size = data->cbData;
1347 de->CodePage = data->codepage;
1348 si->data_entry_ofs += sizeof (IMAGE_RESOURCE_DATA_ENTRY);
1350 /* write out the resource data */
1351 memcpy( &base[si->data_ofs], data->lpData, data->cbData );
1352 si->data_ofs += data->cbData;
1354 pad_size = (-si->data_ofs)&3;
1355 res_write_padding( &base[si->data_ofs], pad_size );
1356 si->data_ofs += pad_size;
1361 return TRUE;
1365 * FIXME:
1366 * Assumes that the resources are in .rsrc
1367 * and .rsrc is the last section in the file.
1368 * Not sure whether updating resources will other cases on Windows.
1369 * If the resources lie in a section containing other data,
1370 * resizing that section could possibly cause trouble.
1371 * If the section with the resources isn't last, the remaining
1372 * sections need to be moved down in the file, and the section header
1373 * would need to be adjusted.
1374 * If we needed to add a section, what would we name it?
1375 * If we needed to add a section and there wasn't space in the file
1376 * header, how would that work?
1377 * Seems that at least some of these cases can't be handled properly.
1379 static IMAGE_SECTION_HEADER *get_resource_section( void *base, DWORD mapping_size )
1381 IMAGE_SECTION_HEADER *sec;
1382 IMAGE_NT_HEADERS *nt;
1383 DWORD i, num_sections = 0;
1385 nt = get_nt_header( base, mapping_size );
1386 if (!nt)
1387 return NULL;
1389 sec = get_section_header( base, mapping_size, &num_sections );
1390 if (!sec)
1391 return NULL;
1393 /* find the resources section */
1394 for (i=0; i<num_sections; i++)
1395 if (!memcmp(sec[i].Name, ".rsrc", 6))
1396 break;
1398 if (i == num_sections)
1400 FIXME(".rsrc doesn't exist\n");
1401 return NULL;
1404 /* check that the resources section is last */
1405 if (i != num_sections - 1)
1407 FIXME(".rsrc isn't the last section\n");
1408 return NULL;
1411 return &sec[i];
1414 static DWORD get_init_data_size( void *base, DWORD mapping_size )
1416 DWORD i, sz = 0, num_sections = 0;
1417 IMAGE_SECTION_HEADER *s;
1419 s = get_section_header( base, mapping_size, &num_sections );
1421 for (i=0; i<num_sections; i++)
1422 if (s[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
1423 sz += s[i].SizeOfRawData;
1425 TRACE("size = %08x\n", sz);
1427 return sz;
1430 static BOOL write_raw_resources( QUEUEDUPDATES *updates )
1432 static const WCHAR prefix[] = { 'r','e','s','u',0 };
1433 WCHAR tempdir[MAX_PATH], tempfile[MAX_PATH];
1434 DWORD mapping_size, section_size, old_size;
1435 BOOL ret = FALSE;
1436 IMAGE_SECTION_HEADER *sec;
1437 IMAGE_NT_HEADERS *nt;
1438 struct resource_size_info res_size;
1439 BYTE *res_base;
1440 struct mapping_info *read_map = NULL, *write_map = NULL;
1442 /* copy the exe to a temp file then update the temp file... */
1443 tempdir[0] = 0;
1444 if (!GetTempPathW( MAX_PATH, tempdir ))
1445 return ret;
1447 if (!GetTempFileNameW( tempdir, prefix, 0, tempfile ))
1448 return ret;
1450 if (!CopyFileW( updates->pFileName, tempfile, FALSE ))
1451 goto done;
1453 TRACE("tempfile %s\n", debugstr_w(tempfile));
1455 if (!updates->bDeleteExistingResources)
1457 read_map = create_mapping( updates->pFileName, FALSE );
1458 if (!read_map)
1459 goto done;
1461 ret = read_mapped_resources( updates, read_map->base, read_map->size );
1462 if (!ret)
1464 ERR("failed to read existing resources\n");
1465 goto done;
1469 write_map = create_mapping( tempfile, TRUE );
1470 if (!write_map)
1471 goto done;
1473 nt = get_nt_header( write_map->base, write_map->size );
1474 if (!nt)
1475 goto done;
1477 if (nt->OptionalHeader.SectionAlignment <= 0)
1479 ERR("invalid section alignment %04x\n", nt->OptionalHeader.SectionAlignment);
1480 goto done;
1483 sec = get_resource_section( write_map->base, write_map->size );
1484 if (!sec)
1485 goto done;
1487 if ((sec->SizeOfRawData + sec->PointerToRawData) != write_map->size)
1489 FIXME(".rsrc isn't at the end of the image %08x + %08x != %08x\n",
1490 sec->SizeOfRawData, sec->PointerToRawData, write_map->size);
1491 goto done;
1494 TRACE("before .rsrc at %08x, size %08x\n", sec->PointerToRawData, sec->SizeOfRawData);
1496 get_resource_sizes( updates, &res_size );
1498 /* round up the section size */
1499 section_size = res_size.total_size;
1500 section_size += (-section_size) % nt->OptionalHeader.SectionAlignment;
1502 mapping_size = sec->PointerToRawData + section_size;
1504 TRACE("requires %08x (%08x) bytes\n", res_size.total_size, section_size );
1506 /* check if the file size needs to be changed */
1507 if (section_size != sec->SizeOfRawData)
1509 old_size = write_map->size;
1511 TRACE("file size %08x -> %08x\n", old_size, mapping_size);
1513 /* unmap the file before changing the file size */
1514 ret = resize_mapping( write_map, mapping_size );
1516 /* get the pointers again - they might be different after remapping */
1517 nt = get_nt_header( write_map->base, mapping_size );
1518 if (!nt)
1520 ERR("couldn't get NT header\n");
1521 goto done;
1524 sec = get_resource_section( write_map->base, mapping_size );
1525 if (!sec)
1526 goto done;
1528 /* adjust the PE header information */
1529 nt->OptionalHeader.SizeOfImage += (mapping_size - old_size);
1530 sec->SizeOfRawData = section_size;
1531 sec->Misc.VirtualSize = section_size;
1532 nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = res_size.total_size;
1533 nt->OptionalHeader.SizeOfInitializedData = get_init_data_size( write_map->base, mapping_size );
1536 res_base = (LPBYTE) write_map->base + sec->PointerToRawData;
1538 TRACE("base = %p offset = %08x\n", write_map->base, sec->PointerToRawData);
1540 ret = write_resources( updates, res_base, &res_size, sec->VirtualAddress );
1542 res_write_padding( res_base + res_size.total_size, section_size - res_size.total_size );
1544 TRACE("after .rsrc at %08x, size %08x\n", sec->PointerToRawData, sec->SizeOfRawData);
1546 done:
1547 destroy_mapping( read_map );
1548 destroy_mapping( write_map );
1550 if (ret)
1551 ret = CopyFileW( tempfile, updates->pFileName, FALSE );
1553 DeleteFileW( tempfile );
1555 return ret;
1558 /***********************************************************************
1559 * BeginUpdateResourceW (KERNEL32.@)
1561 HANDLE WINAPI BeginUpdateResourceW( LPCWSTR pFileName, BOOL bDeleteExistingResources )
1563 QUEUEDUPDATES *updates = NULL;
1564 HANDLE hUpdate, file, ret = NULL;
1566 TRACE("%s, %d\n", debugstr_w(pFileName), bDeleteExistingResources);
1568 hUpdate = GlobalAlloc(GHND, sizeof(QUEUEDUPDATES));
1569 if (!hUpdate)
1570 return ret;
1572 updates = GlobalLock(hUpdate);
1573 if (updates)
1575 list_init( &updates->root );
1576 updates->bDeleteExistingResources = bDeleteExistingResources;
1577 updates->pFileName = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(pFileName)+1)*sizeof(WCHAR));
1578 if (updates->pFileName)
1580 lstrcpyW(updates->pFileName, pFileName);
1582 file = CreateFileW( pFileName, GENERIC_READ | GENERIC_WRITE,
1583 0, NULL, OPEN_EXISTING, 0, 0 );
1585 /* if resources are deleted, only the file's presence is checked */
1586 if (file != INVALID_HANDLE_VALUE &&
1587 (bDeleteExistingResources || check_pe_exe( file, updates )))
1588 ret = hUpdate;
1589 else
1590 HeapFree( GetProcessHeap(), 0, updates->pFileName );
1592 CloseHandle( file );
1594 GlobalUnlock(hUpdate);
1597 if (!ret)
1598 GlobalFree(hUpdate);
1600 return ret;
1604 /***********************************************************************
1605 * BeginUpdateResourceA (KERNEL32.@)
1607 HANDLE WINAPI BeginUpdateResourceA( LPCSTR pFileName, BOOL bDeleteExistingResources )
1609 UNICODE_STRING FileNameW;
1610 HANDLE ret;
1611 RtlCreateUnicodeStringFromAsciiz(&FileNameW, pFileName);
1612 ret = BeginUpdateResourceW(FileNameW.Buffer, bDeleteExistingResources);
1613 RtlFreeUnicodeString(&FileNameW);
1614 return ret;
1618 /***********************************************************************
1619 * EndUpdateResourceW (KERNEL32.@)
1621 BOOL WINAPI EndUpdateResourceW( HANDLE hUpdate, BOOL fDiscard )
1623 QUEUEDUPDATES *updates;
1624 BOOL ret;
1626 TRACE("%p %d\n", hUpdate, fDiscard);
1628 updates = GlobalLock(hUpdate);
1629 if (!updates)
1630 return FALSE;
1632 ret = fDiscard || write_raw_resources( updates );
1634 free_resource_directory( &updates->root, 2 );
1636 HeapFree( GetProcessHeap(), 0, updates->pFileName );
1637 GlobalUnlock( hUpdate );
1638 GlobalFree( hUpdate );
1640 return ret;
1644 /***********************************************************************
1645 * EndUpdateResourceA (KERNEL32.@)
1647 BOOL WINAPI EndUpdateResourceA( HANDLE hUpdate, BOOL fDiscard )
1649 return EndUpdateResourceW(hUpdate, fDiscard);
1653 /***********************************************************************
1654 * UpdateResourceW (KERNEL32.@)
1656 BOOL WINAPI UpdateResourceW( HANDLE hUpdate, LPCWSTR lpType, LPCWSTR lpName,
1657 WORD wLanguage, LPVOID lpData, DWORD cbData)
1659 QUEUEDUPDATES *updates;
1660 BOOL ret = FALSE;
1662 TRACE("%p %s %s %08x %p %d\n", hUpdate,
1663 debugstr_w(lpType), debugstr_w(lpName), wLanguage, lpData, cbData);
1665 updates = GlobalLock(hUpdate);
1666 if (updates)
1668 struct resource_data *data;
1669 data = allocate_resource_data( wLanguage, 0, lpData, cbData, TRUE );
1670 if (data)
1671 ret = update_add_resource( updates, lpType, lpName, data, TRUE );
1672 GlobalUnlock(hUpdate);
1674 return ret;
1678 /***********************************************************************
1679 * UpdateResourceA (KERNEL32.@)
1681 BOOL WINAPI UpdateResourceA( HANDLE hUpdate, LPCSTR lpType, LPCSTR lpName,
1682 WORD wLanguage, LPVOID lpData, DWORD cbData)
1684 BOOL ret;
1685 UNICODE_STRING TypeW;
1686 UNICODE_STRING NameW;
1687 if(!HIWORD(lpType))
1688 TypeW.Buffer = ULongToPtr(LOWORD(lpType));
1689 else
1690 RtlCreateUnicodeStringFromAsciiz(&TypeW, lpType);
1691 if(!HIWORD(lpName))
1692 NameW.Buffer = ULongToPtr(LOWORD(lpName));
1693 else
1694 RtlCreateUnicodeStringFromAsciiz(&NameW, lpName);
1695 ret = UpdateResourceW(hUpdate, TypeW.Buffer, NameW.Buffer, wLanguage, lpData, cbData);
1696 if(HIWORD(lpType)) RtlFreeUnicodeString(&TypeW);
1697 if(HIWORD(lpName)) RtlFreeUnicodeString(&NameW);
1698 return ret;