wined3d: Pass a texture and sub-resource index to wined3d_volume_download_data().
[wine.git] / dlls / kernel32 / resource.c
blobc88c9215365be5a8096a61acdf2cbbee13bc65be
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/debug.h"
36 #include "wine/exception.h"
37 #include "wine/unicode.h"
38 #include "wine/list.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(resource);
42 /* we don't want to include winuser.h just for this */
43 #define IS_INTRESOURCE(x) (((ULONG_PTR)(x) >> 16) == 0)
45 /* retrieve the resource name to pass to the ntdll functions */
46 static NTSTATUS get_res_nameA( LPCSTR name, UNICODE_STRING *str )
48 if (IS_INTRESOURCE(name))
50 str->Buffer = ULongToPtr(LOWORD(name));
51 return STATUS_SUCCESS;
53 if (name[0] == '#')
55 ULONG value;
56 if (RtlCharToInteger( name + 1, 10, &value ) != STATUS_SUCCESS || HIWORD(value))
57 return STATUS_INVALID_PARAMETER;
58 str->Buffer = ULongToPtr(value);
59 return STATUS_SUCCESS;
61 RtlCreateUnicodeStringFromAsciiz( str, name );
62 RtlUpcaseUnicodeString( str, str, FALSE );
63 return STATUS_SUCCESS;
66 /* retrieve the resource name to pass to the ntdll functions */
67 static NTSTATUS get_res_nameW( LPCWSTR name, UNICODE_STRING *str )
69 if (IS_INTRESOURCE(name))
71 str->Buffer = ULongToPtr(LOWORD(name));
72 return STATUS_SUCCESS;
74 if (name[0] == '#')
76 ULONG value;
77 RtlInitUnicodeString( str, name + 1 );
78 if (RtlUnicodeStringToInteger( str, 10, &value ) != STATUS_SUCCESS || HIWORD(value))
79 return STATUS_INVALID_PARAMETER;
80 str->Buffer = ULongToPtr(value);
81 return STATUS_SUCCESS;
83 RtlCreateUnicodeString( str, name );
84 RtlUpcaseUnicodeString( str, str, FALSE );
85 return STATUS_SUCCESS;
88 /* implementation of FindResourceExA */
89 static HRSRC find_resourceA( HMODULE hModule, LPCSTR type, LPCSTR name, WORD lang )
91 NTSTATUS status;
92 UNICODE_STRING nameW, typeW;
93 LDR_RESOURCE_INFO info;
94 const IMAGE_RESOURCE_DATA_ENTRY *entry = NULL;
96 nameW.Buffer = NULL;
97 typeW.Buffer = NULL;
99 __TRY
101 if ((status = get_res_nameA( name, &nameW )) != STATUS_SUCCESS) goto done;
102 if ((status = get_res_nameA( type, &typeW )) != STATUS_SUCCESS) goto done;
103 info.Type = (ULONG_PTR)typeW.Buffer;
104 info.Name = (ULONG_PTR)nameW.Buffer;
105 info.Language = lang;
106 status = LdrFindResource_U( hModule, &info, 3, &entry );
107 done:
108 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
110 __EXCEPT_PAGE_FAULT
112 SetLastError( ERROR_INVALID_PARAMETER );
114 __ENDTRY
116 if (!IS_INTRESOURCE(nameW.Buffer)) HeapFree( GetProcessHeap(), 0, nameW.Buffer );
117 if (!IS_INTRESOURCE(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
118 return (HRSRC)entry;
122 /* implementation of FindResourceExW */
123 static HRSRC find_resourceW( HMODULE hModule, LPCWSTR type, LPCWSTR name, WORD lang )
125 NTSTATUS status;
126 UNICODE_STRING nameW, typeW;
127 LDR_RESOURCE_INFO info;
128 const IMAGE_RESOURCE_DATA_ENTRY *entry = NULL;
130 nameW.Buffer = typeW.Buffer = NULL;
132 __TRY
134 if ((status = get_res_nameW( name, &nameW )) != STATUS_SUCCESS) goto done;
135 if ((status = get_res_nameW( type, &typeW )) != STATUS_SUCCESS) goto done;
136 info.Type = (ULONG_PTR)typeW.Buffer;
137 info.Name = (ULONG_PTR)nameW.Buffer;
138 info.Language = lang;
139 status = LdrFindResource_U( hModule, &info, 3, &entry );
140 done:
141 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
143 __EXCEPT_PAGE_FAULT
145 SetLastError( ERROR_INVALID_PARAMETER );
147 __ENDTRY
149 if (!IS_INTRESOURCE(nameW.Buffer)) HeapFree( GetProcessHeap(), 0, nameW.Buffer );
150 if (!IS_INTRESOURCE(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
151 return (HRSRC)entry;
154 /**********************************************************************
155 * FindResourceExA (KERNEL32.@)
157 HRSRC WINAPI FindResourceExA( HMODULE hModule, LPCSTR type, LPCSTR name, WORD lang )
159 TRACE( "%p %s %s %04x\n", hModule, debugstr_a(type), debugstr_a(name), lang );
161 if (!hModule) hModule = GetModuleHandleW(0);
162 return find_resourceA( hModule, type, name, lang );
166 /**********************************************************************
167 * FindResourceA (KERNEL32.@)
169 HRSRC WINAPI FindResourceA( HMODULE hModule, LPCSTR name, LPCSTR type )
171 return FindResourceExA( hModule, type, name, MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL ) );
175 /**********************************************************************
176 * FindResourceExW (KERNEL32.@)
178 HRSRC WINAPI FindResourceExW( HMODULE hModule, LPCWSTR type, LPCWSTR name, WORD lang )
180 TRACE( "%p %s %s %04x\n", hModule, debugstr_w(type), debugstr_w(name), lang );
182 if (!hModule) hModule = GetModuleHandleW(0);
183 return find_resourceW( hModule, type, name, lang );
187 /**********************************************************************
188 * FindResourceW (KERNEL32.@)
190 HRSRC WINAPI FindResourceW( HINSTANCE hModule, LPCWSTR name, LPCWSTR type )
192 return FindResourceExW( hModule, type, name, MAKELANGID( LANG_NEUTRAL, SUBLANG_NEUTRAL ) );
196 /**********************************************************************
197 * EnumResourceTypesA (KERNEL32.@)
199 BOOL WINAPI EnumResourceTypesA( HMODULE hmod, ENUMRESTYPEPROCA lpfun, LONG_PTR lparam )
201 int i;
202 BOOL ret = FALSE;
203 LPSTR type = NULL;
204 DWORD len = 0, newlen;
205 NTSTATUS status;
206 const IMAGE_RESOURCE_DIRECTORY *resdir;
207 const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
208 const IMAGE_RESOURCE_DIR_STRING_U *str;
210 TRACE( "%p %p %lx\n", hmod, lpfun, lparam );
212 if (!hmod) hmod = GetModuleHandleA( NULL );
214 if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &resdir )) != STATUS_SUCCESS)
216 SetLastError( RtlNtStatusToDosError(status) );
217 return FALSE;
219 et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
220 for (i = 0; i < resdir->NumberOfNamedEntries+resdir->NumberOfIdEntries; i++)
222 if (et[i].u.s.NameIsString)
224 str = (const IMAGE_RESOURCE_DIR_STRING_U *)((const BYTE *)resdir + et[i].u.s.NameOffset);
225 newlen = WideCharToMultiByte( CP_ACP, 0, str->NameString, str->Length, NULL, 0, NULL, NULL);
226 if (newlen + 1 > len)
228 len = newlen + 1;
229 HeapFree( GetProcessHeap(), 0, type );
230 if (!(type = HeapAlloc( GetProcessHeap(), 0, len ))) return FALSE;
232 WideCharToMultiByte( CP_ACP, 0, str->NameString, str->Length, type, len, NULL, NULL);
233 type[newlen] = 0;
234 ret = lpfun(hmod,type,lparam);
236 else
238 ret = lpfun( hmod, UIntToPtr(et[i].u.Id), lparam );
240 if (!ret) break;
242 HeapFree( GetProcessHeap(), 0, type );
243 return ret;
247 /**********************************************************************
248 * EnumResourceTypesW (KERNEL32.@)
250 BOOL WINAPI EnumResourceTypesW( HMODULE hmod, ENUMRESTYPEPROCW lpfun, LONG_PTR lparam )
252 int i, len = 0;
253 BOOL ret = FALSE;
254 LPWSTR type = NULL;
255 NTSTATUS status;
256 const IMAGE_RESOURCE_DIRECTORY *resdir;
257 const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
258 const IMAGE_RESOURCE_DIR_STRING_U *str;
260 TRACE( "%p %p %lx\n", hmod, lpfun, lparam );
262 if (!hmod) hmod = GetModuleHandleW( NULL );
264 if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &resdir )) != STATUS_SUCCESS)
266 SetLastError( RtlNtStatusToDosError(status) );
267 return FALSE;
269 et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
270 for (i = 0; i < resdir->NumberOfNamedEntries + resdir->NumberOfIdEntries; i++)
272 if (et[i].u.s.NameIsString)
274 str = (const IMAGE_RESOURCE_DIR_STRING_U *)((const BYTE *)resdir + et[i].u.s.NameOffset);
275 if (str->Length + 1 > len)
277 len = str->Length + 1;
278 HeapFree( GetProcessHeap(), 0, type );
279 if (!(type = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) ))) return FALSE;
281 memcpy(type, str->NameString, str->Length * sizeof (WCHAR));
282 type[str->Length] = 0;
283 ret = lpfun(hmod,type,lparam);
285 else
287 ret = lpfun( hmod, UIntToPtr(et[i].u.Id), lparam );
289 if (!ret) break;
291 HeapFree( GetProcessHeap(), 0, type );
292 return ret;
296 /**********************************************************************
297 * EnumResourceNamesA (KERNEL32.@)
299 BOOL WINAPI EnumResourceNamesA( HMODULE hmod, LPCSTR type, ENUMRESNAMEPROCA lpfun, LONG_PTR lparam )
301 int i;
302 BOOL ret = FALSE;
303 DWORD len = 0, newlen;
304 LPSTR name = NULL;
305 NTSTATUS status;
306 UNICODE_STRING typeW;
307 LDR_RESOURCE_INFO info;
308 const IMAGE_RESOURCE_DIRECTORY *basedir, *resdir;
309 const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
310 const IMAGE_RESOURCE_DIR_STRING_U *str;
312 TRACE( "%p %s %p %lx\n", hmod, debugstr_a(type), lpfun, lparam );
314 if (!hmod) hmod = GetModuleHandleA( NULL );
315 typeW.Buffer = NULL;
316 if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &basedir )) != STATUS_SUCCESS)
317 goto done;
318 if ((status = get_res_nameA( type, &typeW )) != STATUS_SUCCESS)
319 goto done;
320 info.Type = (ULONG_PTR)typeW.Buffer;
321 if ((status = LdrFindResourceDirectory_U( hmod, &info, 1, &resdir )) != STATUS_SUCCESS)
322 goto done;
324 et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
325 __TRY
327 for (i = 0; i < resdir->NumberOfNamedEntries+resdir->NumberOfIdEntries; i++)
329 if (et[i].u.s.NameIsString)
331 str = (const IMAGE_RESOURCE_DIR_STRING_U *)((const BYTE *)basedir + et[i].u.s.NameOffset);
332 newlen = WideCharToMultiByte(CP_ACP, 0, str->NameString, str->Length, NULL, 0, NULL, NULL);
333 if (newlen + 1 > len)
335 len = newlen + 1;
336 HeapFree( GetProcessHeap(), 0, name );
337 if (!(name = HeapAlloc(GetProcessHeap(), 0, len + 1 )))
339 ret = FALSE;
340 break;
343 WideCharToMultiByte( CP_ACP, 0, str->NameString, str->Length, name, len, NULL, NULL );
344 name[newlen] = 0;
345 ret = lpfun(hmod,type,name,lparam);
347 else
349 ret = lpfun( hmod, type, UIntToPtr(et[i].u.Id), lparam );
351 if (!ret) break;
354 __EXCEPT_PAGE_FAULT
356 ret = FALSE;
357 status = STATUS_ACCESS_VIOLATION;
359 __ENDTRY
361 done:
362 HeapFree( GetProcessHeap(), 0, name );
363 if (!IS_INTRESOURCE(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
364 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
365 return ret;
369 /**********************************************************************
370 * EnumResourceNamesW (KERNEL32.@)
372 BOOL WINAPI EnumResourceNamesW( HMODULE hmod, LPCWSTR type, ENUMRESNAMEPROCW lpfun, LONG_PTR lparam )
374 int i, len = 0;
375 BOOL ret = FALSE;
376 LPWSTR name = NULL;
377 NTSTATUS status;
378 UNICODE_STRING typeW;
379 LDR_RESOURCE_INFO info;
380 const IMAGE_RESOURCE_DIRECTORY *basedir, *resdir;
381 const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
382 const IMAGE_RESOURCE_DIR_STRING_U *str;
384 TRACE( "%p %s %p %lx\n", hmod, debugstr_w(type), lpfun, lparam );
386 if (!hmod) hmod = GetModuleHandleW( NULL );
387 typeW.Buffer = NULL;
388 if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &basedir )) != STATUS_SUCCESS)
389 goto done;
390 if ((status = get_res_nameW( type, &typeW )) != STATUS_SUCCESS)
391 goto done;
392 info.Type = (ULONG_PTR)typeW.Buffer;
393 if ((status = LdrFindResourceDirectory_U( hmod, &info, 1, &resdir )) != STATUS_SUCCESS)
394 goto done;
396 et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
397 __TRY
399 for (i = 0; i < resdir->NumberOfNamedEntries+resdir->NumberOfIdEntries; i++)
401 if (et[i].u.s.NameIsString)
403 str = (const IMAGE_RESOURCE_DIR_STRING_U *)((const BYTE *)basedir + et[i].u.s.NameOffset);
404 if (str->Length + 1 > len)
406 len = str->Length + 1;
407 HeapFree( GetProcessHeap(), 0, name );
408 if (!(name = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
410 ret = FALSE;
411 break;
414 memcpy(name, str->NameString, str->Length * sizeof (WCHAR));
415 name[str->Length] = 0;
416 ret = lpfun(hmod,type,name,lparam);
418 else
420 ret = lpfun( hmod, type, UIntToPtr(et[i].u.Id), lparam );
422 if (!ret) break;
425 __EXCEPT_PAGE_FAULT
427 ret = FALSE;
428 status = STATUS_ACCESS_VIOLATION;
430 __ENDTRY
431 done:
432 HeapFree( GetProcessHeap(), 0, name );
433 if (!IS_INTRESOURCE(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
434 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
435 return ret;
439 /**********************************************************************
440 * EnumResourceLanguagesExA (KERNEL32.@)
442 BOOL WINAPI EnumResourceLanguagesExA( HMODULE hmod, LPCSTR type, LPCSTR name,
443 ENUMRESLANGPROCA lpfun, LONG_PTR lparam,
444 DWORD flags, LANGID lang )
446 int i;
447 BOOL ret = FALSE;
448 NTSTATUS status;
449 UNICODE_STRING typeW, nameW;
450 LDR_RESOURCE_INFO info;
451 const IMAGE_RESOURCE_DIRECTORY *basedir, *resdir;
452 const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
454 TRACE( "%p %s %s %p %lx %x %d\n", hmod, debugstr_a(type), debugstr_a(name),
455 lpfun, lparam, flags, lang );
457 if (flags & (RESOURCE_ENUM_MUI | RESOURCE_ENUM_MUI_SYSTEM | RESOURCE_ENUM_VALIDATE))
458 FIXME( "unimplemented flags: %x\n", flags );
460 if (!flags) flags = RESOURCE_ENUM_LN | RESOURCE_ENUM_MUI;
462 if (!(flags & RESOURCE_ENUM_LN)) return ret;
464 if (!hmod) hmod = GetModuleHandleA( NULL );
465 typeW.Buffer = nameW.Buffer = NULL;
466 if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &basedir )) != STATUS_SUCCESS)
467 goto done;
468 if ((status = get_res_nameA( type, &typeW )) != STATUS_SUCCESS)
469 goto done;
470 if ((status = get_res_nameA( name, &nameW )) != STATUS_SUCCESS)
471 goto done;
472 info.Type = (ULONG_PTR)typeW.Buffer;
473 info.Name = (ULONG_PTR)nameW.Buffer;
474 if ((status = LdrFindResourceDirectory_U( hmod, &info, 2, &resdir )) != STATUS_SUCCESS)
475 goto done;
477 et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
478 __TRY
480 for (i = 0; i < resdir->NumberOfNamedEntries + resdir->NumberOfIdEntries; i++)
482 ret = lpfun( hmod, type, name, et[i].u.Id, lparam );
483 if (!ret) break;
486 __EXCEPT_PAGE_FAULT
488 ret = FALSE;
489 status = STATUS_ACCESS_VIOLATION;
491 __ENDTRY
492 done:
493 if (!IS_INTRESOURCE(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
494 if (!IS_INTRESOURCE(nameW.Buffer)) HeapFree( GetProcessHeap(), 0, nameW.Buffer );
495 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
496 return ret;
500 /**********************************************************************
501 * EnumResourceLanguagesA (KERNEL32.@)
503 BOOL WINAPI EnumResourceLanguagesA( HMODULE hmod, LPCSTR type, LPCSTR name,
504 ENUMRESLANGPROCA lpfun, LONG_PTR lparam )
506 return EnumResourceLanguagesExA( hmod, type, name, lpfun, lparam, 0, 0 );
510 /**********************************************************************
511 * EnumResourceLanguagesExW (KERNEL32.@)
513 BOOL WINAPI EnumResourceLanguagesExW( HMODULE hmod, LPCWSTR type, LPCWSTR name,
514 ENUMRESLANGPROCW lpfun, LONG_PTR lparam,
515 DWORD flags, LANGID lang )
517 int i;
518 BOOL ret = FALSE;
519 NTSTATUS status;
520 UNICODE_STRING typeW, nameW;
521 LDR_RESOURCE_INFO info;
522 const IMAGE_RESOURCE_DIRECTORY *basedir, *resdir;
523 const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
525 TRACE( "%p %s %s %p %lx %x %d\n", hmod, debugstr_w(type), debugstr_w(name),
526 lpfun, lparam, flags, lang );
528 if (flags & (RESOURCE_ENUM_MUI | RESOURCE_ENUM_MUI_SYSTEM | RESOURCE_ENUM_VALIDATE))
529 FIXME( "unimplemented flags: %x\n", flags );
531 if (!flags) flags = RESOURCE_ENUM_LN | RESOURCE_ENUM_MUI;
533 if (!(flags & RESOURCE_ENUM_LN)) return ret;
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;
548 et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
549 __TRY
551 for (i = 0; i < resdir->NumberOfNamedEntries + resdir->NumberOfIdEntries; i++)
553 ret = lpfun( hmod, type, name, et[i].u.Id, lparam );
554 if (!ret) break;
557 __EXCEPT_PAGE_FAULT
559 ret = FALSE;
560 status = STATUS_ACCESS_VIOLATION;
562 __ENDTRY
563 done:
564 if (!IS_INTRESOURCE(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
565 if (!IS_INTRESOURCE(nameW.Buffer)) HeapFree( GetProcessHeap(), 0, nameW.Buffer );
566 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
567 return ret;
571 /**********************************************************************
572 * EnumResourceLanguagesW (KERNEL32.@)
574 BOOL WINAPI EnumResourceLanguagesW( HMODULE hmod, LPCWSTR type, LPCWSTR name,
575 ENUMRESLANGPROCW lpfun, LONG_PTR lparam )
577 return EnumResourceLanguagesExW( hmod, type, name, lpfun, lparam, 0, 0 );
581 /**********************************************************************
582 * LoadResource (KERNEL32.@)
584 HGLOBAL WINAPI LoadResource( HINSTANCE hModule, HRSRC hRsrc )
586 NTSTATUS status;
587 void *ret = NULL;
589 TRACE( "%p %p\n", hModule, hRsrc );
591 if (!hRsrc) return 0;
592 if (!hModule) hModule = GetModuleHandleA( NULL );
593 status = LdrAccessResource( hModule, (IMAGE_RESOURCE_DATA_ENTRY *)hRsrc, &ret, NULL );
594 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
595 return ret;
599 /**********************************************************************
600 * LockResource (KERNEL32.@)
602 LPVOID WINAPI LockResource( HGLOBAL handle )
604 return handle;
608 /**********************************************************************
609 * FreeResource (KERNEL32.@)
611 BOOL WINAPI FreeResource( HGLOBAL handle )
613 return FALSE;
617 /**********************************************************************
618 * SizeofResource (KERNEL32.@)
620 DWORD WINAPI SizeofResource( HINSTANCE hModule, HRSRC hRsrc )
622 if (!hRsrc) return 0;
623 return ((PIMAGE_RESOURCE_DATA_ENTRY)hRsrc)->Size;
627 * Data structure for updating resources.
628 * Type/Name/Language is a keyset for accessing resource data.
630 * QUEUEDUPDATES (root) ->
631 * list of struct resource_dir_entry (Type) ->
632 * list of struct resource_dir_entry (Name) ->
633 * list of struct resource_data Language + Data
636 typedef struct
638 LPWSTR pFileName;
639 BOOL bDeleteExistingResources;
640 struct list root;
641 } QUEUEDUPDATES;
643 /* this structure is shared for types and names */
644 struct resource_dir_entry {
645 struct list entry;
646 LPWSTR id;
647 struct list children;
650 /* this structure is the leaf */
651 struct resource_data {
652 struct list entry;
653 LANGID lang;
654 DWORD codepage;
655 DWORD cbData;
656 void *lpData;
659 static int resource_strcmp( LPCWSTR a, LPCWSTR b )
661 if ( a == b )
662 return 0;
663 if (!IS_INTRESOURCE( a ) && !IS_INTRESOURCE( b ) )
664 return lstrcmpW( a, b );
665 /* strings come before ids */
666 if (!IS_INTRESOURCE( a ) && IS_INTRESOURCE( b ))
667 return -1;
668 if (!IS_INTRESOURCE( b ) && IS_INTRESOURCE( a ))
669 return 1;
670 return ( a < b ) ? -1 : 1;
673 static struct resource_dir_entry *find_resource_dir_entry( struct list *dir, LPCWSTR id )
675 struct resource_dir_entry *ent;
677 /* match either IDs or strings */
678 LIST_FOR_EACH_ENTRY( ent, dir, struct resource_dir_entry, entry )
679 if (!resource_strcmp( id, ent->id ))
680 return ent;
682 return NULL;
685 static struct resource_data *find_resource_data( struct list *dir, LANGID lang )
687 struct resource_data *res_data;
689 /* match only languages here */
690 LIST_FOR_EACH_ENTRY( res_data, dir, struct resource_data, entry )
691 if ( lang == res_data->lang )
692 return res_data;
694 return NULL;
697 static void add_resource_dir_entry( struct list *dir, struct resource_dir_entry *resdir )
699 struct resource_dir_entry *ent;
701 LIST_FOR_EACH_ENTRY( ent, dir, struct resource_dir_entry, entry )
703 if (0>resource_strcmp( ent->id, resdir->id ))
704 continue;
706 list_add_before( &ent->entry, &resdir->entry );
707 return;
709 list_add_tail( dir, &resdir->entry );
712 static void add_resource_data_entry( struct list *dir, struct resource_data *resdata )
714 struct resource_data *ent;
716 LIST_FOR_EACH_ENTRY( ent, dir, struct resource_data, entry )
718 if (ent->lang < resdata->lang)
719 continue;
721 list_add_before( &ent->entry, &resdata->entry );
722 return;
724 list_add_tail( dir, &resdata->entry );
727 static LPWSTR res_strdupW( LPCWSTR str )
729 LPWSTR ret;
730 UINT len;
732 if (IS_INTRESOURCE(str))
733 return (LPWSTR) (UINT_PTR) LOWORD(str);
734 len = (lstrlenW( str ) + 1) * sizeof (WCHAR);
735 ret = HeapAlloc( GetProcessHeap(), 0, len );
736 memcpy( ret, str, len );
737 return ret;
740 static void res_free_str( LPWSTR str )
742 if (!IS_INTRESOURCE(str))
743 HeapFree( GetProcessHeap(), 0, str );
746 static BOOL update_add_resource( QUEUEDUPDATES *updates, LPCWSTR Type, LPCWSTR Name,
747 LANGID Lang, struct resource_data *resdata,
748 BOOL overwrite_existing )
750 struct resource_dir_entry *restype, *resname;
751 struct resource_data *existing;
753 TRACE("%p %s %s %p %d\n", updates,
754 debugstr_w(Type), debugstr_w(Name), resdata, overwrite_existing );
756 restype = find_resource_dir_entry( &updates->root, Type );
757 if (!restype)
759 restype = HeapAlloc( GetProcessHeap(), 0, sizeof *restype );
760 restype->id = res_strdupW( Type );
761 list_init( &restype->children );
762 add_resource_dir_entry( &updates->root, restype );
765 resname = find_resource_dir_entry( &restype->children, Name );
766 if (!resname)
768 resname = HeapAlloc( GetProcessHeap(), 0, sizeof *resname );
769 resname->id = res_strdupW( Name );
770 list_init( &resname->children );
771 add_resource_dir_entry( &restype->children, resname );
775 * If there's an existing resource entry with matching (Type,Name,Language)
776 * it needs to be removed before adding the new data.
778 existing = find_resource_data( &resname->children, Lang );
779 if (existing)
781 if (!overwrite_existing)
782 return FALSE;
783 list_remove( &existing->entry );
784 HeapFree( GetProcessHeap(), 0, existing );
787 if (resdata)
788 add_resource_data_entry( &resname->children, resdata );
790 return TRUE;
793 static struct resource_data *allocate_resource_data( WORD Language, DWORD codepage,
794 LPVOID lpData, DWORD cbData, BOOL copy_data )
796 struct resource_data *resdata;
798 if (!lpData || !cbData)
799 return NULL;
801 resdata = HeapAlloc( GetProcessHeap(), 0, sizeof *resdata + (copy_data ? cbData : 0) );
802 if (resdata)
804 resdata->lang = Language;
805 resdata->codepage = codepage;
806 resdata->cbData = cbData;
807 if (copy_data)
809 resdata->lpData = &resdata[1];
810 memcpy( resdata->lpData, lpData, cbData );
812 else
813 resdata->lpData = lpData;
816 return resdata;
819 static void free_resource_directory( struct list *head, int level )
821 struct list *ptr = NULL;
823 while ((ptr = list_head( head )))
825 list_remove( ptr );
826 if (level)
828 struct resource_dir_entry *ent;
830 ent = LIST_ENTRY( ptr, struct resource_dir_entry, entry );
831 res_free_str( ent->id );
832 free_resource_directory( &ent->children, level - 1 );
833 HeapFree(GetProcessHeap(), 0, ent);
835 else
837 struct resource_data *data;
839 data = LIST_ENTRY( ptr, struct resource_data, entry );
840 HeapFree( GetProcessHeap(), 0, data );
845 static IMAGE_NT_HEADERS *get_nt_header( void *base, DWORD mapping_size )
847 IMAGE_NT_HEADERS *nt;
848 IMAGE_DOS_HEADER *dos;
850 if (mapping_size<sizeof (*dos))
851 return NULL;
853 dos = base;
854 if (dos->e_magic != IMAGE_DOS_SIGNATURE)
855 return NULL;
857 if ((dos->e_lfanew + sizeof (*nt)) > mapping_size)
858 return NULL;
860 nt = (void*) ((BYTE*)base + dos->e_lfanew);
862 if (nt->Signature != IMAGE_NT_SIGNATURE)
863 return NULL;
865 return nt;
868 static IMAGE_SECTION_HEADER *get_section_header( void *base, DWORD mapping_size, DWORD *num_sections )
870 IMAGE_NT_HEADERS *nt;
871 DWORD section_ofs;
873 nt = get_nt_header( base, mapping_size );
874 if (!nt)
875 return NULL;
877 /* check that we don't go over the end of the file accessing the sections */
878 section_ofs = FIELD_OFFSET(IMAGE_NT_HEADERS, OptionalHeader) + nt->FileHeader.SizeOfOptionalHeader;
879 if ((nt->FileHeader.NumberOfSections * sizeof (IMAGE_SECTION_HEADER) + section_ofs) > mapping_size)
880 return NULL;
882 if (num_sections)
883 *num_sections = nt->FileHeader.NumberOfSections;
885 /* from here we have a valid PE exe to update */
886 return (void*) ((BYTE*)nt + section_ofs);
889 static BOOL check_pe_exe( HANDLE file, QUEUEDUPDATES *updates )
891 const IMAGE_NT_HEADERS32 *nt;
892 const IMAGE_NT_HEADERS64 *nt64;
893 const IMAGE_SECTION_HEADER *sec;
894 const IMAGE_DATA_DIRECTORY *dd;
895 BOOL ret = FALSE;
896 HANDLE mapping;
897 DWORD mapping_size, num_sections = 0;
898 void *base = NULL;
900 mapping_size = GetFileSize( file, NULL );
902 mapping = CreateFileMappingW( file, NULL, PAGE_READONLY, 0, 0, NULL );
903 if (!mapping)
904 goto done;
906 base = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, mapping_size );
907 if (!base)
908 goto done;
910 nt = (IMAGE_NT_HEADERS32 *)get_nt_header( base, mapping_size );
911 if (!nt)
912 goto done;
914 nt64 = (IMAGE_NT_HEADERS64*)nt;
915 dd = &nt->OptionalHeader.DataDirectory[0];
916 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
917 dd = &nt64->OptionalHeader.DataDirectory[0];
919 TRACE("resources: %08x %08x\n",
920 dd[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress,
921 dd[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size);
923 sec = get_section_header( base, mapping_size, &num_sections );
924 if (!sec)
925 goto done;
927 ret = TRUE;
929 done:
930 if (base)
931 UnmapViewOfFile( base );
932 if (mapping)
933 CloseHandle( mapping );
935 return ret;
938 struct resource_size_info {
939 DWORD types_ofs;
940 DWORD names_ofs;
941 DWORD langs_ofs;
942 DWORD data_entry_ofs;
943 DWORD strings_ofs;
944 DWORD data_ofs;
945 DWORD total_size;
948 struct mapping_info {
949 HANDLE file;
950 void *base;
951 DWORD size;
952 BOOL read_write;
955 static const IMAGE_SECTION_HEADER *section_from_rva( void *base, DWORD mapping_size, DWORD rva )
957 const IMAGE_SECTION_HEADER *sec;
958 DWORD num_sections = 0;
959 int i;
961 sec = get_section_header( base, mapping_size, &num_sections );
962 if (!sec)
963 return NULL;
965 for (i=num_sections-1; i>=0; i--)
967 if (sec[i].VirtualAddress <= rva &&
968 rva <= (DWORD)sec[i].VirtualAddress + sec[i].SizeOfRawData)
970 return &sec[i];
974 return NULL;
977 static void *address_from_rva( void *base, DWORD mapping_size, DWORD rva, DWORD len )
979 const IMAGE_SECTION_HEADER *sec;
981 sec = section_from_rva( base, mapping_size, rva );
982 if (!sec)
983 return NULL;
985 if (rva + len <= (DWORD)sec->VirtualAddress + sec->SizeOfRawData)
986 return (void*)((LPBYTE) base + (sec->PointerToRawData + rva - sec->VirtualAddress));
988 return NULL;
991 static LPWSTR resource_dup_string( const IMAGE_RESOURCE_DIRECTORY *root, const IMAGE_RESOURCE_DIRECTORY_ENTRY *entry )
993 const IMAGE_RESOURCE_DIR_STRING_U* string;
994 LPWSTR s;
996 if (!entry->u.s.NameIsString)
997 return UIntToPtr(entry->u.Id);
999 string = (const IMAGE_RESOURCE_DIR_STRING_U*) (((const char *)root) + entry->u.s.NameOffset);
1000 s = HeapAlloc(GetProcessHeap(), 0, (string->Length + 1)*sizeof (WCHAR) );
1001 memcpy( s, string->NameString, (string->Length + 1)*sizeof (WCHAR) );
1002 s[string->Length] = 0;
1004 return s;
1007 /* this function is based on the code in winedump's pe.c */
1008 static BOOL enumerate_mapped_resources( QUEUEDUPDATES *updates,
1009 void *base, DWORD mapping_size,
1010 const IMAGE_RESOURCE_DIRECTORY *root )
1012 const IMAGE_RESOURCE_DIRECTORY *namedir, *langdir;
1013 const IMAGE_RESOURCE_DIRECTORY_ENTRY *e1, *e2, *e3;
1014 const IMAGE_RESOURCE_DATA_ENTRY *data;
1015 DWORD i, j, k;
1017 TRACE("version (%d.%d) %d named %d id entries\n",
1018 root->MajorVersion, root->MinorVersion, root->NumberOfNamedEntries, root->NumberOfIdEntries);
1020 for (i = 0; i< root->NumberOfNamedEntries + root->NumberOfIdEntries; i++)
1022 LPWSTR Type;
1024 e1 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(root + 1) + i;
1026 Type = resource_dup_string( root, e1 );
1028 namedir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e1->u2.s2.OffsetToDirectory);
1029 for (j = 0; j < namedir->NumberOfNamedEntries + namedir->NumberOfIdEntries; j++)
1031 LPWSTR Name;
1033 e2 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(namedir + 1) + j;
1035 Name = resource_dup_string( root, e2 );
1037 langdir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e2->u2.s2.OffsetToDirectory);
1038 for (k = 0; k < langdir->NumberOfNamedEntries + langdir->NumberOfIdEntries; k++)
1040 LANGID Lang;
1041 void *p;
1042 struct resource_data *resdata;
1044 e3 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(langdir + 1) + k;
1046 Lang = e3->u.Id;
1048 data = (const IMAGE_RESOURCE_DATA_ENTRY *)((const char *)root + e3->u2.OffsetToData);
1050 p = address_from_rva( base, mapping_size, data->OffsetToData, data->Size );
1052 resdata = allocate_resource_data( Lang, data->CodePage, p, data->Size, FALSE );
1053 if (resdata)
1055 if (!update_add_resource( updates, Type, Name, Lang, resdata, FALSE ))
1056 HeapFree( GetProcessHeap(), 0, resdata );
1059 res_free_str( Name );
1061 res_free_str( Type );
1064 return TRUE;
1067 static BOOL read_mapped_resources( QUEUEDUPDATES *updates, void *base, DWORD mapping_size )
1069 const IMAGE_RESOURCE_DIRECTORY *root;
1070 const IMAGE_NT_HEADERS *nt;
1071 const IMAGE_SECTION_HEADER *sec;
1072 DWORD num_sections = 0, i;
1074 nt = get_nt_header( base, mapping_size );
1075 if (!nt)
1076 return FALSE;
1078 sec = get_section_header( base, mapping_size, &num_sections );
1079 if (!sec)
1080 return FALSE;
1082 for (i=0; i<num_sections; i++)
1083 if (!memcmp(sec[i].Name, ".rsrc", 6))
1084 break;
1086 if (i == num_sections)
1087 return TRUE;
1089 /* check the resource data is inside the mapping */
1090 if (sec[i].PointerToRawData > mapping_size ||
1091 (sec[i].PointerToRawData + sec[i].SizeOfRawData) > mapping_size)
1092 return TRUE;
1094 TRACE("found .rsrc at %08x, size %08x\n", sec[i].PointerToRawData, sec[i].SizeOfRawData);
1096 if (!sec[i].PointerToRawData || sec[i].SizeOfRawData < sizeof(IMAGE_RESOURCE_DIRECTORY))
1097 return TRUE;
1099 root = (void*) ((BYTE*)base + sec[i].PointerToRawData);
1100 enumerate_mapped_resources( updates, base, mapping_size, root );
1102 return TRUE;
1105 static BOOL map_file_into_memory( struct mapping_info *mi )
1107 DWORD page_attr, perm;
1108 HANDLE mapping;
1110 if (mi->read_write)
1112 page_attr = PAGE_READWRITE;
1113 perm = FILE_MAP_WRITE | FILE_MAP_READ;
1115 else
1117 page_attr = PAGE_READONLY;
1118 perm = FILE_MAP_READ;
1121 mapping = CreateFileMappingW( mi->file, NULL, page_attr, 0, 0, NULL );
1122 if (!mapping) return FALSE;
1124 mi->base = MapViewOfFile( mapping, perm, 0, 0, mi->size );
1125 CloseHandle( mapping );
1127 return mi->base != NULL;
1130 static BOOL unmap_file_from_memory( struct mapping_info *mi )
1132 if (mi->base)
1133 UnmapViewOfFile( mi->base );
1134 mi->base = NULL;
1135 return TRUE;
1138 static void destroy_mapping( struct mapping_info *mi )
1140 if (!mi)
1141 return;
1142 unmap_file_from_memory( mi );
1143 if (mi->file)
1144 CloseHandle( mi->file );
1145 HeapFree( GetProcessHeap(), 0, mi );
1148 static struct mapping_info *create_mapping( LPCWSTR name, BOOL rw )
1150 struct mapping_info *mi;
1152 mi = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof *mi );
1153 if (!mi)
1154 return NULL;
1156 mi->read_write = rw;
1158 mi->file = CreateFileW( name, GENERIC_READ | (rw ? GENERIC_WRITE : 0),
1159 0, NULL, OPEN_EXISTING, 0, 0 );
1161 if (mi->file != INVALID_HANDLE_VALUE)
1163 mi->size = GetFileSize( mi->file, NULL );
1165 if (map_file_into_memory( mi ))
1166 return mi;
1168 destroy_mapping( mi );
1169 return NULL;
1172 static BOOL resize_mapping( struct mapping_info *mi, DWORD new_size )
1174 if (!unmap_file_from_memory( mi ))
1175 return FALSE;
1177 /* change the file size */
1178 SetFilePointer( mi->file, new_size, NULL, FILE_BEGIN );
1179 if (!SetEndOfFile( mi->file ))
1181 ERR("failed to set file size to %08x\n", new_size );
1182 return FALSE;
1185 mi->size = new_size;
1187 return map_file_into_memory( mi );
1190 static void get_resource_sizes( QUEUEDUPDATES *updates, struct resource_size_info *si )
1192 struct resource_dir_entry *types, *names;
1193 struct resource_data *data;
1194 DWORD num_types = 0, num_names = 0, num_langs = 0, strings_size = 0, data_size = 0;
1196 memset( si, 0, sizeof *si );
1198 LIST_FOR_EACH_ENTRY( types, &updates->root, struct resource_dir_entry, entry )
1200 num_types++;
1201 if (!IS_INTRESOURCE( types->id ))
1202 strings_size += sizeof (WORD) + lstrlenW( types->id )*sizeof (WCHAR);
1204 LIST_FOR_EACH_ENTRY( names, &types->children, struct resource_dir_entry, entry )
1206 num_names++;
1208 if (!IS_INTRESOURCE( names->id ))
1209 strings_size += sizeof (WORD) + lstrlenW( names->id )*sizeof (WCHAR);
1211 LIST_FOR_EACH_ENTRY( data, &names->children, struct resource_data, entry )
1213 num_langs++;
1214 data_size += (data->cbData + 3) & ~3;
1219 /* names are at the end of the types */
1220 si->names_ofs = sizeof (IMAGE_RESOURCE_DIRECTORY) +
1221 num_types * sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1223 /* language directories are at the end of the names */
1224 si->langs_ofs = si->names_ofs +
1225 num_types * sizeof (IMAGE_RESOURCE_DIRECTORY) +
1226 num_names * sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1228 si->data_entry_ofs = si->langs_ofs +
1229 num_names * sizeof (IMAGE_RESOURCE_DIRECTORY) +
1230 num_langs * sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1232 si->strings_ofs = si->data_entry_ofs +
1233 num_langs * sizeof (IMAGE_RESOURCE_DATA_ENTRY);
1235 si->data_ofs = si->strings_ofs + ((strings_size + 3) & ~3);
1237 si->total_size = si->data_ofs + data_size;
1239 TRACE("names %08x langs %08x data entries %08x strings %08x data %08x total %08x\n",
1240 si->names_ofs, si->langs_ofs, si->data_entry_ofs,
1241 si->strings_ofs, si->data_ofs, si->total_size);
1244 static void res_write_padding( BYTE *res_base, DWORD size )
1246 static const BYTE pad[] = {
1247 'P','A','D','D','I','N','G','X','X','P','A','D','D','I','N','G' };
1248 DWORD i;
1250 for ( i = 0; i < size / sizeof pad; i++ )
1251 memcpy( &res_base[i*sizeof pad], pad, sizeof pad );
1252 memcpy( &res_base[i*sizeof pad], pad, size%sizeof pad );
1255 static BOOL write_resources( QUEUEDUPDATES *updates, LPBYTE base, struct resource_size_info *si, DWORD rva )
1257 struct resource_dir_entry *types, *names;
1258 struct resource_data *data;
1259 IMAGE_RESOURCE_DIRECTORY *root;
1261 TRACE("%p %p %p %08x\n", updates, base, si, rva );
1263 memset( base, 0, si->total_size );
1265 /* the root entry always exists */
1266 root = (IMAGE_RESOURCE_DIRECTORY*) base;
1267 memset( root, 0, sizeof *root );
1268 root->MajorVersion = 4;
1269 si->types_ofs = sizeof *root;
1270 LIST_FOR_EACH_ENTRY( types, &updates->root, struct resource_dir_entry, entry )
1272 IMAGE_RESOURCE_DIRECTORY_ENTRY *e1;
1273 IMAGE_RESOURCE_DIRECTORY *namedir;
1275 e1 = (IMAGE_RESOURCE_DIRECTORY_ENTRY*) &base[si->types_ofs];
1276 memset( e1, 0, sizeof *e1 );
1277 if (!IS_INTRESOURCE( types->id ))
1279 WCHAR *strings;
1280 DWORD len;
1282 root->NumberOfNamedEntries++;
1283 e1->u.s.NameIsString = 1;
1284 e1->u.s.NameOffset = si->strings_ofs;
1286 strings = (WCHAR*) &base[si->strings_ofs];
1287 len = lstrlenW( types->id );
1288 strings[0] = len;
1289 memcpy( &strings[1], types->id, len * sizeof (WCHAR) );
1290 si->strings_ofs += (len + 1) * sizeof (WCHAR);
1292 else
1294 root->NumberOfIdEntries++;
1295 e1->u.Id = LOWORD( types->id );
1297 e1->u2.s2.OffsetToDirectory = si->names_ofs;
1298 e1->u2.s2.DataIsDirectory = TRUE;
1299 si->types_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1301 namedir = (IMAGE_RESOURCE_DIRECTORY*) &base[si->names_ofs];
1302 memset( namedir, 0, sizeof *namedir );
1303 namedir->MajorVersion = 4;
1304 si->names_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY);
1306 LIST_FOR_EACH_ENTRY( names, &types->children, struct resource_dir_entry, entry )
1308 IMAGE_RESOURCE_DIRECTORY_ENTRY *e2;
1309 IMAGE_RESOURCE_DIRECTORY *langdir;
1311 e2 = (IMAGE_RESOURCE_DIRECTORY_ENTRY*) &base[si->names_ofs];
1312 memset( e2, 0, sizeof *e2 );
1313 if (!IS_INTRESOURCE( names->id ))
1315 WCHAR *strings;
1316 DWORD len;
1318 namedir->NumberOfNamedEntries++;
1319 e2->u.s.NameIsString = 1;
1320 e2->u.s.NameOffset = si->strings_ofs;
1322 strings = (WCHAR*) &base[si->strings_ofs];
1323 len = lstrlenW( names->id );
1324 strings[0] = len;
1325 memcpy( &strings[1], names->id, len * sizeof (WCHAR) );
1326 si->strings_ofs += (len + 1) * sizeof (WCHAR);
1328 else
1330 namedir->NumberOfIdEntries++;
1331 e2->u.Id = LOWORD( names->id );
1333 e2->u2.s2.OffsetToDirectory = si->langs_ofs;
1334 e2->u2.s2.DataIsDirectory = TRUE;
1335 si->names_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1337 langdir = (IMAGE_RESOURCE_DIRECTORY*) &base[si->langs_ofs];
1338 memset( langdir, 0, sizeof *langdir );
1339 langdir->MajorVersion = 4;
1340 si->langs_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY);
1342 LIST_FOR_EACH_ENTRY( data, &names->children, struct resource_data, entry )
1344 IMAGE_RESOURCE_DIRECTORY_ENTRY *e3;
1345 IMAGE_RESOURCE_DATA_ENTRY *de;
1346 int pad_size;
1348 e3 = (IMAGE_RESOURCE_DIRECTORY_ENTRY*) &base[si->langs_ofs];
1349 memset( e3, 0, sizeof *e3 );
1350 langdir->NumberOfIdEntries++;
1351 e3->u.Id = LOWORD( data->lang );
1352 e3->u2.OffsetToData = si->data_entry_ofs;
1354 si->langs_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1356 /* write out all the data entries */
1357 de = (IMAGE_RESOURCE_DATA_ENTRY*) &base[si->data_entry_ofs];
1358 memset( de, 0, sizeof *de );
1359 de->OffsetToData = si->data_ofs + rva;
1360 de->Size = data->cbData;
1361 de->CodePage = data->codepage;
1362 si->data_entry_ofs += sizeof (IMAGE_RESOURCE_DATA_ENTRY);
1364 /* write out the resource data */
1365 memcpy( &base[si->data_ofs], data->lpData, data->cbData );
1366 si->data_ofs += data->cbData;
1368 pad_size = (-si->data_ofs)&3;
1369 res_write_padding( &base[si->data_ofs], pad_size );
1370 si->data_ofs += pad_size;
1375 return TRUE;
1379 * FIXME:
1380 * Assumes that the resources are in .rsrc
1381 * and .rsrc is the last section in the file.
1382 * Not sure whether updating resources will other cases on Windows.
1383 * If the resources lie in a section containing other data,
1384 * resizing that section could possibly cause trouble.
1385 * If the section with the resources isn't last, the remaining
1386 * sections need to be moved down in the file, and the section header
1387 * would need to be adjusted.
1388 * If we needed to add a section, what would we name it?
1389 * If we needed to add a section and there wasn't space in the file
1390 * header, how would that work?
1391 * Seems that at least some of these cases can't be handled properly.
1393 static IMAGE_SECTION_HEADER *get_resource_section( void *base, DWORD mapping_size )
1395 IMAGE_SECTION_HEADER *sec;
1396 IMAGE_NT_HEADERS *nt;
1397 DWORD i, num_sections = 0;
1399 nt = get_nt_header( base, mapping_size );
1400 if (!nt)
1401 return NULL;
1403 sec = get_section_header( base, mapping_size, &num_sections );
1404 if (!sec)
1405 return NULL;
1407 /* find the resources section */
1408 for (i=0; i<num_sections; i++)
1409 if (!memcmp(sec[i].Name, ".rsrc", 6))
1410 break;
1412 if (i == num_sections)
1413 return NULL;
1415 return &sec[i];
1418 static DWORD get_init_data_size( void *base, DWORD mapping_size )
1420 DWORD i, sz = 0, num_sections = 0;
1421 IMAGE_SECTION_HEADER *s;
1423 s = get_section_header( base, mapping_size, &num_sections );
1425 for (i=0; i<num_sections; i++)
1426 if (s[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
1427 sz += s[i].SizeOfRawData;
1429 TRACE("size = %08x\n", sz);
1431 return sz;
1434 static BOOL write_raw_resources( QUEUEDUPDATES *updates )
1436 static const WCHAR prefix[] = { 'r','e','s','u',0 };
1437 WCHAR tempdir[MAX_PATH], tempfile[MAX_PATH];
1438 DWORD section_size;
1439 BOOL ret = FALSE;
1440 IMAGE_SECTION_HEADER *sec;
1441 IMAGE_NT_HEADERS32 *nt;
1442 IMAGE_NT_HEADERS64 *nt64;
1443 struct resource_size_info res_size;
1444 BYTE *res_base;
1445 struct mapping_info *read_map = NULL, *write_map = NULL;
1446 DWORD PeSectionAlignment, PeFileAlignment, PeSizeOfImage;
1448 /* copy the exe to a temp file then update the temp file... */
1449 tempdir[0] = 0;
1450 if (!GetTempPathW( MAX_PATH, tempdir ))
1451 return ret;
1453 if (!GetTempFileNameW( tempdir, prefix, 0, tempfile ))
1454 return ret;
1456 if (!CopyFileW( updates->pFileName, tempfile, FALSE ))
1457 goto done;
1459 TRACE("tempfile %s\n", debugstr_w(tempfile));
1461 if (!updates->bDeleteExistingResources)
1463 read_map = create_mapping( updates->pFileName, FALSE );
1464 if (!read_map)
1465 goto done;
1467 ret = read_mapped_resources( updates, read_map->base, read_map->size );
1468 if (!ret)
1470 ERR("failed to read existing resources\n");
1471 goto done;
1475 write_map = create_mapping( tempfile, TRUE );
1476 if (!write_map)
1477 goto done;
1479 nt = (IMAGE_NT_HEADERS32*)get_nt_header( write_map->base, write_map->size );
1480 if (!nt)
1481 goto done;
1483 nt64 = (IMAGE_NT_HEADERS64*)nt;
1484 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
1485 PeSectionAlignment = nt64->OptionalHeader.SectionAlignment;
1486 PeFileAlignment = nt64->OptionalHeader.FileAlignment;
1487 PeSizeOfImage = nt64->OptionalHeader.SizeOfImage;
1488 } else {
1489 PeSectionAlignment = nt->OptionalHeader.SectionAlignment;
1490 PeFileAlignment = nt->OptionalHeader.FileAlignment;
1491 PeSizeOfImage = nt->OptionalHeader.SizeOfImage;
1494 if ((LONG)PeSectionAlignment <= 0)
1496 ERR("invalid section alignment %08x\n", PeSectionAlignment);
1497 goto done;
1500 if ((LONG)PeFileAlignment <= 0)
1502 ERR("invalid file alignment %08x\n", PeFileAlignment);
1503 goto done;
1506 sec = get_resource_section( write_map->base, write_map->size );
1507 if (!sec) /* no section, add one */
1509 DWORD num_sections;
1511 sec = get_section_header( write_map->base, write_map->size, &num_sections );
1512 if (!sec)
1513 goto done;
1515 sec += num_sections;
1516 nt->FileHeader.NumberOfSections++;
1518 memset( sec, 0, sizeof *sec );
1519 memcpy( sec->Name, ".rsrc", 5 );
1520 sec->Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
1521 sec->VirtualAddress = PeSizeOfImage;
1524 if (!sec->PointerToRawData) /* empty section */
1526 sec->PointerToRawData = write_map->size + (-write_map->size) % PeFileAlignment;
1527 sec->SizeOfRawData = 0;
1530 TRACE("before .rsrc at %08x, size %08x\n", sec->PointerToRawData, sec->SizeOfRawData);
1532 get_resource_sizes( updates, &res_size );
1534 /* round up the section size */
1535 section_size = res_size.total_size;
1536 section_size += (-section_size) % PeFileAlignment;
1538 TRACE("requires %08x (%08x) bytes\n", res_size.total_size, section_size );
1540 /* check if the file size needs to be changed */
1541 if (section_size != sec->SizeOfRawData)
1543 DWORD old_size = write_map->size;
1544 DWORD virtual_section_size = res_size.total_size + (-res_size.total_size) % PeSectionAlignment;
1545 int delta = section_size - (sec->SizeOfRawData + (-sec->SizeOfRawData) % PeFileAlignment);
1546 int rva_delta = virtual_section_size -
1547 (sec->Misc.VirtualSize + (-sec->Misc.VirtualSize) % PeSectionAlignment);
1548 /* when new section is added it could end past current mapping size */
1549 BOOL rsrc_is_last = sec->PointerToRawData + sec->SizeOfRawData >= old_size;
1550 /* align .rsrc size when possible */
1551 DWORD mapping_size = rsrc_is_last ? sec->PointerToRawData + section_size : old_size + delta;
1553 /* postpone file truncation if there are some data to be moved down from file end */
1554 BOOL resize_after = mapping_size < old_size && !rsrc_is_last;
1556 TRACE("file size %08x -> %08x\n", old_size, mapping_size);
1558 if (!resize_after)
1560 /* unmap the file before changing the file size */
1561 ret = resize_mapping( write_map, mapping_size );
1563 /* get the pointers again - they might be different after remapping */
1564 nt = (IMAGE_NT_HEADERS32*)get_nt_header( write_map->base, mapping_size );
1565 if (!nt)
1567 ERR("couldn't get NT header\n");
1568 goto done;
1570 nt64 = (IMAGE_NT_HEADERS64*)nt;
1572 sec = get_resource_section( write_map->base, mapping_size );
1573 if (!sec)
1574 goto done;
1577 if (!rsrc_is_last) /* not last section, relocate trailing sections */
1579 IMAGE_SECTION_HEADER *s;
1580 DWORD tail_start = sec->PointerToRawData + sec->SizeOfRawData;
1581 DWORD i, num_sections = 0;
1583 memmove( (char*)write_map->base + tail_start + delta, (char*)write_map->base + tail_start, old_size - tail_start );
1585 s = get_section_header( write_map->base, mapping_size, &num_sections );
1587 for (i=0; i<num_sections; i++)
1589 if (s[i].PointerToRawData > sec->PointerToRawData)
1591 s[i].PointerToRawData += delta;
1592 s[i].VirtualAddress += rva_delta;
1597 if (resize_after)
1599 ret = resize_mapping( write_map, mapping_size );
1601 nt = (IMAGE_NT_HEADERS32*)get_nt_header( write_map->base, mapping_size );
1602 if (!nt)
1604 ERR("couldn't get NT header\n");
1605 goto done;
1607 nt64 = (IMAGE_NT_HEADERS64*)nt;
1609 sec = get_resource_section( write_map->base, mapping_size );
1610 if (!sec)
1611 goto done;
1614 /* adjust the PE header information */
1615 sec->SizeOfRawData = section_size;
1616 sec->Misc.VirtualSize = virtual_section_size;
1617 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC) {
1618 nt64->OptionalHeader.SizeOfImage += rva_delta;
1619 nt64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = sec->VirtualAddress;
1620 nt64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = res_size.total_size;
1621 nt64->OptionalHeader.SizeOfInitializedData = get_init_data_size( write_map->base, mapping_size );
1622 } else {
1623 nt->OptionalHeader.SizeOfImage += rva_delta;
1624 nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress = sec->VirtualAddress;
1625 nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = res_size.total_size;
1626 nt->OptionalHeader.SizeOfInitializedData = get_init_data_size( write_map->base, mapping_size );
1630 res_base = (LPBYTE) write_map->base + sec->PointerToRawData;
1632 TRACE("base = %p offset = %08x\n", write_map->base, sec->PointerToRawData);
1634 ret = write_resources( updates, res_base, &res_size, sec->VirtualAddress );
1636 res_write_padding( res_base + res_size.total_size, section_size - res_size.total_size );
1638 TRACE("after .rsrc at %08x, size %08x\n", sec->PointerToRawData, sec->SizeOfRawData);
1640 done:
1641 destroy_mapping( read_map );
1642 destroy_mapping( write_map );
1644 if (ret)
1645 ret = CopyFileW( tempfile, updates->pFileName, FALSE );
1647 DeleteFileW( tempfile );
1649 return ret;
1652 /***********************************************************************
1653 * BeginUpdateResourceW (KERNEL32.@)
1655 HANDLE WINAPI BeginUpdateResourceW( LPCWSTR pFileName, BOOL bDeleteExistingResources )
1657 QUEUEDUPDATES *updates = NULL;
1658 HANDLE hUpdate, file, ret = NULL;
1660 TRACE("%s, %d\n", debugstr_w(pFileName), bDeleteExistingResources);
1662 hUpdate = GlobalAlloc(GHND, sizeof(QUEUEDUPDATES));
1663 if (!hUpdate)
1664 return ret;
1666 updates = GlobalLock(hUpdate);
1667 if (updates)
1669 list_init( &updates->root );
1670 updates->bDeleteExistingResources = bDeleteExistingResources;
1671 updates->pFileName = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(pFileName)+1)*sizeof(WCHAR));
1672 if (updates->pFileName)
1674 lstrcpyW(updates->pFileName, pFileName);
1676 file = CreateFileW( pFileName, GENERIC_READ | GENERIC_WRITE,
1677 0, NULL, OPEN_EXISTING, 0, 0 );
1679 /* if resources are deleted, only the file's presence is checked */
1680 if (file != INVALID_HANDLE_VALUE &&
1681 (bDeleteExistingResources || check_pe_exe( file, updates )))
1682 ret = hUpdate;
1683 else
1684 HeapFree( GetProcessHeap(), 0, updates->pFileName );
1686 CloseHandle( file );
1688 GlobalUnlock(hUpdate);
1691 if (!ret)
1692 GlobalFree(hUpdate);
1694 return ret;
1698 /***********************************************************************
1699 * BeginUpdateResourceA (KERNEL32.@)
1701 HANDLE WINAPI BeginUpdateResourceA( LPCSTR pFileName, BOOL bDeleteExistingResources )
1703 UNICODE_STRING FileNameW;
1704 HANDLE ret;
1705 RtlCreateUnicodeStringFromAsciiz(&FileNameW, pFileName);
1706 ret = BeginUpdateResourceW(FileNameW.Buffer, bDeleteExistingResources);
1707 RtlFreeUnicodeString(&FileNameW);
1708 return ret;
1712 /***********************************************************************
1713 * EndUpdateResourceW (KERNEL32.@)
1715 BOOL WINAPI EndUpdateResourceW( HANDLE hUpdate, BOOL fDiscard )
1717 QUEUEDUPDATES *updates;
1718 BOOL ret;
1720 TRACE("%p %d\n", hUpdate, fDiscard);
1722 updates = GlobalLock(hUpdate);
1723 if (!updates)
1724 return FALSE;
1726 ret = fDiscard || write_raw_resources( updates );
1728 free_resource_directory( &updates->root, 2 );
1730 HeapFree( GetProcessHeap(), 0, updates->pFileName );
1731 GlobalUnlock( hUpdate );
1732 GlobalFree( hUpdate );
1734 return ret;
1738 /***********************************************************************
1739 * EndUpdateResourceA (KERNEL32.@)
1741 BOOL WINAPI EndUpdateResourceA( HANDLE hUpdate, BOOL fDiscard )
1743 return EndUpdateResourceW(hUpdate, fDiscard);
1747 /***********************************************************************
1748 * UpdateResourceW (KERNEL32.@)
1750 BOOL WINAPI UpdateResourceW( HANDLE hUpdate, LPCWSTR lpType, LPCWSTR lpName,
1751 WORD wLanguage, LPVOID lpData, DWORD cbData)
1753 QUEUEDUPDATES *updates;
1754 BOOL ret = FALSE;
1756 TRACE("%p %s %s %08x %p %d\n", hUpdate,
1757 debugstr_w(lpType), debugstr_w(lpName), wLanguage, lpData, cbData);
1759 updates = GlobalLock(hUpdate);
1760 if (updates)
1762 if (lpData == NULL && cbData == 0) /* remove resource */
1764 ret = update_add_resource( updates, lpType, lpName, wLanguage, NULL, TRUE );
1766 else
1768 struct resource_data *data;
1769 data = allocate_resource_data( wLanguage, 0, lpData, cbData, TRUE );
1770 if (data)
1771 ret = update_add_resource( updates, lpType, lpName, wLanguage, data, TRUE );
1773 GlobalUnlock(hUpdate);
1775 return ret;
1779 /***********************************************************************
1780 * UpdateResourceA (KERNEL32.@)
1782 BOOL WINAPI UpdateResourceA( HANDLE hUpdate, LPCSTR lpType, LPCSTR lpName,
1783 WORD wLanguage, LPVOID lpData, DWORD cbData)
1785 BOOL ret;
1786 UNICODE_STRING TypeW;
1787 UNICODE_STRING NameW;
1788 if(IS_INTRESOURCE(lpType))
1789 TypeW.Buffer = ULongToPtr(LOWORD(lpType));
1790 else
1791 RtlCreateUnicodeStringFromAsciiz(&TypeW, lpType);
1792 if(IS_INTRESOURCE(lpName))
1793 NameW.Buffer = ULongToPtr(LOWORD(lpName));
1794 else
1795 RtlCreateUnicodeStringFromAsciiz(&NameW, lpName);
1796 ret = UpdateResourceW(hUpdate, TypeW.Buffer, NameW.Buffer, wLanguage, lpData, cbData);
1797 if(!IS_INTRESOURCE(lpType)) RtlFreeUnicodeString(&TypeW);
1798 if(!IS_INTRESOURCE(lpName)) RtlFreeUnicodeString(&NameW);
1799 return ret;