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