oleaut32: Convert CustData to use standard linked lists.
[wine.git] / dlls / kernel32 / resource.c
blob81f600ed817081502454934df043ca94c8358489
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].u1.s1.NameIsString)
224 str = (const IMAGE_RESOURCE_DIR_STRING_U *)((const BYTE *)resdir + et[i].u1.s1.NameOffset);
225 newlen = WideCharToMultiByte( CP_ACP, 0, str->NameString, str->Length, NULL, 0, NULL, NULL);
226 if (newlen + 1 > len)
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].u1.s2.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].u1.s1.NameIsString)
274 str = (const IMAGE_RESOURCE_DIR_STRING_U *)((const BYTE *)resdir + et[i].u1.s1.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].u1.s2.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].u1.s1.NameIsString)
331 str = (const IMAGE_RESOURCE_DIR_STRING_U *)((const BYTE *)basedir + et[i].u1.s1.NameOffset);
332 newlen = WideCharToMultiByte(CP_ACP, 0, str->NameString, str->Length, NULL, 0, NULL, NULL);
333 if (newlen + 1 > len)
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].u1.s2.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].u1.s1.NameIsString)
403 str = (const IMAGE_RESOURCE_DIR_STRING_U *)((const BYTE *)basedir + et[i].u1.s1.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].u1.s2.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 * EnumResourceLanguagesA (KERNEL32.@)
442 BOOL WINAPI EnumResourceLanguagesA( HMODULE hmod, LPCSTR type, LPCSTR name,
443 ENUMRESLANGPROCA lpfun, LONG_PTR lparam )
445 int i;
446 BOOL ret = FALSE;
447 NTSTATUS status;
448 UNICODE_STRING typeW, nameW;
449 LDR_RESOURCE_INFO info;
450 const IMAGE_RESOURCE_DIRECTORY *basedir, *resdir;
451 const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
453 TRACE( "%p %s %s %p %lx\n", hmod, debugstr_a(type), debugstr_a(name), lpfun, lparam );
455 if (!hmod) hmod = GetModuleHandleA( NULL );
456 typeW.Buffer = nameW.Buffer = NULL;
457 if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &basedir )) != STATUS_SUCCESS)
458 goto done;
459 if ((status = get_res_nameA( type, &typeW )) != STATUS_SUCCESS)
460 goto done;
461 if ((status = get_res_nameA( name, &nameW )) != STATUS_SUCCESS)
462 goto done;
463 info.Type = (ULONG_PTR)typeW.Buffer;
464 info.Name = (ULONG_PTR)nameW.Buffer;
465 if ((status = LdrFindResourceDirectory_U( hmod, &info, 2, &resdir )) != STATUS_SUCCESS)
466 goto done;
468 et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
469 __TRY
471 for (i = 0; i < resdir->NumberOfNamedEntries + resdir->NumberOfIdEntries; i++)
473 ret = lpfun( hmod, type, name, et[i].u1.s2.Id, lparam );
474 if (!ret) break;
477 __EXCEPT_PAGE_FAULT
479 ret = FALSE;
480 status = STATUS_ACCESS_VIOLATION;
482 __ENDTRY
483 done:
484 if (!IS_INTRESOURCE(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
485 if (!IS_INTRESOURCE(nameW.Buffer)) HeapFree( GetProcessHeap(), 0, nameW.Buffer );
486 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
487 return ret;
491 /**********************************************************************
492 * EnumResourceLanguagesW (KERNEL32.@)
494 BOOL WINAPI EnumResourceLanguagesW( HMODULE hmod, LPCWSTR type, LPCWSTR name,
495 ENUMRESLANGPROCW lpfun, LONG_PTR lparam )
497 int i;
498 BOOL ret = FALSE;
499 NTSTATUS status;
500 UNICODE_STRING typeW, nameW;
501 LDR_RESOURCE_INFO info;
502 const IMAGE_RESOURCE_DIRECTORY *basedir, *resdir;
503 const IMAGE_RESOURCE_DIRECTORY_ENTRY *et;
505 TRACE( "%p %s %s %p %lx\n", hmod, debugstr_w(type), debugstr_w(name), lpfun, lparam );
507 if (!hmod) hmod = GetModuleHandleW( NULL );
508 typeW.Buffer = nameW.Buffer = NULL;
509 if ((status = LdrFindResourceDirectory_U( hmod, NULL, 0, &basedir )) != STATUS_SUCCESS)
510 goto done;
511 if ((status = get_res_nameW( type, &typeW )) != STATUS_SUCCESS)
512 goto done;
513 if ((status = get_res_nameW( name, &nameW )) != STATUS_SUCCESS)
514 goto done;
515 info.Type = (ULONG_PTR)typeW.Buffer;
516 info.Name = (ULONG_PTR)nameW.Buffer;
517 if ((status = LdrFindResourceDirectory_U( hmod, &info, 2, &resdir )) != STATUS_SUCCESS)
518 goto done;
520 et = (const IMAGE_RESOURCE_DIRECTORY_ENTRY *)(resdir + 1);
521 __TRY
523 for (i = 0; i < resdir->NumberOfNamedEntries + resdir->NumberOfIdEntries; i++)
525 ret = lpfun( hmod, type, name, et[i].u1.s2.Id, lparam );
526 if (!ret) break;
529 __EXCEPT_PAGE_FAULT
531 ret = FALSE;
532 status = STATUS_ACCESS_VIOLATION;
534 __ENDTRY
535 done:
536 if (!IS_INTRESOURCE(typeW.Buffer)) HeapFree( GetProcessHeap(), 0, typeW.Buffer );
537 if (!IS_INTRESOURCE(nameW.Buffer)) HeapFree( GetProcessHeap(), 0, nameW.Buffer );
538 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
539 return ret;
543 /**********************************************************************
544 * LoadResource (KERNEL32.@)
546 HGLOBAL WINAPI LoadResource( HINSTANCE hModule, HRSRC hRsrc )
548 NTSTATUS status;
549 void *ret = NULL;
551 TRACE( "%p %p\n", hModule, hRsrc );
553 if (!hRsrc) return 0;
554 if (!hModule) hModule = GetModuleHandleA( NULL );
555 status = LdrAccessResource( hModule, (IMAGE_RESOURCE_DATA_ENTRY *)hRsrc, &ret, NULL );
556 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
557 return ret;
561 /**********************************************************************
562 * LockResource (KERNEL32.@)
564 LPVOID WINAPI LockResource( HGLOBAL handle )
566 return handle;
570 /**********************************************************************
571 * FreeResource (KERNEL32.@)
573 BOOL WINAPI FreeResource( HGLOBAL handle )
575 return 0;
579 /**********************************************************************
580 * SizeofResource (KERNEL32.@)
582 DWORD WINAPI SizeofResource( HINSTANCE hModule, HRSRC hRsrc )
584 if (!hRsrc) return 0;
585 return ((PIMAGE_RESOURCE_DATA_ENTRY)hRsrc)->Size;
589 * Data structure for updating resources.
590 * Type/Name/Language is a keyset for accessing resource data.
592 * QUEUEDUPDATES (root) ->
593 * list of struct resource_dir_entry (Type) ->
594 * list of struct resource_dir_entry (Name) ->
595 * list of struct resource_data Language + Data
598 typedef struct
600 LPWSTR pFileName;
601 BOOL bDeleteExistingResources;
602 struct list root;
603 } QUEUEDUPDATES;
605 /* this structure is shared for types and names */
606 struct resource_dir_entry {
607 struct list entry;
608 LPWSTR id;
609 struct list children;
612 /* this structure is the leaf */
613 struct resource_data {
614 struct list entry;
615 LANGID lang;
616 DWORD codepage;
617 DWORD cbData;
618 void *lpData;
621 static int resource_strcmp( LPCWSTR a, LPCWSTR b )
623 if ( a == b )
624 return 0;
625 if (!IS_INTRESOURCE( a ) && !IS_INTRESOURCE( b ) )
626 return lstrcmpW( a, b );
627 /* strings come before ids */
628 if (!IS_INTRESOURCE( a ) && IS_INTRESOURCE( b ))
629 return -1;
630 if (!IS_INTRESOURCE( b ) && IS_INTRESOURCE( a ))
631 return 1;
632 return ( a < b ) ? -1 : 1;
635 static struct resource_dir_entry *find_resource_dir_entry( struct list *dir, LPCWSTR id )
637 struct resource_dir_entry *ent;
639 /* match either IDs or strings */
640 LIST_FOR_EACH_ENTRY( ent, dir, struct resource_dir_entry, entry )
641 if (!resource_strcmp( id, ent->id ))
642 return ent;
644 return NULL;
647 static struct resource_data *find_resource_data( struct list *dir, LANGID lang )
649 struct resource_data *res_data;
651 /* match only languages here */
652 LIST_FOR_EACH_ENTRY( res_data, dir, struct resource_data, entry )
653 if ( lang == res_data->lang )
654 return res_data;
656 return NULL;
659 static void add_resource_dir_entry( struct list *dir, struct resource_dir_entry *resdir )
661 struct resource_dir_entry *ent;
663 LIST_FOR_EACH_ENTRY( ent, dir, struct resource_dir_entry, entry )
665 if (0>resource_strcmp( ent->id, resdir->id ))
666 continue;
668 list_add_before( &ent->entry, &resdir->entry );
669 return;
671 list_add_tail( dir, &resdir->entry );
674 static void add_resource_data_entry( struct list *dir, struct resource_data *resdata )
676 struct resource_data *ent;
678 LIST_FOR_EACH_ENTRY( ent, dir, struct resource_data, entry )
680 if (ent->lang < resdata->lang)
681 continue;
683 list_add_before( &ent->entry, &resdata->entry );
684 return;
686 list_add_tail( dir, &resdata->entry );
689 static LPWSTR res_strdupW( LPCWSTR str )
691 LPWSTR ret;
692 UINT len;
694 if (IS_INTRESOURCE(str))
695 return (LPWSTR) (UINT_PTR) LOWORD(str);
696 len = (lstrlenW( str ) + 1) * sizeof (WCHAR);
697 ret = HeapAlloc( GetProcessHeap(), 0, len );
698 memcpy( ret, str, len );
699 return ret;
702 static void res_free_str( LPWSTR str )
704 if (!IS_INTRESOURCE(str))
705 HeapFree( GetProcessHeap(), 0, str );
708 static BOOL update_add_resource( QUEUEDUPDATES *updates, LPCWSTR Type, LPCWSTR Name,
709 LANGID Lang, struct resource_data *resdata,
710 BOOL overwrite_existing )
712 struct resource_dir_entry *restype, *resname;
713 struct resource_data *existing;
715 TRACE("%p %s %s %p %d\n", updates,
716 debugstr_w(Type), debugstr_w(Name), resdata, overwrite_existing );
718 restype = find_resource_dir_entry( &updates->root, Type );
719 if (!restype)
721 restype = HeapAlloc( GetProcessHeap(), 0, sizeof *restype );
722 restype->id = res_strdupW( Type );
723 list_init( &restype->children );
724 add_resource_dir_entry( &updates->root, restype );
727 resname = find_resource_dir_entry( &restype->children, Name );
728 if (!resname)
730 resname = HeapAlloc( GetProcessHeap(), 0, sizeof *resname );
731 resname->id = res_strdupW( Name );
732 list_init( &resname->children );
733 add_resource_dir_entry( &restype->children, resname );
737 * If there's an existing resource entry with matching (Type,Name,Language)
738 * it needs to be removed before adding the new data.
740 existing = find_resource_data( &resname->children, Lang );
741 if (existing)
743 if (!overwrite_existing)
744 return FALSE;
745 list_remove( &existing->entry );
746 HeapFree( GetProcessHeap(), 0, existing );
749 if (resdata)
750 add_resource_data_entry( &resname->children, resdata );
752 return TRUE;
755 static struct resource_data *allocate_resource_data( WORD Language, DWORD codepage,
756 LPVOID lpData, DWORD cbData, BOOL copy_data )
758 struct resource_data *resdata;
760 if (!lpData || !cbData)
761 return NULL;
763 resdata = HeapAlloc( GetProcessHeap(), 0, sizeof *resdata + (copy_data ? cbData : 0) );
764 if (resdata)
766 resdata->lang = Language;
767 resdata->codepage = codepage;
768 resdata->cbData = cbData;
769 if (copy_data)
771 resdata->lpData = &resdata[1];
772 memcpy( resdata->lpData, lpData, cbData );
774 else
775 resdata->lpData = lpData;
778 return resdata;
781 static void free_resource_directory( struct list *head, int level )
783 struct list *ptr = NULL;
785 while ((ptr = list_head( head )))
787 list_remove( ptr );
788 if (level)
790 struct resource_dir_entry *ent;
792 ent = LIST_ENTRY( ptr, struct resource_dir_entry, entry );
793 res_free_str( ent->id );
794 free_resource_directory( &ent->children, level - 1 );
795 HeapFree(GetProcessHeap(), 0, ent);
797 else
799 struct resource_data *data;
801 data = LIST_ENTRY( ptr, struct resource_data, entry );
802 HeapFree( GetProcessHeap(), 0, data );
807 static IMAGE_NT_HEADERS *get_nt_header( void *base, DWORD mapping_size )
809 IMAGE_NT_HEADERS *nt;
810 IMAGE_DOS_HEADER *dos;
812 if (mapping_size<sizeof (*dos))
813 return NULL;
815 dos = base;
816 if (dos->e_magic != IMAGE_DOS_SIGNATURE)
817 return NULL;
819 if ((dos->e_lfanew + sizeof (*nt)) > mapping_size)
820 return NULL;
822 nt = (void*) ((BYTE*)base + dos->e_lfanew);
824 if (nt->Signature != IMAGE_NT_SIGNATURE)
825 return NULL;
827 return nt;
830 static IMAGE_SECTION_HEADER *get_section_header( void *base, DWORD mapping_size, DWORD *num_sections )
832 IMAGE_NT_HEADERS *nt;
833 IMAGE_SECTION_HEADER *sec;
834 DWORD section_ofs;
836 nt = get_nt_header( base, mapping_size );
837 if (!nt)
838 return NULL;
840 /* check that we don't go over the end of the file accessing the sections */
841 section_ofs = FIELD_OFFSET(IMAGE_NT_HEADERS, OptionalHeader) + nt->FileHeader.SizeOfOptionalHeader;
842 if ((nt->FileHeader.NumberOfSections * sizeof (*sec) + section_ofs) > mapping_size)
843 return NULL;
845 if (num_sections)
846 *num_sections = nt->FileHeader.NumberOfSections;
848 /* from here we have a valid PE exe to update */
849 return (void*) ((BYTE*)nt + section_ofs);
852 static BOOL check_pe_exe( HANDLE file, QUEUEDUPDATES *updates )
854 const IMAGE_NT_HEADERS *nt;
855 const IMAGE_SECTION_HEADER *sec;
856 BOOL ret = FALSE;
857 HANDLE mapping;
858 DWORD mapping_size, num_sections = 0;
859 void *base = NULL;
861 mapping_size = GetFileSize( file, NULL );
863 mapping = CreateFileMappingW( file, NULL, PAGE_READONLY, 0, 0, NULL );
864 if (!mapping)
865 goto done;
867 base = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, mapping_size );
868 if (!base)
869 goto done;
871 nt = get_nt_header( base, mapping_size );
872 if (!nt)
873 goto done;
875 TRACE("resources: %08x %08x\n",
876 nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress,
877 nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size);
879 sec = get_section_header( base, mapping_size, &num_sections );
880 if (!sec)
881 goto done;
883 ret = TRUE;
885 done:
886 if (base)
887 UnmapViewOfFile( base );
888 if (mapping)
889 CloseHandle( mapping );
891 return ret;
894 struct resource_size_info {
895 DWORD types_ofs;
896 DWORD names_ofs;
897 DWORD langs_ofs;
898 DWORD data_entry_ofs;
899 DWORD strings_ofs;
900 DWORD data_ofs;
901 DWORD total_size;
904 struct mapping_info {
905 HANDLE file;
906 HANDLE mapping;
907 void *base;
908 DWORD size;
909 BOOL read_write;
912 static const IMAGE_SECTION_HEADER *section_from_rva( void *base, DWORD mapping_size, DWORD rva )
914 const IMAGE_SECTION_HEADER *sec;
915 DWORD num_sections = 0;
916 int i;
918 sec = get_section_header( base, mapping_size, &num_sections );
919 if (!sec)
920 return NULL;
922 for (i=num_sections-1; i>=0; i--)
924 if (sec[i].VirtualAddress <= rva &&
925 rva <= (DWORD)sec[i].VirtualAddress + sec[i].SizeOfRawData)
927 return &sec[i];
931 return NULL;
934 static void *address_from_rva( void *base, DWORD mapping_size, DWORD rva, DWORD len )
936 const IMAGE_SECTION_HEADER *sec;
938 sec = section_from_rva( base, mapping_size, rva );
939 if (!sec)
940 return NULL;
942 if (rva + len <= (DWORD)sec->VirtualAddress + sec->SizeOfRawData)
943 return (void*)((LPBYTE) base + (sec->PointerToRawData + rva - sec->VirtualAddress));
945 return NULL;
948 static LPWSTR resource_dup_string( const IMAGE_RESOURCE_DIRECTORY *root, const IMAGE_RESOURCE_DIRECTORY_ENTRY *entry )
950 const IMAGE_RESOURCE_DIR_STRING_U* string;
951 LPWSTR s;
953 if (!entry->u1.s1.NameIsString)
954 return UIntToPtr(entry->u1.s2.Id);
956 string = (const IMAGE_RESOURCE_DIR_STRING_U*) (((const char *)root) + entry->u1.s1.NameOffset);
957 s = HeapAlloc(GetProcessHeap(), 0, (string->Length + 1)*sizeof (WCHAR) );
958 memcpy( s, string->NameString, (string->Length + 1)*sizeof (WCHAR) );
959 s[string->Length] = 0;
961 return s;
964 /* this function is based on the code in winedump's pe.c */
965 static BOOL enumerate_mapped_resources( QUEUEDUPDATES *updates,
966 void *base, DWORD mapping_size,
967 const IMAGE_RESOURCE_DIRECTORY *root )
969 const IMAGE_RESOURCE_DIRECTORY *namedir, *langdir;
970 const IMAGE_RESOURCE_DIRECTORY_ENTRY *e1, *e2, *e3;
971 const IMAGE_RESOURCE_DATA_ENTRY *data;
972 DWORD i, j, k;
974 TRACE("version (%d.%d) %d named %d id entries\n",
975 root->MajorVersion, root->MinorVersion, root->NumberOfNamedEntries, root->NumberOfIdEntries);
977 for (i = 0; i< root->NumberOfNamedEntries + root->NumberOfIdEntries; i++)
979 LPWSTR Type;
981 e1 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(root + 1) + i;
983 Type = resource_dup_string( root, e1 );
985 namedir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e1->u2.s3.OffsetToDirectory);
986 for (j = 0; j < namedir->NumberOfNamedEntries + namedir->NumberOfIdEntries; j++)
988 LPWSTR Name;
990 e2 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(namedir + 1) + j;
992 Name = resource_dup_string( root, e2 );
994 langdir = (const IMAGE_RESOURCE_DIRECTORY *)((const char *)root + e2->u2.s3.OffsetToDirectory);
995 for (k = 0; k < langdir->NumberOfNamedEntries + langdir->NumberOfIdEntries; k++)
997 LANGID Lang;
998 void *p;
999 struct resource_data *resdata;
1001 e3 = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(langdir + 1) + k;
1003 Lang = e3->u1.s2.Id;
1005 data = (const IMAGE_RESOURCE_DATA_ENTRY *)((const char *)root + e3->u2.OffsetToData);
1007 p = address_from_rva( base, mapping_size, data->OffsetToData, data->Size );
1009 resdata = allocate_resource_data( Lang, data->CodePage, p, data->Size, FALSE );
1010 if (resdata)
1012 if (!update_add_resource( updates, Type, Name, Lang, resdata, FALSE ))
1013 HeapFree( GetProcessHeap(), 0, resdata );
1016 res_free_str( Name );
1018 res_free_str( Type );
1021 return TRUE;
1024 static BOOL read_mapped_resources( QUEUEDUPDATES *updates, void *base, DWORD mapping_size )
1026 const IMAGE_RESOURCE_DIRECTORY *root;
1027 const IMAGE_NT_HEADERS *nt;
1028 const IMAGE_SECTION_HEADER *sec;
1029 DWORD num_sections = 0, i;
1031 nt = get_nt_header( base, mapping_size );
1032 if (!nt)
1033 return FALSE;
1035 sec = get_section_header( base, mapping_size, &num_sections );
1036 if (!sec)
1037 return FALSE;
1039 for (i=0; i<num_sections; i++)
1040 if (!memcmp(sec[i].Name, ".rsrc", 6))
1041 break;
1043 if (i == num_sections)
1044 return TRUE;
1046 /* check the resource data is inside the mapping */
1047 if (sec[i].PointerToRawData > mapping_size ||
1048 (sec[i].PointerToRawData + sec[i].SizeOfRawData) > mapping_size)
1049 return TRUE;
1051 TRACE("found .rsrc at %08x, size %08x\n", sec[i].PointerToRawData, sec[i].SizeOfRawData);
1053 if (!sec[i].PointerToRawData || sec[i].SizeOfRawData < sizeof(IMAGE_RESOURCE_DIRECTORY))
1054 return TRUE;
1056 root = (void*) ((BYTE*)base + sec[i].PointerToRawData);
1057 enumerate_mapped_resources( updates, base, mapping_size, root );
1059 return TRUE;
1062 static BOOL map_file_into_memory( struct mapping_info *mi )
1064 DWORD page_attr, perm;
1066 if (mi->read_write)
1068 page_attr = PAGE_READWRITE;
1069 perm = FILE_MAP_WRITE | FILE_MAP_READ;
1071 else
1073 page_attr = PAGE_READONLY;
1074 perm = FILE_MAP_READ;
1077 mi->mapping = CreateFileMappingW( mi->file, NULL, page_attr, 0, 0, NULL );
1078 if (!mi->mapping)
1079 return FALSE;
1081 mi->base = MapViewOfFile( mi->mapping, perm, 0, 0, mi->size );
1082 if (!mi->base)
1083 return FALSE;
1085 return TRUE;
1088 static BOOL unmap_file_from_memory( struct mapping_info *mi )
1090 if (mi->base)
1091 UnmapViewOfFile( mi->base );
1092 mi->base = NULL;
1093 if (mi->mapping)
1094 CloseHandle( mi->mapping );
1095 mi->mapping = NULL;
1096 return TRUE;
1099 static void destroy_mapping( struct mapping_info *mi )
1101 if (!mi)
1102 return;
1103 unmap_file_from_memory( mi );
1104 if (mi->file)
1105 CloseHandle( mi->file );
1106 HeapFree( GetProcessHeap(), 0, mi );
1109 static struct mapping_info *create_mapping( LPCWSTR name, BOOL rw )
1111 struct mapping_info *mi;
1113 mi = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof *mi );
1114 if (!mi)
1115 return NULL;
1117 mi->read_write = rw;
1119 mi->file = CreateFileW( name, GENERIC_READ | (rw ? GENERIC_WRITE : 0),
1120 0, NULL, OPEN_EXISTING, 0, 0 );
1122 if (mi->file != INVALID_HANDLE_VALUE)
1124 mi->size = GetFileSize( mi->file, NULL );
1126 if (map_file_into_memory( mi ))
1127 return mi;
1130 unmap_file_from_memory( mi );
1131 HeapFree( GetProcessHeap(), 0, mi );
1133 return NULL;
1136 static BOOL resize_mapping( struct mapping_info *mi, DWORD new_size )
1138 if (!unmap_file_from_memory( mi ))
1139 return FALSE;
1141 /* change the file size */
1142 SetFilePointer( mi->file, new_size, NULL, FILE_BEGIN );
1143 if (!SetEndOfFile( mi->file ))
1145 ERR("failed to set file size to %08x\n", new_size );
1146 return FALSE;
1149 mi->size = new_size;
1151 return map_file_into_memory( mi );
1154 static void get_resource_sizes( QUEUEDUPDATES *updates, struct resource_size_info *si )
1156 struct resource_dir_entry *types, *names;
1157 struct resource_data *data;
1158 DWORD num_types = 0, num_names = 0, num_langs = 0, strings_size = 0, data_size = 0;
1160 memset( si, 0, sizeof *si );
1162 LIST_FOR_EACH_ENTRY( types, &updates->root, struct resource_dir_entry, entry )
1164 num_types++;
1165 if (!IS_INTRESOURCE( types->id ))
1166 strings_size += sizeof (WORD) + lstrlenW( types->id )*sizeof (WCHAR);
1168 LIST_FOR_EACH_ENTRY( names, &types->children, struct resource_dir_entry, entry )
1170 num_names++;
1172 if (!IS_INTRESOURCE( names->id ))
1173 strings_size += sizeof (WORD) + lstrlenW( names->id )*sizeof (WCHAR);
1175 LIST_FOR_EACH_ENTRY( data, &names->children, struct resource_data, entry )
1177 num_langs++;
1178 data_size += (data->cbData + 3) & ~3;
1183 /* names are at the end of the types */
1184 si->names_ofs = sizeof (IMAGE_RESOURCE_DIRECTORY) +
1185 num_types * sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1187 /* language directories are at the end of the names */
1188 si->langs_ofs = si->names_ofs +
1189 num_types * sizeof (IMAGE_RESOURCE_DIRECTORY) +
1190 num_names * sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1192 si->data_entry_ofs = si->langs_ofs +
1193 num_names * sizeof (IMAGE_RESOURCE_DIRECTORY) +
1194 num_langs * sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1196 si->strings_ofs = si->data_entry_ofs +
1197 num_langs * sizeof (IMAGE_RESOURCE_DATA_ENTRY);
1199 si->data_ofs = si->strings_ofs + ((strings_size + 3) & ~3);
1201 si->total_size = si->data_ofs + data_size;
1203 TRACE("names %08x langs %08x data entries %08x strings %08x data %08x total %08x\n",
1204 si->names_ofs, si->langs_ofs, si->data_entry_ofs,
1205 si->strings_ofs, si->data_ofs, si->total_size);
1208 static void res_write_padding( BYTE *res_base, DWORD size )
1210 static const BYTE pad[] = {
1211 'P','A','D','D','I','N','G','X','X','P','A','D','D','I','N','G' };
1212 DWORD i;
1214 for ( i = 0; i < size / sizeof pad; i++ )
1215 memcpy( &res_base[i*sizeof pad], pad, sizeof pad );
1216 memcpy( &res_base[i*sizeof pad], pad, size%sizeof pad );
1219 static BOOL write_resources( QUEUEDUPDATES *updates, LPBYTE base, struct resource_size_info *si, DWORD rva )
1221 struct resource_dir_entry *types, *names;
1222 struct resource_data *data;
1223 IMAGE_RESOURCE_DIRECTORY *root;
1225 TRACE("%p %p %p %08x\n", updates, base, si, rva );
1227 memset( base, 0, si->total_size );
1229 /* the root entry always exists */
1230 root = (IMAGE_RESOURCE_DIRECTORY*) base;
1231 memset( root, 0, sizeof *root );
1232 root->MajorVersion = 4;
1233 si->types_ofs = sizeof *root;
1234 LIST_FOR_EACH_ENTRY( types, &updates->root, struct resource_dir_entry, entry )
1236 IMAGE_RESOURCE_DIRECTORY_ENTRY *e1;
1237 IMAGE_RESOURCE_DIRECTORY *namedir;
1239 e1 = (IMAGE_RESOURCE_DIRECTORY_ENTRY*) &base[si->types_ofs];
1240 memset( e1, 0, sizeof *e1 );
1241 if (!IS_INTRESOURCE( types->id ))
1243 WCHAR *strings;
1244 DWORD len;
1246 root->NumberOfNamedEntries++;
1247 e1->u1.s1.NameIsString = 1;
1248 e1->u1.s1.NameOffset = si->strings_ofs;
1250 strings = (WCHAR*) &base[si->strings_ofs];
1251 len = lstrlenW( types->id );
1252 strings[0] = len;
1253 memcpy( &strings[1], types->id, len * sizeof (WCHAR) );
1254 si->strings_ofs += (len + 1) * sizeof (WCHAR);
1256 else
1258 root->NumberOfIdEntries++;
1259 e1->u1.s2.Id = LOWORD( types->id );
1261 e1->u2.s3.OffsetToDirectory = si->names_ofs;
1262 e1->u2.s3.DataIsDirectory = TRUE;
1263 si->types_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1265 namedir = (IMAGE_RESOURCE_DIRECTORY*) &base[si->names_ofs];
1266 memset( namedir, 0, sizeof *namedir );
1267 namedir->MajorVersion = 4;
1268 si->names_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY);
1270 LIST_FOR_EACH_ENTRY( names, &types->children, struct resource_dir_entry, entry )
1272 IMAGE_RESOURCE_DIRECTORY_ENTRY *e2;
1273 IMAGE_RESOURCE_DIRECTORY *langdir;
1275 e2 = (IMAGE_RESOURCE_DIRECTORY_ENTRY*) &base[si->names_ofs];
1276 memset( e2, 0, sizeof *e2 );
1277 if (!IS_INTRESOURCE( names->id ))
1279 WCHAR *strings;
1280 DWORD len;
1282 namedir->NumberOfNamedEntries++;
1283 e2->u1.s1.NameIsString = 1;
1284 e2->u1.s1.NameOffset = si->strings_ofs;
1286 strings = (WCHAR*) &base[si->strings_ofs];
1287 len = lstrlenW( names->id );
1288 strings[0] = len;
1289 memcpy( &strings[1], names->id, len * sizeof (WCHAR) );
1290 si->strings_ofs += (len + 1) * sizeof (WCHAR);
1292 else
1294 namedir->NumberOfIdEntries++;
1295 e2->u1.s2.Id = LOWORD( names->id );
1297 e2->u2.s3.OffsetToDirectory = si->langs_ofs;
1298 e2->u2.s3.DataIsDirectory = TRUE;
1299 si->names_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1301 langdir = (IMAGE_RESOURCE_DIRECTORY*) &base[si->langs_ofs];
1302 memset( langdir, 0, sizeof *langdir );
1303 langdir->MajorVersion = 4;
1304 si->langs_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY);
1306 LIST_FOR_EACH_ENTRY( data, &names->children, struct resource_data, entry )
1308 IMAGE_RESOURCE_DIRECTORY_ENTRY *e3;
1309 IMAGE_RESOURCE_DATA_ENTRY *de;
1310 int pad_size;
1312 e3 = (IMAGE_RESOURCE_DIRECTORY_ENTRY*) &base[si->langs_ofs];
1313 memset( e3, 0, sizeof *e3 );
1314 langdir->NumberOfIdEntries++;
1315 e3->u1.s2.Id = LOWORD( data->lang );
1316 e3->u2.OffsetToData = si->data_entry_ofs;
1318 si->langs_ofs += sizeof (IMAGE_RESOURCE_DIRECTORY_ENTRY);
1320 /* write out all the data entries */
1321 de = (IMAGE_RESOURCE_DATA_ENTRY*) &base[si->data_entry_ofs];
1322 memset( de, 0, sizeof *de );
1323 de->OffsetToData = si->data_ofs + rva;
1324 de->Size = data->cbData;
1325 de->CodePage = data->codepage;
1326 si->data_entry_ofs += sizeof (IMAGE_RESOURCE_DATA_ENTRY);
1328 /* write out the resource data */
1329 memcpy( &base[si->data_ofs], data->lpData, data->cbData );
1330 si->data_ofs += data->cbData;
1332 pad_size = (-si->data_ofs)&3;
1333 res_write_padding( &base[si->data_ofs], pad_size );
1334 si->data_ofs += pad_size;
1339 return TRUE;
1343 * FIXME:
1344 * Assumes that the resources are in .rsrc
1345 * and .rsrc is the last section in the file.
1346 * Not sure whether updating resources will other cases on Windows.
1347 * If the resources lie in a section containing other data,
1348 * resizing that section could possibly cause trouble.
1349 * If the section with the resources isn't last, the remaining
1350 * sections need to be moved down in the file, and the section header
1351 * would need to be adjusted.
1352 * If we needed to add a section, what would we name it?
1353 * If we needed to add a section and there wasn't space in the file
1354 * header, how would that work?
1355 * Seems that at least some of these cases can't be handled properly.
1357 static IMAGE_SECTION_HEADER *get_resource_section( void *base, DWORD mapping_size )
1359 IMAGE_SECTION_HEADER *sec;
1360 IMAGE_NT_HEADERS *nt;
1361 DWORD i, num_sections = 0;
1363 nt = get_nt_header( base, mapping_size );
1364 if (!nt)
1365 return NULL;
1367 sec = get_section_header( base, mapping_size, &num_sections );
1368 if (!sec)
1369 return NULL;
1371 /* find the resources section */
1372 for (i=0; i<num_sections; i++)
1373 if (!memcmp(sec[i].Name, ".rsrc", 6))
1374 break;
1376 if (i == num_sections)
1377 return NULL;
1379 return &sec[i];
1382 static DWORD get_init_data_size( void *base, DWORD mapping_size )
1384 DWORD i, sz = 0, num_sections = 0;
1385 IMAGE_SECTION_HEADER *s;
1387 s = get_section_header( base, mapping_size, &num_sections );
1389 for (i=0; i<num_sections; i++)
1390 if (s[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
1391 sz += s[i].SizeOfRawData;
1393 TRACE("size = %08x\n", sz);
1395 return sz;
1398 static BOOL write_raw_resources( QUEUEDUPDATES *updates )
1400 static const WCHAR prefix[] = { 'r','e','s','u',0 };
1401 WCHAR tempdir[MAX_PATH], tempfile[MAX_PATH];
1402 DWORD section_size;
1403 BOOL ret = FALSE;
1404 IMAGE_SECTION_HEADER *sec;
1405 IMAGE_NT_HEADERS *nt;
1406 struct resource_size_info res_size;
1407 BYTE *res_base;
1408 struct mapping_info *read_map = NULL, *write_map = NULL;
1410 /* copy the exe to a temp file then update the temp file... */
1411 tempdir[0] = 0;
1412 if (!GetTempPathW( MAX_PATH, tempdir ))
1413 return ret;
1415 if (!GetTempFileNameW( tempdir, prefix, 0, tempfile ))
1416 return ret;
1418 if (!CopyFileW( updates->pFileName, tempfile, FALSE ))
1419 goto done;
1421 TRACE("tempfile %s\n", debugstr_w(tempfile));
1423 if (!updates->bDeleteExistingResources)
1425 read_map = create_mapping( updates->pFileName, FALSE );
1426 if (!read_map)
1427 goto done;
1429 ret = read_mapped_resources( updates, read_map->base, read_map->size );
1430 if (!ret)
1432 ERR("failed to read existing resources\n");
1433 goto done;
1437 write_map = create_mapping( tempfile, TRUE );
1438 if (!write_map)
1439 goto done;
1441 nt = get_nt_header( write_map->base, write_map->size );
1442 if (!nt)
1443 goto done;
1445 if (nt->OptionalHeader.SectionAlignment <= 0)
1447 ERR("invalid section alignment %04x\n", nt->OptionalHeader.SectionAlignment);
1448 goto done;
1451 if (nt->OptionalHeader.FileAlignment <= 0)
1453 ERR("invalid file alignment %04x\n", nt->OptionalHeader.FileAlignment);
1454 goto done;
1457 sec = get_resource_section( write_map->base, write_map->size );
1458 if (!sec) /* no section, add one */
1460 DWORD num_sections;
1462 sec = get_section_header( write_map->base, write_map->size, &num_sections );
1463 if (!sec)
1464 goto done;
1466 sec += num_sections;
1467 nt->FileHeader.NumberOfSections++;
1469 memset( sec, 0, sizeof *sec );
1470 memcpy( sec->Name, ".rsrc", 5 );
1471 sec->Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ;
1472 sec->VirtualAddress = nt->OptionalHeader.SizeOfImage;
1475 if (!sec->PointerToRawData) /* empty section */
1477 sec->PointerToRawData = write_map->size + (-write_map->size) % nt->OptionalHeader.FileAlignment;
1478 sec->SizeOfRawData = 0;
1481 TRACE("before .rsrc at %08x, size %08x\n", sec->PointerToRawData, sec->SizeOfRawData);
1483 get_resource_sizes( updates, &res_size );
1485 /* round up the section size */
1486 section_size = res_size.total_size;
1487 section_size += (-section_size) % nt->OptionalHeader.FileAlignment;
1489 TRACE("requires %08x (%08x) bytes\n", res_size.total_size, section_size );
1491 /* check if the file size needs to be changed */
1492 if (section_size != sec->SizeOfRawData)
1494 DWORD old_size = write_map->size;
1495 DWORD virtual_section_size = res_size.total_size + (-res_size.total_size) % nt->OptionalHeader.SectionAlignment;
1496 int delta = section_size - (sec->SizeOfRawData + (-sec->SizeOfRawData) % nt->OptionalHeader.FileAlignment);
1497 int rva_delta = virtual_section_size -
1498 (sec->Misc.VirtualSize + (-sec->Misc.VirtualSize) % nt->OptionalHeader.SectionAlignment);
1499 BOOL rsrc_is_last = sec->PointerToRawData + sec->SizeOfRawData == old_size;
1500 /* align .rsrc size when possible */
1501 DWORD mapping_size = rsrc_is_last ? sec->PointerToRawData + section_size : old_size + delta;
1503 /* postpone file truncation if there are some data to be moved down from file end */
1504 BOOL resize_after = mapping_size < old_size && !rsrc_is_last;
1506 TRACE("file size %08x -> %08x\n", old_size, mapping_size);
1508 if (!resize_after)
1510 /* unmap the file before changing the file size */
1511 ret = resize_mapping( write_map, mapping_size );
1513 /* get the pointers again - they might be different after remapping */
1514 nt = get_nt_header( write_map->base, mapping_size );
1515 if (!nt)
1517 ERR("couldn't get NT header\n");
1518 goto done;
1521 sec = get_resource_section( write_map->base, mapping_size );
1522 if (!sec)
1523 goto done;
1526 if (!rsrc_is_last) /* not last section, relocate trailing sections */
1528 IMAGE_SECTION_HEADER *s;
1529 DWORD tail_start = sec->PointerToRawData + sec->SizeOfRawData;
1530 DWORD i, num_sections = 0;
1532 memmove( (char*)write_map->base + tail_start + delta, (char*)write_map->base + tail_start, old_size - tail_start );
1534 s = get_section_header( write_map->base, mapping_size, &num_sections );
1536 for (i=0; i<num_sections; i++)
1538 if (s[i].PointerToRawData > sec->PointerToRawData)
1540 s[i].PointerToRawData += delta;
1541 s[i].VirtualAddress += rva_delta;
1546 if (resize_after)
1548 ret = resize_mapping( write_map, mapping_size );
1550 nt = get_nt_header( write_map->base, mapping_size );
1551 if (!nt)
1553 ERR("couldn't get NT header\n");
1554 goto done;
1557 sec = get_resource_section( write_map->base, mapping_size );
1558 if (!sec)
1559 goto done;
1562 /* adjust the PE header information */
1563 sec->SizeOfRawData = section_size;
1564 sec->Misc.VirtualSize = virtual_section_size;
1565 nt->OptionalHeader.SizeOfImage += rva_delta;
1566 nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size = res_size.total_size;
1567 nt->OptionalHeader.SizeOfInitializedData = get_init_data_size( write_map->base, mapping_size );
1570 res_base = (LPBYTE) write_map->base + sec->PointerToRawData;
1572 TRACE("base = %p offset = %08x\n", write_map->base, sec->PointerToRawData);
1574 ret = write_resources( updates, res_base, &res_size, sec->VirtualAddress );
1576 res_write_padding( res_base + res_size.total_size, section_size - res_size.total_size );
1578 TRACE("after .rsrc at %08x, size %08x\n", sec->PointerToRawData, sec->SizeOfRawData);
1580 done:
1581 destroy_mapping( read_map );
1582 destroy_mapping( write_map );
1584 if (ret)
1585 ret = CopyFileW( tempfile, updates->pFileName, FALSE );
1587 DeleteFileW( tempfile );
1589 return ret;
1592 /***********************************************************************
1593 * BeginUpdateResourceW (KERNEL32.@)
1595 HANDLE WINAPI BeginUpdateResourceW( LPCWSTR pFileName, BOOL bDeleteExistingResources )
1597 QUEUEDUPDATES *updates = NULL;
1598 HANDLE hUpdate, file, ret = NULL;
1600 TRACE("%s, %d\n", debugstr_w(pFileName), bDeleteExistingResources);
1602 hUpdate = GlobalAlloc(GHND, sizeof(QUEUEDUPDATES));
1603 if (!hUpdate)
1604 return ret;
1606 updates = GlobalLock(hUpdate);
1607 if (updates)
1609 list_init( &updates->root );
1610 updates->bDeleteExistingResources = bDeleteExistingResources;
1611 updates->pFileName = HeapAlloc(GetProcessHeap(), 0, (lstrlenW(pFileName)+1)*sizeof(WCHAR));
1612 if (updates->pFileName)
1614 lstrcpyW(updates->pFileName, pFileName);
1616 file = CreateFileW( pFileName, GENERIC_READ | GENERIC_WRITE,
1617 0, NULL, OPEN_EXISTING, 0, 0 );
1619 /* if resources are deleted, only the file's presence is checked */
1620 if (file != INVALID_HANDLE_VALUE &&
1621 (bDeleteExistingResources || check_pe_exe( file, updates )))
1622 ret = hUpdate;
1623 else
1624 HeapFree( GetProcessHeap(), 0, updates->pFileName );
1626 CloseHandle( file );
1628 GlobalUnlock(hUpdate);
1631 if (!ret)
1632 GlobalFree(hUpdate);
1634 return ret;
1638 /***********************************************************************
1639 * BeginUpdateResourceA (KERNEL32.@)
1641 HANDLE WINAPI BeginUpdateResourceA( LPCSTR pFileName, BOOL bDeleteExistingResources )
1643 UNICODE_STRING FileNameW;
1644 HANDLE ret;
1645 RtlCreateUnicodeStringFromAsciiz(&FileNameW, pFileName);
1646 ret = BeginUpdateResourceW(FileNameW.Buffer, bDeleteExistingResources);
1647 RtlFreeUnicodeString(&FileNameW);
1648 return ret;
1652 /***********************************************************************
1653 * EndUpdateResourceW (KERNEL32.@)
1655 BOOL WINAPI EndUpdateResourceW( HANDLE hUpdate, BOOL fDiscard )
1657 QUEUEDUPDATES *updates;
1658 BOOL ret;
1660 TRACE("%p %d\n", hUpdate, fDiscard);
1662 updates = GlobalLock(hUpdate);
1663 if (!updates)
1664 return FALSE;
1666 ret = fDiscard || write_raw_resources( updates );
1668 free_resource_directory( &updates->root, 2 );
1670 HeapFree( GetProcessHeap(), 0, updates->pFileName );
1671 GlobalUnlock( hUpdate );
1672 GlobalFree( hUpdate );
1674 return ret;
1678 /***********************************************************************
1679 * EndUpdateResourceA (KERNEL32.@)
1681 BOOL WINAPI EndUpdateResourceA( HANDLE hUpdate, BOOL fDiscard )
1683 return EndUpdateResourceW(hUpdate, fDiscard);
1687 /***********************************************************************
1688 * UpdateResourceW (KERNEL32.@)
1690 BOOL WINAPI UpdateResourceW( HANDLE hUpdate, LPCWSTR lpType, LPCWSTR lpName,
1691 WORD wLanguage, LPVOID lpData, DWORD cbData)
1693 QUEUEDUPDATES *updates;
1694 BOOL ret = FALSE;
1696 TRACE("%p %s %s %08x %p %d\n", hUpdate,
1697 debugstr_w(lpType), debugstr_w(lpName), wLanguage, lpData, cbData);
1699 updates = GlobalLock(hUpdate);
1700 if (updates)
1702 if (lpData == NULL && cbData == 0) /* remove resource */
1704 ret = update_add_resource( updates, lpType, lpName, wLanguage, NULL, TRUE );
1706 else
1708 struct resource_data *data;
1709 data = allocate_resource_data( wLanguage, 0, lpData, cbData, TRUE );
1710 if (data)
1711 ret = update_add_resource( updates, lpType, lpName, wLanguage, data, TRUE );
1713 GlobalUnlock(hUpdate);
1715 return ret;
1719 /***********************************************************************
1720 * UpdateResourceA (KERNEL32.@)
1722 BOOL WINAPI UpdateResourceA( HANDLE hUpdate, LPCSTR lpType, LPCSTR lpName,
1723 WORD wLanguage, LPVOID lpData, DWORD cbData)
1725 BOOL ret;
1726 UNICODE_STRING TypeW;
1727 UNICODE_STRING NameW;
1728 if(IS_INTRESOURCE(lpType))
1729 TypeW.Buffer = ULongToPtr(LOWORD(lpType));
1730 else
1731 RtlCreateUnicodeStringFromAsciiz(&TypeW, lpType);
1732 if(IS_INTRESOURCE(lpName))
1733 NameW.Buffer = ULongToPtr(LOWORD(lpName));
1734 else
1735 RtlCreateUnicodeStringFromAsciiz(&NameW, lpName);
1736 ret = UpdateResourceW(hUpdate, TypeW.Buffer, NameW.Buffer, wLanguage, lpData, cbData);
1737 if(!IS_INTRESOURCE(lpType)) RtlFreeUnicodeString(&TypeW);
1738 if(!IS_INTRESOURCE(lpName)) RtlFreeUnicodeString(&NameW);
1739 return ret;