1 /* Support for the generic parts of PE/PEI; the common executable parts.
2 Copyright (C) 1995-2014 Free Software Foundation, Inc.
3 Written by Cygnus Solutions.
4
5 This file is part of BFD, the Binary File Descriptor library.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
20 MA 02110-1301, USA. */
21
22
23 /* Most of this hacked by Steve Chamberlain <sac@cygnus.com>.
24
25 PE/PEI rearrangement (and code added): Donn Terry
26 Softway Systems, Inc. */
27
28 /* Hey look, some documentation [and in a place you expect to find it]!
29
30 The main reference for the pei format is "Microsoft Portable Executable
31 and Common Object File Format Specification 4.1". Get it if you need to
32 do some serious hacking on this code.
33
34 Another reference:
35 "Peering Inside the PE: A Tour of the Win32 Portable Executable
36 File Format", MSJ 1994, Volume 9.
37
38 The *sole* difference between the pe format and the pei format is that the
39 latter has an MSDOS 2.0 .exe header on the front that prints the message
40 "This app must be run under Windows." (or some such).
41 (FIXME: Whether that statement is *really* true or not is unknown.
42 Are there more subtle differences between pe and pei formats?
43 For now assume there aren't. If you find one, then for God sakes
44 document it here!)
45
46 The Microsoft docs use the word "image" instead of "executable" because
47 the former can also refer to a DLL (shared library). Confusion can arise
48 because the `i' in `pei' also refers to "image". The `pe' format can
49 also create images (i.e. executables), it's just that to run on a win32
50 system you need to use the pei format.
51
52 FIXME: Please add more docs here so the next poor fool that has to hack
53 on this code has a chance of getting something accomplished without
54 wasting too much time. */
55
56 /* This expands into COFF_WITH_pe, COFF_WITH_pep, or COFF_WITH_pex64
57 depending on whether we're compiling for straight PE or PE+. */
58 #define COFF_WITH_XX
59
60 #include "sysdep.h"
61 #include "bfd.h"
62 #include "libbfd.h"
63 #include "coff/internal.h"
64 #include "bfdver.h"
65 #ifdef HAVE_WCHAR_H
66 #include <wchar.h>
67 #endif
68 #ifdef HAVE_WCTYPE_H
69 #include <wctype.h>
70 #endif
71
72 /* NOTE: it's strange to be including an architecture specific header
73 in what's supposed to be general (to PE/PEI) code. However, that's
74 where the definitions are, and they don't vary per architecture
75 within PE/PEI, so we get them from there. FIXME: The lack of
76 variance is an assumption which may prove to be incorrect if new
77 PE/PEI targets are created. */
78 #if defined COFF_WITH_pex64
79 # include "coff/x86_64.h"
80 #elif defined COFF_WITH_pep
81 # include "coff/ia64.h"
82 #else
83 # include "coff/i386.h"
84 #endif
85
86 #include "coff/pe.h"
87 #include "libcoff.h"
88 #include "libpei.h"
89 #include "safe-ctype.h"
90
91 #if defined COFF_WITH_pep || defined COFF_WITH_pex64
92 # undef AOUTSZ
93 # define AOUTSZ PEPAOUTSZ
94 # define PEAOUTHDR PEPAOUTHDR
95 #endif
96
97 #define HighBitSet(val) ((val) & 0x80000000)
98 #define SetHighBit(val) ((val) | 0x80000000)
99 #define WithoutHighBit(val) ((val) & 0x7fffffff)
100
101 /* FIXME: This file has various tests of POWERPC_LE_PE. Those tests
102 worked when the code was in peicode.h, but no longer work now that
103 the code is in peigen.c. PowerPC NT is said to be dead. If
104 anybody wants to revive the code, you will have to figure out how
105 to handle those issues. */
106
107 void
_bfd_XXi_swap_sym_in(bfd * abfd,void * ext1,void * in1)108 _bfd_XXi_swap_sym_in (bfd * abfd, void * ext1, void * in1)
109 {
110 SYMENT *ext = (SYMENT *) ext1;
111 struct internal_syment *in = (struct internal_syment *) in1;
112
113 if (ext->e.e_name[0] == 0)
114 {
115 in->_n._n_n._n_zeroes = 0;
116 in->_n._n_n._n_offset = H_GET_32 (abfd, ext->e.e.e_offset);
117 }
118 else
119 memcpy (in->_n._n_name, ext->e.e_name, SYMNMLEN);
120
121 in->n_value = H_GET_32 (abfd, ext->e_value);
122 in->n_scnum = H_GET_16 (abfd, ext->e_scnum);
123
124 if (sizeof (ext->e_type) == 2)
125 in->n_type = H_GET_16 (abfd, ext->e_type);
126 else
127 in->n_type = H_GET_32 (abfd, ext->e_type);
128
129 in->n_sclass = H_GET_8 (abfd, ext->e_sclass);
130 in->n_numaux = H_GET_8 (abfd, ext->e_numaux);
131
132 #ifndef STRICT_PE_FORMAT
133 /* This is for Gnu-created DLLs. */
134
135 /* The section symbols for the .idata$ sections have class 0x68
136 (C_SECTION), which MS documentation indicates is a section
137 symbol. Unfortunately, the value field in the symbol is simply a
138 copy of the .idata section's flags rather than something useful.
139 When these symbols are encountered, change the value to 0 so that
140 they will be handled somewhat correctly in the bfd code. */
141 if (in->n_sclass == C_SECTION)
142 {
143 char namebuf[SYMNMLEN + 1];
144 const char *name = NULL;
145
146 in->n_value = 0x0;
147
148 /* Create synthetic empty sections as needed. DJ */
149 if (in->n_scnum == 0)
150 {
151 asection *sec;
152
153 name = _bfd_coff_internal_syment_name (abfd, in, namebuf);
154 if (name == NULL)
155 {
156 _bfd_error_handler (_("%B: unable to find name for empty section"),
157 abfd);
158 bfd_set_error (bfd_error_invalid_target);
159 return;
160 }
161
162 sec = bfd_get_section_by_name (abfd, name);
163 if (sec != NULL)
164 in->n_scnum = sec->target_index;
165 }
166
167 if (in->n_scnum == 0)
168 {
169 int unused_section_number = 0;
170 asection *sec;
171 flagword flags;
172
173 for (sec = abfd->sections; sec; sec = sec->next)
174 if (unused_section_number <= sec->target_index)
175 unused_section_number = sec->target_index + 1;
176
177 if (name == namebuf)
178 {
179 name = (const char *) bfd_alloc (abfd, strlen (namebuf) + 1);
180 if (name == NULL)
181 {
182 _bfd_error_handler (_("%B: out of memory creating name for empty section"),
183 abfd);
184 return;
185 }
186 strcpy ((char *) name, namebuf);
187 }
188
189 flags = SEC_HAS_CONTENTS | SEC_ALLOC | SEC_DATA | SEC_LOAD;
190 sec = bfd_make_section_anyway_with_flags (abfd, name, flags);
191 if (sec == NULL)
192 {
193 _bfd_error_handler (_("%B: unable to create fake empty section"),
194 abfd);
195 return;
196 }
197
198 sec->vma = 0;
199 sec->lma = 0;
200 sec->size = 0;
201 sec->filepos = 0;
202 sec->rel_filepos = 0;
203 sec->reloc_count = 0;
204 sec->line_filepos = 0;
205 sec->lineno_count = 0;
206 sec->userdata = NULL;
207 sec->next = NULL;
208 sec->alignment_power = 2;
209
210 sec->target_index = unused_section_number;
211
212 in->n_scnum = unused_section_number;
213 }
214 in->n_sclass = C_STAT;
215 }
216 #endif
217
218 #ifdef coff_swap_sym_in_hook
219 /* This won't work in peigen.c, but since it's for PPC PE, it's not
220 worth fixing. */
221 coff_swap_sym_in_hook (abfd, ext1, in1);
222 #endif
223 }
224
225 static bfd_boolean
abs_finder(bfd * abfd ATTRIBUTE_UNUSED,asection * sec,void * data)226 abs_finder (bfd * abfd ATTRIBUTE_UNUSED, asection * sec, void * data)
227 {
228 bfd_vma abs_val = * (bfd_vma *) data;
229
230 return (sec->vma <= abs_val) && ((sec->vma + (1ULL << 32)) > abs_val);
231 }
232
233 unsigned int
_bfd_XXi_swap_sym_out(bfd * abfd,void * inp,void * extp)234 _bfd_XXi_swap_sym_out (bfd * abfd, void * inp, void * extp)
235 {
236 struct internal_syment *in = (struct internal_syment *) inp;
237 SYMENT *ext = (SYMENT *) extp;
238
239 if (in->_n._n_name[0] == 0)
240 {
241 H_PUT_32 (abfd, 0, ext->e.e.e_zeroes);
242 H_PUT_32 (abfd, in->_n._n_n._n_offset, ext->e.e.e_offset);
243 }
244 else
245 memcpy (ext->e.e_name, in->_n._n_name, SYMNMLEN);
246
247 /* The PE32 and PE32+ formats only use 4 bytes to hold the value of a
248 symbol. This is a problem on 64-bit targets where we can generate
249 absolute symbols with values >= 1^32. We try to work around this
250 problem by finding a section whose base address is sufficient to
251 reduce the absolute value to < 1^32, and then transforming the
252 symbol into a section relative symbol. This of course is a hack. */
253 if (sizeof (in->n_value) > 4
254 /* The strange computation of the shift amount is here in order to
255 avoid a compile time warning about the comparison always being
256 false. It does not matter if this test fails to work as expected
257 as the worst that can happen is that some absolute symbols are
258 needlessly converted into section relative symbols. */
259 && in->n_value > ((1ULL << (sizeof (in->n_value) > 4 ? 32 : 31)) - 1)
260 && in->n_scnum == -1)
261 {
262 asection * sec;
263
264 sec = bfd_sections_find_if (abfd, abs_finder, & in->n_value);
265 if (sec)
266 {
267 in->n_value -= sec->vma;
268 in->n_scnum = sec->target_index;
269 }
270 /* else: FIXME: The value is outside the range of any section. This
271 happens for __image_base__ and __ImageBase and maybe some other
272 symbols as well. We should find a way to handle these values. */
273 }
274
275 H_PUT_32 (abfd, in->n_value, ext->e_value);
276 H_PUT_16 (abfd, in->n_scnum, ext->e_scnum);
277
278 if (sizeof (ext->e_type) == 2)
279 H_PUT_16 (abfd, in->n_type, ext->e_type);
280 else
281 H_PUT_32 (abfd, in->n_type, ext->e_type);
282
283 H_PUT_8 (abfd, in->n_sclass, ext->e_sclass);
284 H_PUT_8 (abfd, in->n_numaux, ext->e_numaux);
285
286 return SYMESZ;
287 }
288
289 void
_bfd_XXi_swap_aux_in(bfd * abfd,void * ext1,int type,int in_class,int indx ATTRIBUTE_UNUSED,int numaux ATTRIBUTE_UNUSED,void * in1)290 _bfd_XXi_swap_aux_in (bfd * abfd,
291 void * ext1,
292 int type,
293 int in_class,
294 int indx ATTRIBUTE_UNUSED,
295 int numaux ATTRIBUTE_UNUSED,
296 void * in1)
297 {
298 AUXENT *ext = (AUXENT *) ext1;
299 union internal_auxent *in = (union internal_auxent *) in1;
300
301 /* PR 17521: Make sure that all fields in the aux structure
302 are initialised. */
303 memset (in, 0, sizeof * in);
304 switch (in_class)
305 {
306 case C_FILE:
307 if (ext->x_file.x_fname[0] == 0)
308 {
309 in->x_file.x_n.x_zeroes = 0;
310 in->x_file.x_n.x_offset = H_GET_32 (abfd, ext->x_file.x_n.x_offset);
311 }
312 else
313 memcpy (in->x_file.x_fname, ext->x_file.x_fname, FILNMLEN);
314 return;
315
316 case C_STAT:
317 case C_LEAFSTAT:
318 case C_HIDDEN:
319 if (type == T_NULL)
320 {
321 in->x_scn.x_scnlen = GET_SCN_SCNLEN (abfd, ext);
322 in->x_scn.x_nreloc = GET_SCN_NRELOC (abfd, ext);
323 in->x_scn.x_nlinno = GET_SCN_NLINNO (abfd, ext);
324 in->x_scn.x_checksum = H_GET_32 (abfd, ext->x_scn.x_checksum);
325 in->x_scn.x_associated = H_GET_16 (abfd, ext->x_scn.x_associated);
326 in->x_scn.x_comdat = H_GET_8 (abfd, ext->x_scn.x_comdat);
327 return;
328 }
329 break;
330 }
331
332 in->x_sym.x_tagndx.l = H_GET_32 (abfd, ext->x_sym.x_tagndx);
333 in->x_sym.x_tvndx = H_GET_16 (abfd, ext->x_sym.x_tvndx);
334
335 if (in_class == C_BLOCK || in_class == C_FCN || ISFCN (type)
336 || ISTAG (in_class))
337 {
338 in->x_sym.x_fcnary.x_fcn.x_lnnoptr = GET_FCN_LNNOPTR (abfd, ext);
339 in->x_sym.x_fcnary.x_fcn.x_endndx.l = GET_FCN_ENDNDX (abfd, ext);
340 }
341 else
342 {
343 in->x_sym.x_fcnary.x_ary.x_dimen[0] =
344 H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[0]);
345 in->x_sym.x_fcnary.x_ary.x_dimen[1] =
346 H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[1]);
347 in->x_sym.x_fcnary.x_ary.x_dimen[2] =
348 H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[2]);
349 in->x_sym.x_fcnary.x_ary.x_dimen[3] =
350 H_GET_16 (abfd, ext->x_sym.x_fcnary.x_ary.x_dimen[3]);
351 }
352
353 if (ISFCN (type))
354 {
355 in->x_sym.x_misc.x_fsize = H_GET_32 (abfd, ext->x_sym.x_misc.x_fsize);
356 }
357 else
358 {
359 in->x_sym.x_misc.x_lnsz.x_lnno = GET_LNSZ_LNNO (abfd, ext);
360 in->x_sym.x_misc.x_lnsz.x_size = GET_LNSZ_SIZE (abfd, ext);
361 }
362 }
363
364 unsigned int
_bfd_XXi_swap_aux_out(bfd * abfd,void * inp,int type,int in_class,int indx ATTRIBUTE_UNUSED,int numaux ATTRIBUTE_UNUSED,void * extp)365 _bfd_XXi_swap_aux_out (bfd * abfd,
366 void * inp,
367 int type,
368 int in_class,
369 int indx ATTRIBUTE_UNUSED,
370 int numaux ATTRIBUTE_UNUSED,
371 void * extp)
372 {
373 union internal_auxent *in = (union internal_auxent *) inp;
374 AUXENT *ext = (AUXENT *) extp;
375
376 memset (ext, 0, AUXESZ);
377
378 switch (in_class)
379 {
380 case C_FILE:
381 if (in->x_file.x_fname[0] == 0)
382 {
383 H_PUT_32 (abfd, 0, ext->x_file.x_n.x_zeroes);
384 H_PUT_32 (abfd, in->x_file.x_n.x_offset, ext->x_file.x_n.x_offset);
385 }
386 else
387 memcpy (ext->x_file.x_fname, in->x_file.x_fname, FILNMLEN);
388
389 return AUXESZ;
390
391 case C_STAT:
392 case C_LEAFSTAT:
393 case C_HIDDEN:
394 if (type == T_NULL)
395 {
396 PUT_SCN_SCNLEN (abfd, in->x_scn.x_scnlen, ext);
397 PUT_SCN_NRELOC (abfd, in->x_scn.x_nreloc, ext);
398 PUT_SCN_NLINNO (abfd, in->x_scn.x_nlinno, ext);
399 H_PUT_32 (abfd, in->x_scn.x_checksum, ext->x_scn.x_checksum);
400 H_PUT_16 (abfd, in->x_scn.x_associated, ext->x_scn.x_associated);
401 H_PUT_8 (abfd, in->x_scn.x_comdat, ext->x_scn.x_comdat);
402 return AUXESZ;
403 }
404 break;
405 }
406
407 H_PUT_32 (abfd, in->x_sym.x_tagndx.l, ext->x_sym.x_tagndx);
408 H_PUT_16 (abfd, in->x_sym.x_tvndx, ext->x_sym.x_tvndx);
409
410 if (in_class == C_BLOCK || in_class == C_FCN || ISFCN (type)
411 || ISTAG (in_class))
412 {
413 PUT_FCN_LNNOPTR (abfd, in->x_sym.x_fcnary.x_fcn.x_lnnoptr, ext);
414 PUT_FCN_ENDNDX (abfd, in->x_sym.x_fcnary.x_fcn.x_endndx.l, ext);
415 }
416 else
417 {
418 H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[0],
419 ext->x_sym.x_fcnary.x_ary.x_dimen[0]);
420 H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[1],
421 ext->x_sym.x_fcnary.x_ary.x_dimen[1]);
422 H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[2],
423 ext->x_sym.x_fcnary.x_ary.x_dimen[2]);
424 H_PUT_16 (abfd, in->x_sym.x_fcnary.x_ary.x_dimen[3],
425 ext->x_sym.x_fcnary.x_ary.x_dimen[3]);
426 }
427
428 if (ISFCN (type))
429 H_PUT_32 (abfd, in->x_sym.x_misc.x_fsize, ext->x_sym.x_misc.x_fsize);
430 else
431 {
432 PUT_LNSZ_LNNO (abfd, in->x_sym.x_misc.x_lnsz.x_lnno, ext);
433 PUT_LNSZ_SIZE (abfd, in->x_sym.x_misc.x_lnsz.x_size, ext);
434 }
435
436 return AUXESZ;
437 }
438
439 void
_bfd_XXi_swap_lineno_in(bfd * abfd,void * ext1,void * in1)440 _bfd_XXi_swap_lineno_in (bfd * abfd, void * ext1, void * in1)
441 {
442 LINENO *ext = (LINENO *) ext1;
443 struct internal_lineno *in = (struct internal_lineno *) in1;
444
445 in->l_addr.l_symndx = H_GET_32 (abfd, ext->l_addr.l_symndx);
446 in->l_lnno = GET_LINENO_LNNO (abfd, ext);
447 }
448
449 unsigned int
_bfd_XXi_swap_lineno_out(bfd * abfd,void * inp,void * outp)450 _bfd_XXi_swap_lineno_out (bfd * abfd, void * inp, void * outp)
451 {
452 struct internal_lineno *in = (struct internal_lineno *) inp;
453 struct external_lineno *ext = (struct external_lineno *) outp;
454 H_PUT_32 (abfd, in->l_addr.l_symndx, ext->l_addr.l_symndx);
455
456 PUT_LINENO_LNNO (abfd, in->l_lnno, ext);
457 return LINESZ;
458 }
459
460 void
_bfd_XXi_swap_aouthdr_in(bfd * abfd,void * aouthdr_ext1,void * aouthdr_int1)461 _bfd_XXi_swap_aouthdr_in (bfd * abfd,
462 void * aouthdr_ext1,
463 void * aouthdr_int1)
464 {
465 PEAOUTHDR * src = (PEAOUTHDR *) aouthdr_ext1;
466 AOUTHDR * aouthdr_ext = (AOUTHDR *) aouthdr_ext1;
467 struct internal_aouthdr *aouthdr_int
468 = (struct internal_aouthdr *) aouthdr_int1;
469 struct internal_extra_pe_aouthdr *a = &aouthdr_int->pe;
470
471 aouthdr_int->magic = H_GET_16 (abfd, aouthdr_ext->magic);
472 aouthdr_int->vstamp = H_GET_16 (abfd, aouthdr_ext->vstamp);
473 aouthdr_int->tsize = GET_AOUTHDR_TSIZE (abfd, aouthdr_ext->tsize);
474 aouthdr_int->dsize = GET_AOUTHDR_DSIZE (abfd, aouthdr_ext->dsize);
475 aouthdr_int->bsize = GET_AOUTHDR_BSIZE (abfd, aouthdr_ext->bsize);
476 aouthdr_int->entry = GET_AOUTHDR_ENTRY (abfd, aouthdr_ext->entry);
477 aouthdr_int->text_start =
478 GET_AOUTHDR_TEXT_START (abfd, aouthdr_ext->text_start);
479
480 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
481 /* PE32+ does not have data_start member! */
482 aouthdr_int->data_start =
483 GET_AOUTHDR_DATA_START (abfd, aouthdr_ext->data_start);
484 a->BaseOfData = aouthdr_int->data_start;
485 #endif
486
487 a->Magic = aouthdr_int->magic;
488 a->MajorLinkerVersion = H_GET_8 (abfd, aouthdr_ext->vstamp);
489 a->MinorLinkerVersion = H_GET_8 (abfd, aouthdr_ext->vstamp + 1);
490 a->SizeOfCode = aouthdr_int->tsize ;
491 a->SizeOfInitializedData = aouthdr_int->dsize ;
492 a->SizeOfUninitializedData = aouthdr_int->bsize ;
493 a->AddressOfEntryPoint = aouthdr_int->entry;
494 a->BaseOfCode = aouthdr_int->text_start;
495 a->ImageBase = GET_OPTHDR_IMAGE_BASE (abfd, src->ImageBase);
496 a->SectionAlignment = H_GET_32 (abfd, src->SectionAlignment);
497 a->FileAlignment = H_GET_32 (abfd, src->FileAlignment);
498 a->MajorOperatingSystemVersion =
499 H_GET_16 (abfd, src->MajorOperatingSystemVersion);
500 a->MinorOperatingSystemVersion =
501 H_GET_16 (abfd, src->MinorOperatingSystemVersion);
502 a->MajorImageVersion = H_GET_16 (abfd, src->MajorImageVersion);
503 a->MinorImageVersion = H_GET_16 (abfd, src->MinorImageVersion);
504 a->MajorSubsystemVersion = H_GET_16 (abfd, src->MajorSubsystemVersion);
505 a->MinorSubsystemVersion = H_GET_16 (abfd, src->MinorSubsystemVersion);
506 a->Reserved1 = H_GET_32 (abfd, src->Reserved1);
507 a->SizeOfImage = H_GET_32 (abfd, src->SizeOfImage);
508 a->SizeOfHeaders = H_GET_32 (abfd, src->SizeOfHeaders);
509 a->CheckSum = H_GET_32 (abfd, src->CheckSum);
510 a->Subsystem = H_GET_16 (abfd, src->Subsystem);
511 a->DllCharacteristics = H_GET_16 (abfd, src->DllCharacteristics);
512 a->SizeOfStackReserve =
513 GET_OPTHDR_SIZE_OF_STACK_RESERVE (abfd, src->SizeOfStackReserve);
514 a->SizeOfStackCommit =
515 GET_OPTHDR_SIZE_OF_STACK_COMMIT (abfd, src->SizeOfStackCommit);
516 a->SizeOfHeapReserve =
517 GET_OPTHDR_SIZE_OF_HEAP_RESERVE (abfd, src->SizeOfHeapReserve);
518 a->SizeOfHeapCommit =
519 GET_OPTHDR_SIZE_OF_HEAP_COMMIT (abfd, src->SizeOfHeapCommit);
520 a->LoaderFlags = H_GET_32 (abfd, src->LoaderFlags);
521 a->NumberOfRvaAndSizes = H_GET_32 (abfd, src->NumberOfRvaAndSizes);
522
523 {
524 int idx;
525
526 /* PR 17512: Corrupt PE binaries can cause seg-faults. */
527 if (a->NumberOfRvaAndSizes > IMAGE_NUMBEROF_DIRECTORY_ENTRIES)
528 {
529 (*_bfd_error_handler)
530 (_("%B: aout header specifies an invalid number of data-directory entries: %d"),
531 abfd, a->NumberOfRvaAndSizes);
532 /* Paranoia: If the number is corrupt, then assume that the
533 actual entries themselves might be corrupt as well. */
534 a->NumberOfRvaAndSizes = 0;
535 }
536
537 for (idx = 0; idx < a->NumberOfRvaAndSizes; idx++)
538 {
539 /* If data directory is empty, rva also should be 0. */
540 int size =
541 H_GET_32 (abfd, src->DataDirectory[idx][1]);
542
543 a->DataDirectory[idx].Size = size;
544
545 if (size)
546 a->DataDirectory[idx].VirtualAddress =
547 H_GET_32 (abfd, src->DataDirectory[idx][0]);
548 else
549 a->DataDirectory[idx].VirtualAddress = 0;
550 }
551
552 while (idx < IMAGE_NUMBEROF_DIRECTORY_ENTRIES)
553 {
554 a->DataDirectory[idx].Size = 0;
555 a->DataDirectory[idx].VirtualAddress = 0;
556 idx ++;
557 }
558 }
559
560 if (aouthdr_int->entry)
561 {
562 aouthdr_int->entry += a->ImageBase;
563 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
564 aouthdr_int->entry &= 0xffffffff;
565 #endif
566 }
567
568 if (aouthdr_int->tsize)
569 {
570 aouthdr_int->text_start += a->ImageBase;
571 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
572 aouthdr_int->text_start &= 0xffffffff;
573 #endif
574 }
575
576 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
577 /* PE32+ does not have data_start member! */
578 if (aouthdr_int->dsize)
579 {
580 aouthdr_int->data_start += a->ImageBase;
581 aouthdr_int->data_start &= 0xffffffff;
582 }
583 #endif
584
585 #ifdef POWERPC_LE_PE
586 /* These three fields are normally set up by ppc_relocate_section.
587 In the case of reading a file in, we can pick them up from the
588 DataDirectory. */
589 first_thunk_address = a->DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress;
590 thunk_size = a->DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size;
591 import_table_size = a->DataDirectory[PE_IMPORT_TABLE].Size;
592 #endif
593 }
594
595 /* A support function for below. */
596
597 static void
add_data_entry(bfd * abfd,struct internal_extra_pe_aouthdr * aout,int idx,char * name,bfd_vma base)598 add_data_entry (bfd * abfd,
599 struct internal_extra_pe_aouthdr *aout,
600 int idx,
601 char *name,
602 bfd_vma base)
603 {
604 asection *sec = bfd_get_section_by_name (abfd, name);
605
606 /* Add import directory information if it exists. */
607 if ((sec != NULL)
608 && (coff_section_data (abfd, sec) != NULL)
609 && (pei_section_data (abfd, sec) != NULL))
610 {
611 /* If data directory is empty, rva also should be 0. */
612 int size = pei_section_data (abfd, sec)->virt_size;
613 aout->DataDirectory[idx].Size = size;
614
615 if (size)
616 {
617 aout->DataDirectory[idx].VirtualAddress =
618 (sec->vma - base) & 0xffffffff;
619 sec->flags |= SEC_DATA;
620 }
621 }
622 }
623
624 unsigned int
_bfd_XXi_swap_aouthdr_out(bfd * abfd,void * in,void * out)625 _bfd_XXi_swap_aouthdr_out (bfd * abfd, void * in, void * out)
626 {
627 struct internal_aouthdr *aouthdr_in = (struct internal_aouthdr *) in;
628 pe_data_type *pe = pe_data (abfd);
629 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
630 PEAOUTHDR *aouthdr_out = (PEAOUTHDR *) out;
631 bfd_vma sa, fa, ib;
632 IMAGE_DATA_DIRECTORY idata2, idata5, tls;
633
634 sa = extra->SectionAlignment;
635 fa = extra->FileAlignment;
636 ib = extra->ImageBase;
637
638 idata2 = pe->pe_opthdr.DataDirectory[PE_IMPORT_TABLE];
639 idata5 = pe->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE];
640 tls = pe->pe_opthdr.DataDirectory[PE_TLS_TABLE];
641
642 if (aouthdr_in->tsize)
643 {
644 aouthdr_in->text_start -= ib;
645 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
646 aouthdr_in->text_start &= 0xffffffff;
647 #endif
648 }
649
650 if (aouthdr_in->dsize)
651 {
652 aouthdr_in->data_start -= ib;
653 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
654 aouthdr_in->data_start &= 0xffffffff;
655 #endif
656 }
657
658 if (aouthdr_in->entry)
659 {
660 aouthdr_in->entry -= ib;
661 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
662 aouthdr_in->entry &= 0xffffffff;
663 #endif
664 }
665
666 #define FA(x) (((x) + fa -1 ) & (- fa))
667 #define SA(x) (((x) + sa -1 ) & (- sa))
668
669 /* We like to have the sizes aligned. */
670 aouthdr_in->bsize = FA (aouthdr_in->bsize);
671
672 extra->NumberOfRvaAndSizes = IMAGE_NUMBEROF_DIRECTORY_ENTRIES;
673
674 add_data_entry (abfd, extra, 0, ".edata", ib);
675 add_data_entry (abfd, extra, 2, ".rsrc", ib);
676 add_data_entry (abfd, extra, 3, ".pdata", ib);
677
678 /* In theory we do not need to call add_data_entry for .idata$2 or
679 .idata$5. It will be done in bfd_coff_final_link where all the
680 required information is available. If however, we are not going
681 to perform a final link, eg because we have been invoked by objcopy
682 or strip, then we need to make sure that these Data Directory
683 entries are initialised properly.
684
685 So - we copy the input values into the output values, and then, if
686 a final link is going to be performed, it can overwrite them. */
687 extra->DataDirectory[PE_IMPORT_TABLE] = idata2;
688 extra->DataDirectory[PE_IMPORT_ADDRESS_TABLE] = idata5;
689 extra->DataDirectory[PE_TLS_TABLE] = tls;
690
691 if (extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress == 0)
692 /* Until other .idata fixes are made (pending patch), the entry for
693 .idata is needed for backwards compatibility. FIXME. */
694 add_data_entry (abfd, extra, 1, ".idata", ib);
695
696 /* For some reason, the virtual size (which is what's set by
697 add_data_entry) for .reloc is not the same as the size recorded
698 in this slot by MSVC; it doesn't seem to cause problems (so far),
699 but since it's the best we've got, use it. It does do the right
700 thing for .pdata. */
701 if (pe->has_reloc_section)
702 add_data_entry (abfd, extra, 5, ".reloc", ib);
703
704 {
705 asection *sec;
706 bfd_vma hsize = 0;
707 bfd_vma dsize = 0;
708 bfd_vma isize = 0;
709 bfd_vma tsize = 0;
710
711 for (sec = abfd->sections; sec; sec = sec->next)
712 {
713 int rounded = FA (sec->size);
714
715 /* The first non-zero section filepos is the header size.
716 Sections without contents will have a filepos of 0. */
717 if (hsize == 0)
718 hsize = sec->filepos;
719 if (sec->flags & SEC_DATA)
720 dsize += rounded;
721 if (sec->flags & SEC_CODE)
722 tsize += rounded;
723 /* The image size is the total VIRTUAL size (which is what is
724 in the virt_size field). Files have been seen (from MSVC
725 5.0 link.exe) where the file size of the .data segment is
726 quite small compared to the virtual size. Without this
727 fix, strip munges the file.
728
729 FIXME: We need to handle holes between sections, which may
730 happpen when we covert from another format. We just use
731 the virtual address and virtual size of the last section
732 for the image size. */
733 if (coff_section_data (abfd, sec) != NULL
734 && pei_section_data (abfd, sec) != NULL)
735 isize = (sec->vma - extra->ImageBase
736 + SA (FA (pei_section_data (abfd, sec)->virt_size)));
737 }
738
739 aouthdr_in->dsize = dsize;
740 aouthdr_in->tsize = tsize;
741 extra->SizeOfHeaders = hsize;
742 extra->SizeOfImage = isize;
743 }
744
745 H_PUT_16 (abfd, aouthdr_in->magic, aouthdr_out->standard.magic);
746
747 /* e.g. 219510000 is linker version 2.19 */
748 #define LINKER_VERSION ((short) (BFD_VERSION / 1000000))
749
750 /* This piece of magic sets the "linker version" field to
751 LINKER_VERSION. */
752 H_PUT_16 (abfd, (LINKER_VERSION / 100 + (LINKER_VERSION % 100) * 256),
753 aouthdr_out->standard.vstamp);
754
755 PUT_AOUTHDR_TSIZE (abfd, aouthdr_in->tsize, aouthdr_out->standard.tsize);
756 PUT_AOUTHDR_DSIZE (abfd, aouthdr_in->dsize, aouthdr_out->standard.dsize);
757 PUT_AOUTHDR_BSIZE (abfd, aouthdr_in->bsize, aouthdr_out->standard.bsize);
758 PUT_AOUTHDR_ENTRY (abfd, aouthdr_in->entry, aouthdr_out->standard.entry);
759 PUT_AOUTHDR_TEXT_START (abfd, aouthdr_in->text_start,
760 aouthdr_out->standard.text_start);
761
762 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
763 /* PE32+ does not have data_start member! */
764 PUT_AOUTHDR_DATA_START (abfd, aouthdr_in->data_start,
765 aouthdr_out->standard.data_start);
766 #endif
767
768 PUT_OPTHDR_IMAGE_BASE (abfd, extra->ImageBase, aouthdr_out->ImageBase);
769 H_PUT_32 (abfd, extra->SectionAlignment, aouthdr_out->SectionAlignment);
770 H_PUT_32 (abfd, extra->FileAlignment, aouthdr_out->FileAlignment);
771 H_PUT_16 (abfd, extra->MajorOperatingSystemVersion,
772 aouthdr_out->MajorOperatingSystemVersion);
773 H_PUT_16 (abfd, extra->MinorOperatingSystemVersion,
774 aouthdr_out->MinorOperatingSystemVersion);
775 H_PUT_16 (abfd, extra->MajorImageVersion, aouthdr_out->MajorImageVersion);
776 H_PUT_16 (abfd, extra->MinorImageVersion, aouthdr_out->MinorImageVersion);
777 H_PUT_16 (abfd, extra->MajorSubsystemVersion,
778 aouthdr_out->MajorSubsystemVersion);
779 H_PUT_16 (abfd, extra->MinorSubsystemVersion,
780 aouthdr_out->MinorSubsystemVersion);
781 H_PUT_32 (abfd, extra->Reserved1, aouthdr_out->Reserved1);
782 H_PUT_32 (abfd, extra->SizeOfImage, aouthdr_out->SizeOfImage);
783 H_PUT_32 (abfd, extra->SizeOfHeaders, aouthdr_out->SizeOfHeaders);
784 H_PUT_32 (abfd, extra->CheckSum, aouthdr_out->CheckSum);
785 H_PUT_16 (abfd, extra->Subsystem, aouthdr_out->Subsystem);
786 H_PUT_16 (abfd, extra->DllCharacteristics, aouthdr_out->DllCharacteristics);
787 PUT_OPTHDR_SIZE_OF_STACK_RESERVE (abfd, extra->SizeOfStackReserve,
788 aouthdr_out->SizeOfStackReserve);
789 PUT_OPTHDR_SIZE_OF_STACK_COMMIT (abfd, extra->SizeOfStackCommit,
790 aouthdr_out->SizeOfStackCommit);
791 PUT_OPTHDR_SIZE_OF_HEAP_RESERVE (abfd, extra->SizeOfHeapReserve,
792 aouthdr_out->SizeOfHeapReserve);
793 PUT_OPTHDR_SIZE_OF_HEAP_COMMIT (abfd, extra->SizeOfHeapCommit,
794 aouthdr_out->SizeOfHeapCommit);
795 H_PUT_32 (abfd, extra->LoaderFlags, aouthdr_out->LoaderFlags);
796 H_PUT_32 (abfd, extra->NumberOfRvaAndSizes,
797 aouthdr_out->NumberOfRvaAndSizes);
798 {
799 int idx;
800
801 for (idx = 0; idx < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; idx++)
802 {
803 H_PUT_32 (abfd, extra->DataDirectory[idx].VirtualAddress,
804 aouthdr_out->DataDirectory[idx][0]);
805 H_PUT_32 (abfd, extra->DataDirectory[idx].Size,
806 aouthdr_out->DataDirectory[idx][1]);
807 }
808 }
809
810 return AOUTSZ;
811 }
812
813 unsigned int
_bfd_XXi_only_swap_filehdr_out(bfd * abfd,void * in,void * out)814 _bfd_XXi_only_swap_filehdr_out (bfd * abfd, void * in, void * out)
815 {
816 int idx;
817 struct internal_filehdr *filehdr_in = (struct internal_filehdr *) in;
818 struct external_PEI_filehdr *filehdr_out = (struct external_PEI_filehdr *) out;
819
820 if (pe_data (abfd)->has_reloc_section
821 || pe_data (abfd)->dont_strip_reloc)
822 filehdr_in->f_flags &= ~F_RELFLG;
823
824 if (pe_data (abfd)->dll)
825 filehdr_in->f_flags |= F_DLL;
826
827 filehdr_in->pe.e_magic = DOSMAGIC;
828 filehdr_in->pe.e_cblp = 0x90;
829 filehdr_in->pe.e_cp = 0x3;
830 filehdr_in->pe.e_crlc = 0x0;
831 filehdr_in->pe.e_cparhdr = 0x4;
832 filehdr_in->pe.e_minalloc = 0x0;
833 filehdr_in->pe.e_maxalloc = 0xffff;
834 filehdr_in->pe.e_ss = 0x0;
835 filehdr_in->pe.e_sp = 0xb8;
836 filehdr_in->pe.e_csum = 0x0;
837 filehdr_in->pe.e_ip = 0x0;
838 filehdr_in->pe.e_cs = 0x0;
839 filehdr_in->pe.e_lfarlc = 0x40;
840 filehdr_in->pe.e_ovno = 0x0;
841
842 for (idx = 0; idx < 4; idx++)
843 filehdr_in->pe.e_res[idx] = 0x0;
844
845 filehdr_in->pe.e_oemid = 0x0;
846 filehdr_in->pe.e_oeminfo = 0x0;
847
848 for (idx = 0; idx < 10; idx++)
849 filehdr_in->pe.e_res2[idx] = 0x0;
850
851 filehdr_in->pe.e_lfanew = 0x80;
852
853 /* This next collection of data are mostly just characters. It
854 appears to be constant within the headers put on NT exes. */
855 filehdr_in->pe.dos_message[0] = 0x0eba1f0e;
856 filehdr_in->pe.dos_message[1] = 0xcd09b400;
857 filehdr_in->pe.dos_message[2] = 0x4c01b821;
858 filehdr_in->pe.dos_message[3] = 0x685421cd;
859 filehdr_in->pe.dos_message[4] = 0x70207369;
860 filehdr_in->pe.dos_message[5] = 0x72676f72;
861 filehdr_in->pe.dos_message[6] = 0x63206d61;
862 filehdr_in->pe.dos_message[7] = 0x6f6e6e61;
863 filehdr_in->pe.dos_message[8] = 0x65622074;
864 filehdr_in->pe.dos_message[9] = 0x6e757220;
865 filehdr_in->pe.dos_message[10] = 0x206e6920;
866 filehdr_in->pe.dos_message[11] = 0x20534f44;
867 filehdr_in->pe.dos_message[12] = 0x65646f6d;
868 filehdr_in->pe.dos_message[13] = 0x0a0d0d2e;
869 filehdr_in->pe.dos_message[14] = 0x24;
870 filehdr_in->pe.dos_message[15] = 0x0;
871 filehdr_in->pe.nt_signature = NT_SIGNATURE;
872
873 H_PUT_16 (abfd, filehdr_in->f_magic, filehdr_out->f_magic);
874 H_PUT_16 (abfd, filehdr_in->f_nscns, filehdr_out->f_nscns);
875
876 /* Only use a real timestamp if the option was chosen. */
877 if ((pe_data (abfd)->insert_timestamp))
878 H_PUT_32 (abfd, time (0), filehdr_out->f_timdat);
879
880 PUT_FILEHDR_SYMPTR (abfd, filehdr_in->f_symptr,
881 filehdr_out->f_symptr);
882 H_PUT_32 (abfd, filehdr_in->f_nsyms, filehdr_out->f_nsyms);
883 H_PUT_16 (abfd, filehdr_in->f_opthdr, filehdr_out->f_opthdr);
884 H_PUT_16 (abfd, filehdr_in->f_flags, filehdr_out->f_flags);
885
886 /* Put in extra dos header stuff. This data remains essentially
887 constant, it just has to be tacked on to the beginning of all exes
888 for NT. */
889 H_PUT_16 (abfd, filehdr_in->pe.e_magic, filehdr_out->e_magic);
890 H_PUT_16 (abfd, filehdr_in->pe.e_cblp, filehdr_out->e_cblp);
891 H_PUT_16 (abfd, filehdr_in->pe.e_cp, filehdr_out->e_cp);
892 H_PUT_16 (abfd, filehdr_in->pe.e_crlc, filehdr_out->e_crlc);
893 H_PUT_16 (abfd, filehdr_in->pe.e_cparhdr, filehdr_out->e_cparhdr);
894 H_PUT_16 (abfd, filehdr_in->pe.e_minalloc, filehdr_out->e_minalloc);
895 H_PUT_16 (abfd, filehdr_in->pe.e_maxalloc, filehdr_out->e_maxalloc);
896 H_PUT_16 (abfd, filehdr_in->pe.e_ss, filehdr_out->e_ss);
897 H_PUT_16 (abfd, filehdr_in->pe.e_sp, filehdr_out->e_sp);
898 H_PUT_16 (abfd, filehdr_in->pe.e_csum, filehdr_out->e_csum);
899 H_PUT_16 (abfd, filehdr_in->pe.e_ip, filehdr_out->e_ip);
900 H_PUT_16 (abfd, filehdr_in->pe.e_cs, filehdr_out->e_cs);
901 H_PUT_16 (abfd, filehdr_in->pe.e_lfarlc, filehdr_out->e_lfarlc);
902 H_PUT_16 (abfd, filehdr_in->pe.e_ovno, filehdr_out->e_ovno);
903
904 for (idx = 0; idx < 4; idx++)
905 H_PUT_16 (abfd, filehdr_in->pe.e_res[idx], filehdr_out->e_res[idx]);
906
907 H_PUT_16 (abfd, filehdr_in->pe.e_oemid, filehdr_out->e_oemid);
908 H_PUT_16 (abfd, filehdr_in->pe.e_oeminfo, filehdr_out->e_oeminfo);
909
910 for (idx = 0; idx < 10; idx++)
911 H_PUT_16 (abfd, filehdr_in->pe.e_res2[idx], filehdr_out->e_res2[idx]);
912
913 H_PUT_32 (abfd, filehdr_in->pe.e_lfanew, filehdr_out->e_lfanew);
914
915 for (idx = 0; idx < 16; idx++)
916 H_PUT_32 (abfd, filehdr_in->pe.dos_message[idx],
917 filehdr_out->dos_message[idx]);
918
919 /* Also put in the NT signature. */
920 H_PUT_32 (abfd, filehdr_in->pe.nt_signature, filehdr_out->nt_signature);
921
922 return FILHSZ;
923 }
924
925 unsigned int
_bfd_XX_only_swap_filehdr_out(bfd * abfd,void * in,void * out)926 _bfd_XX_only_swap_filehdr_out (bfd * abfd, void * in, void * out)
927 {
928 struct internal_filehdr *filehdr_in = (struct internal_filehdr *) in;
929 FILHDR *filehdr_out = (FILHDR *) out;
930
931 H_PUT_16 (abfd, filehdr_in->f_magic, filehdr_out->f_magic);
932 H_PUT_16 (abfd, filehdr_in->f_nscns, filehdr_out->f_nscns);
933 H_PUT_32 (abfd, filehdr_in->f_timdat, filehdr_out->f_timdat);
934 PUT_FILEHDR_SYMPTR (abfd, filehdr_in->f_symptr, filehdr_out->f_symptr);
935 H_PUT_32 (abfd, filehdr_in->f_nsyms, filehdr_out->f_nsyms);
936 H_PUT_16 (abfd, filehdr_in->f_opthdr, filehdr_out->f_opthdr);
937 H_PUT_16 (abfd, filehdr_in->f_flags, filehdr_out->f_flags);
938
939 return FILHSZ;
940 }
941
942 unsigned int
_bfd_XXi_swap_scnhdr_out(bfd * abfd,void * in,void * out)943 _bfd_XXi_swap_scnhdr_out (bfd * abfd, void * in, void * out)
944 {
945 struct internal_scnhdr *scnhdr_int = (struct internal_scnhdr *) in;
946 SCNHDR *scnhdr_ext = (SCNHDR *) out;
947 unsigned int ret = SCNHSZ;
948 bfd_vma ps;
949 bfd_vma ss;
950
951 memcpy (scnhdr_ext->s_name, scnhdr_int->s_name, sizeof (scnhdr_int->s_name));
952
953 PUT_SCNHDR_VADDR (abfd,
954 ((scnhdr_int->s_vaddr
955 - pe_data (abfd)->pe_opthdr.ImageBase)
956 & 0xffffffff),
957 scnhdr_ext->s_vaddr);
958
959 /* NT wants the size data to be rounded up to the next
960 NT_FILE_ALIGNMENT, but zero if it has no content (as in .bss,
961 sometimes). */
962 if ((scnhdr_int->s_flags & IMAGE_SCN_CNT_UNINITIALIZED_DATA) != 0)
963 {
964 if (bfd_pei_p (abfd))
965 {
966 ps = scnhdr_int->s_size;
967 ss = 0;
968 }
969 else
970 {
971 ps = 0;
972 ss = scnhdr_int->s_size;
973 }
974 }
975 else
976 {
977 if (bfd_pei_p (abfd))
978 ps = scnhdr_int->s_paddr;
979 else
980 ps = 0;
981
982 ss = scnhdr_int->s_size;
983 }
984
985 PUT_SCNHDR_SIZE (abfd, ss,
986 scnhdr_ext->s_size);
987
988 /* s_paddr in PE is really the virtual size. */
989 PUT_SCNHDR_PADDR (abfd, ps, scnhdr_ext->s_paddr);
990
991 PUT_SCNHDR_SCNPTR (abfd, scnhdr_int->s_scnptr,
992 scnhdr_ext->s_scnptr);
993 PUT_SCNHDR_RELPTR (abfd, scnhdr_int->s_relptr,
994 scnhdr_ext->s_relptr);
995 PUT_SCNHDR_LNNOPTR (abfd, scnhdr_int->s_lnnoptr,
996 scnhdr_ext->s_lnnoptr);
997
998 {
999 /* Extra flags must be set when dealing with PE. All sections should also
1000 have the IMAGE_SCN_MEM_READ (0x40000000) flag set. In addition, the
1001 .text section must have IMAGE_SCN_MEM_EXECUTE (0x20000000) and the data
1002 sections (.idata, .data, .bss, .CRT) must have IMAGE_SCN_MEM_WRITE set
1003 (this is especially important when dealing with the .idata section since
1004 the addresses for routines from .dlls must be overwritten). If .reloc
1005 section data is ever generated, we must add IMAGE_SCN_MEM_DISCARDABLE
1006 (0x02000000). Also, the resource data should also be read and
1007 writable. */
1008
1009 /* FIXME: Alignment is also encoded in this field, at least on PPC and
1010 ARM-WINCE. Although - how do we get the original alignment field
1011 back ? */
1012
1013 typedef struct
1014 {
1015 const char * section_name;
1016 unsigned long must_have;
1017 }
1018 pe_required_section_flags;
1019
1020 pe_required_section_flags known_sections [] =
1021 {
1022 { ".arch", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE | IMAGE_SCN_ALIGN_8BYTES },
1023 { ".bss", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1024 { ".data", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1025 { ".edata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1026 { ".idata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1027 { ".pdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1028 { ".rdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1029 { ".reloc", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_DISCARDABLE },
1030 { ".rsrc", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1031 { ".text" , IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE },
1032 { ".tls", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_WRITE },
1033 { ".xdata", IMAGE_SCN_MEM_READ | IMAGE_SCN_CNT_INITIALIZED_DATA },
1034 { NULL, 0}
1035 };
1036
1037 pe_required_section_flags * p;
1038
1039 /* We have defaulted to adding the IMAGE_SCN_MEM_WRITE flag, but now
1040 we know exactly what this specific section wants so we remove it
1041 and then allow the must_have field to add it back in if necessary.
1042 However, we don't remove IMAGE_SCN_MEM_WRITE flag from .text if the
1043 default WP_TEXT file flag has been cleared. WP_TEXT may be cleared
1044 by ld --enable-auto-import (if auto-import is actually needed),
1045 by ld --omagic, or by obcopy --writable-text. */
1046
1047 for (p = known_sections; p->section_name; p++)
1048 if (strcmp (scnhdr_int->s_name, p->section_name) == 0)
1049 {
1050 if (strcmp (scnhdr_int->s_name, ".text")
1051 || (bfd_get_file_flags (abfd) & WP_TEXT))
1052 scnhdr_int->s_flags &= ~IMAGE_SCN_MEM_WRITE;
1053 scnhdr_int->s_flags |= p->must_have;
1054 break;
1055 }
1056
1057 H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags);
1058 }
1059
1060 if (coff_data (abfd)->link_info
1061 && ! coff_data (abfd)->link_info->relocatable
1062 && ! coff_data (abfd)->link_info->shared
1063 && strcmp (scnhdr_int->s_name, ".text") == 0)
1064 {
1065 /* By inference from looking at MS output, the 32 bit field
1066 which is the combination of the number_of_relocs and
1067 number_of_linenos is used for the line number count in
1068 executables. A 16-bit field won't do for cc1. The MS
1069 document says that the number of relocs is zero for
1070 executables, but the 17-th bit has been observed to be there.
1071 Overflow is not an issue: a 4G-line program will overflow a
1072 bunch of other fields long before this! */
1073 H_PUT_16 (abfd, (scnhdr_int->s_nlnno & 0xffff), scnhdr_ext->s_nlnno);
1074 H_PUT_16 (abfd, (scnhdr_int->s_nlnno >> 16), scnhdr_ext->s_nreloc);
1075 }
1076 else
1077 {
1078 if (scnhdr_int->s_nlnno <= 0xffff)
1079 H_PUT_16 (abfd, scnhdr_int->s_nlnno, scnhdr_ext->s_nlnno);
1080 else
1081 {
1082 (*_bfd_error_handler) (_("%s: line number overflow: 0x%lx > 0xffff"),
1083 bfd_get_filename (abfd),
1084 scnhdr_int->s_nlnno);
1085 bfd_set_error (bfd_error_file_truncated);
1086 H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nlnno);
1087 ret = 0;
1088 }
1089
1090 /* Although we could encode 0xffff relocs here, we do not, to be
1091 consistent with other parts of bfd. Also it lets us warn, as
1092 we should never see 0xffff here w/o having the overflow flag
1093 set. */
1094 if (scnhdr_int->s_nreloc < 0xffff)
1095 H_PUT_16 (abfd, scnhdr_int->s_nreloc, scnhdr_ext->s_nreloc);
1096 else
1097 {
1098 /* PE can deal with large #s of relocs, but not here. */
1099 H_PUT_16 (abfd, 0xffff, scnhdr_ext->s_nreloc);
1100 scnhdr_int->s_flags |= IMAGE_SCN_LNK_NRELOC_OVFL;
1101 H_PUT_32 (abfd, scnhdr_int->s_flags, scnhdr_ext->s_flags);
1102 }
1103 }
1104 return ret;
1105 }
1106
1107 void
_bfd_XXi_swap_debugdir_in(bfd * abfd,void * ext1,void * in1)1108 _bfd_XXi_swap_debugdir_in (bfd * abfd, void * ext1, void * in1)
1109 {
1110 struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *) ext1;
1111 struct internal_IMAGE_DEBUG_DIRECTORY *in = (struct internal_IMAGE_DEBUG_DIRECTORY *) in1;
1112
1113 in->Characteristics = H_GET_32(abfd, ext->Characteristics);
1114 in->TimeDateStamp = H_GET_32(abfd, ext->TimeDateStamp);
1115 in->MajorVersion = H_GET_16(abfd, ext->MajorVersion);
1116 in->MinorVersion = H_GET_16(abfd, ext->MinorVersion);
1117 in->Type = H_GET_32(abfd, ext->Type);
1118 in->SizeOfData = H_GET_32(abfd, ext->SizeOfData);
1119 in->AddressOfRawData = H_GET_32(abfd, ext->AddressOfRawData);
1120 in->PointerToRawData = H_GET_32(abfd, ext->PointerToRawData);
1121 }
1122
1123 unsigned int
_bfd_XXi_swap_debugdir_out(bfd * abfd,void * inp,void * extp)1124 _bfd_XXi_swap_debugdir_out (bfd * abfd, void * inp, void * extp)
1125 {
1126 struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *) extp;
1127 struct internal_IMAGE_DEBUG_DIRECTORY *in = (struct internal_IMAGE_DEBUG_DIRECTORY *) inp;
1128
1129 H_PUT_32(abfd, in->Characteristics, ext->Characteristics);
1130 H_PUT_32(abfd, in->TimeDateStamp, ext->TimeDateStamp);
1131 H_PUT_16(abfd, in->MajorVersion, ext->MajorVersion);
1132 H_PUT_16(abfd, in->MinorVersion, ext->MinorVersion);
1133 H_PUT_32(abfd, in->Type, ext->Type);
1134 H_PUT_32(abfd, in->SizeOfData, ext->SizeOfData);
1135 H_PUT_32(abfd, in->AddressOfRawData, ext->AddressOfRawData);
1136 H_PUT_32(abfd, in->PointerToRawData, ext->PointerToRawData);
1137
1138 return sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
1139 }
1140
1141 const char *
_bfd_XXi_get_codeview_pdb_name(bfd * abfd)1142 _bfd_XXi_get_codeview_pdb_name (bfd * abfd)
1143 {
1144 char * filename_ptr = bfd_get_filename(abfd);
1145 char * last_dir_separator = strrchr(filename_ptr, '/');
1146 if (last_dir_separator != NULL) {
1147 filename_ptr = last_dir_separator+1;
1148 }
1149 return filename_ptr;
1150 }
1151
1152 static CODEVIEW_INFO *
_bfd_XXi_slurp_codeview_record(bfd * abfd,file_ptr where,unsigned long length,CODEVIEW_INFO * cvinfo)1153 _bfd_XXi_slurp_codeview_record (bfd * abfd, file_ptr where, unsigned long length, CODEVIEW_INFO *cvinfo)
1154 {
1155
1156 char buffer [length];
1157
1158 if (!cvinfo)
1159 return NULL;
1160
1161 if (bfd_seek (abfd, where, SEEK_SET) != 0)
1162 return NULL;
1163
1164 if (bfd_bread (buffer, length, abfd) < 4)
1165 return NULL;
1166
1167 cvinfo->CVSignature = H_GET_32(abfd, buffer);
1168 cvinfo->Age = 0;
1169
1170 if ((cvinfo->CVSignature == CVINFO_PDB70_CVSIGNATURE)
1171 && (length > sizeof (CV_INFO_PDB70)))
1172 {
1173 CV_INFO_PDB70 *cvinfo70 = (CV_INFO_PDB70 *)(buffer);
1174
1175 cvinfo->Age = H_GET_32(abfd, cvinfo70->Age);
1176
1177 /* A GUID consists of 4,2,2 byte values in little-endian order, followed
1178 by 8 single bytes. Byte swap them so we can conveniently treat the GUID
1179 as 16 bytes in big-endian order. */
1180 bfd_putb32 (bfd_getl32 (cvinfo70->Signature), cvinfo->Signature);
1181 bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[4])), &(cvinfo->Signature[4]));
1182 bfd_putb16 (bfd_getl16 (&(cvinfo70->Signature[6])), &(cvinfo->Signature[6]));
1183 memcpy (&(cvinfo->Signature[8]), &(cvinfo70->Signature[8]), 8);
1184
1185 cvinfo->SignatureLength = CV_INFO_SIGNATURE_LENGTH;
1186 strcpy(cvinfo->PdbFileName, cvinfo70->PdbFileName);
1187
1188 return cvinfo;
1189 }
1190 else if ((cvinfo->CVSignature == CVINFO_PDB20_CVSIGNATURE)
1191 && (length > sizeof (CV_INFO_PDB20)))
1192 {
1193 CV_INFO_PDB20 *cvinfo20 = (CV_INFO_PDB20 *)(buffer);
1194 cvinfo->Age = H_GET_32(abfd, cvinfo20->Age);
1195 memcpy (cvinfo->Signature, cvinfo20->Signature, 4);
1196 cvinfo->SignatureLength = 4;
1197 // cvinfo->PdbFileName = cvinfo20->PdbFileName;
1198
1199 return cvinfo;
1200 }
1201
1202 return NULL;
1203 }
1204
1205 unsigned int
_bfd_XXi_write_codeview_record(bfd * abfd,file_ptr where,CODEVIEW_INFO * cvinfo)1206 _bfd_XXi_write_codeview_record (bfd * abfd, file_ptr where, CODEVIEW_INFO *cvinfo)
1207 {
1208 const char * filename_ptr = _bfd_XXi_get_codeview_pdb_name(abfd);
1209 unsigned int filename_size = strlen(filename_ptr);
1210 unsigned int size = sizeof (CV_INFO_PDB70) + filename_size + 1;
1211 CV_INFO_PDB70 *cvinfo70;
1212 char buffer[size];
1213
1214 if (bfd_seek (abfd, where, SEEK_SET) != 0)
1215 return 0;
1216
1217 cvinfo70 = (CV_INFO_PDB70 *) buffer;
1218 H_PUT_32 (abfd, CVINFO_PDB70_CVSIGNATURE, cvinfo70->CvSignature);
1219
1220 /* Byte swap the GUID from 16 bytes in big-endian order to 4,2,2 byte values
1221 in little-endian order, followed by 8 single bytes. */
1222 bfd_putl32 (bfd_getb32 (cvinfo->Signature), cvinfo70->Signature);
1223 bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[4])), &(cvinfo70->Signature[4]));
1224 bfd_putl16 (bfd_getb16 (&(cvinfo->Signature[6])), &(cvinfo70->Signature[6]));
1225 memcpy (&(cvinfo70->Signature[8]), &(cvinfo->Signature[8]), 8);
1226
1227 H_PUT_32 (abfd, cvinfo->Age, cvinfo70->Age);
1228 strcpy(cvinfo70->PdbFileName, filename_ptr);
1229
1230 if (bfd_bwrite (buffer, size, abfd) != size)
1231 return 0;
1232
1233 return size;
1234 }
1235
1236 static char * dir_names[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] =
1237 {
1238 N_("Export Directory [.edata (or where ever we found it)]"),
1239 N_("Import Directory [parts of .idata]"),
1240 N_("Resource Directory [.rsrc]"),
1241 N_("Exception Directory [.pdata]"),
1242 N_("Security Directory"),
1243 N_("Base Relocation Directory [.reloc]"),
1244 N_("Debug Directory"),
1245 N_("Description Directory"),
1246 N_("Special Directory"),
1247 N_("Thread Storage Directory [.tls]"),
1248 N_("Load Configuration Directory"),
1249 N_("Bound Import Directory"),
1250 N_("Import Address Table Directory"),
1251 N_("Delay Import Directory"),
1252 N_("CLR Runtime Header"),
1253 N_("Reserved")
1254 };
1255
1256 #ifdef POWERPC_LE_PE
1257 /* The code for the PPC really falls in the "architecture dependent"
1258 category. However, it's not clear that anyone will ever care, so
1259 we're ignoring the issue for now; if/when PPC matters, some of this
1260 may need to go into peicode.h, or arguments passed to enable the
1261 PPC- specific code. */
1262 #endif
1263
1264 static bfd_boolean
pe_print_idata(bfd * abfd,void * vfile)1265 pe_print_idata (bfd * abfd, void * vfile)
1266 {
1267 FILE *file = (FILE *) vfile;
1268 bfd_byte *data;
1269 asection *section;
1270 bfd_signed_vma adj;
1271
1272 #ifdef POWERPC_LE_PE
1273 asection *rel_section = bfd_get_section_by_name (abfd, ".reldata");
1274 #endif
1275
1276 bfd_size_type datasize = 0;
1277 bfd_size_type dataoff;
1278 bfd_size_type i;
1279 int onaline = 20;
1280
1281 pe_data_type *pe = pe_data (abfd);
1282 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
1283
1284 bfd_vma addr;
1285
1286 addr = extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress;
1287
1288 if (addr == 0 && extra->DataDirectory[PE_IMPORT_TABLE].Size == 0)
1289 {
1290 /* Maybe the extra header isn't there. Look for the section. */
1291 section = bfd_get_section_by_name (abfd, ".idata");
1292 if (section == NULL)
1293 return TRUE;
1294
1295 addr = section->vma;
1296 datasize = section->size;
1297 if (datasize == 0)
1298 return TRUE;
1299 }
1300 else
1301 {
1302 addr += extra->ImageBase;
1303 for (section = abfd->sections; section != NULL; section = section->next)
1304 {
1305 datasize = section->size;
1306 if (addr >= section->vma && addr < section->vma + datasize)
1307 break;
1308 }
1309
1310 if (section == NULL)
1311 {
1312 fprintf (file,
1313 _("\nThere is an import table, but the section containing it could not be found\n"));
1314 return TRUE;
1315 }
1316 else if (!(section->flags & SEC_HAS_CONTENTS))
1317 {
1318 fprintf (file,
1319 _("\nThere is an import table in %s, but that section has no contents\n"),
1320 section->name);
1321 return TRUE;
1322 }
1323 }
1324
1325 fprintf (file, _("\nThere is an import table in %s at 0x%lx\n"),
1326 section->name, (unsigned long) addr);
1327
1328 dataoff = addr - section->vma;
1329
1330 #ifdef POWERPC_LE_PE
1331 if (rel_section != 0 && rel_section->size != 0)
1332 {
1333 /* The toc address can be found by taking the starting address,
1334 which on the PPC locates a function descriptor. The
1335 descriptor consists of the function code starting address
1336 followed by the address of the toc. The starting address we
1337 get from the bfd, and the descriptor is supposed to be in the
1338 .reldata section. */
1339
1340 bfd_vma loadable_toc_address;
1341 bfd_vma toc_address;
1342 bfd_vma start_address;
1343 bfd_byte *data;
1344 bfd_vma offset;
1345
1346 if (!bfd_malloc_and_get_section (abfd, rel_section, &data))
1347 {
1348 if (data != NULL)
1349 free (data);
1350 return FALSE;
1351 }
1352
1353 offset = abfd->start_address - rel_section->vma;
1354
1355 if (offset >= rel_section->size || offset + 8 > rel_section->size)
1356 {
1357 if (data != NULL)
1358 free (data);
1359 return FALSE;
1360 }
1361
1362 start_address = bfd_get_32 (abfd, data + offset);
1363 loadable_toc_address = bfd_get_32 (abfd, data + offset + 4);
1364 toc_address = loadable_toc_address - 32768;
1365
1366 fprintf (file,
1367 _("\nFunction descriptor located at the start address: %04lx\n"),
1368 (unsigned long int) (abfd->start_address));
1369 fprintf (file,
1370 _("\tcode-base %08lx toc (loadable/actual) %08lx/%08lx\n"),
1371 start_address, loadable_toc_address, toc_address);
1372 if (data != NULL)
1373 free (data);
1374 }
1375 else
1376 {
1377 fprintf (file,
1378 _("\nNo reldata section! Function descriptor not decoded.\n"));
1379 }
1380 #endif
1381
1382 fprintf (file,
1383 _("\nThe Import Tables (interpreted %s section contents)\n"),
1384 section->name);
1385 fprintf (file,
1386 _("\
1387 vma: Hint Time Forward DLL First\n\
1388 Table Stamp Chain Name Thunk\n"));
1389
1390 /* Read the whole section. Some of the fields might be before dataoff. */
1391 if (!bfd_malloc_and_get_section (abfd, section, &data))
1392 {
1393 if (data != NULL)
1394 free (data);
1395 return FALSE;
1396 }
1397
1398 adj = section->vma - extra->ImageBase;
1399
1400 /* Print all image import descriptors. */
1401 for (i = dataoff; i + onaline <= datasize; i += onaline)
1402 {
1403 bfd_vma hint_addr;
1404 bfd_vma time_stamp;
1405 bfd_vma forward_chain;
1406 bfd_vma dll_name;
1407 bfd_vma first_thunk;
1408 int idx = 0;
1409 bfd_size_type j;
1410 char *dll;
1411
1412 /* Print (i + extra->DataDirectory[PE_IMPORT_TABLE].VirtualAddress). */
1413 fprintf (file, " %08lx\t", (unsigned long) (i + adj));
1414 hint_addr = bfd_get_32 (abfd, data + i);
1415 time_stamp = bfd_get_32 (abfd, data + i + 4);
1416 forward_chain = bfd_get_32 (abfd, data + i + 8);
1417 dll_name = bfd_get_32 (abfd, data + i + 12);
1418 first_thunk = bfd_get_32 (abfd, data + i + 16);
1419
1420 fprintf (file, "%08lx %08lx %08lx %08lx %08lx\n",
1421 (unsigned long) hint_addr,
1422 (unsigned long) time_stamp,
1423 (unsigned long) forward_chain,
1424 (unsigned long) dll_name,
1425 (unsigned long) first_thunk);
1426
1427 if (hint_addr == 0 && first_thunk == 0)
1428 break;
1429
1430 if (dll_name - adj >= section->size)
1431 break;
1432
1433 dll = (char *) data + dll_name - adj;
1434 /* PR 17512 file: 078-12277-0.004. */
1435 bfd_size_type maxlen = (char *)(data + datasize) - dll - 1;
1436 fprintf (file, _("\n\tDLL Name: %.*s\n"), (int) maxlen, dll);
1437
1438 if (hint_addr != 0)
1439 {
1440 bfd_byte *ft_data;
1441 asection *ft_section;
1442 bfd_vma ft_addr;
1443 bfd_size_type ft_datasize;
1444 int ft_idx;
1445 int ft_allocated;
1446
1447 fprintf (file, _("\tvma: Hint/Ord Member-Name Bound-To\n"));
1448
1449 idx = hint_addr - adj;
1450
1451 ft_addr = first_thunk + extra->ImageBase;
1452 ft_idx = first_thunk - adj;
1453 ft_data = data + ft_idx;
1454 ft_datasize = datasize - ft_idx;
1455 ft_allocated = 0;
1456
1457 if (first_thunk != hint_addr)
1458 {
1459 /* Find the section which contains the first thunk. */
1460 for (ft_section = abfd->sections;
1461 ft_section != NULL;
1462 ft_section = ft_section->next)
1463 {
1464 if (ft_addr >= ft_section->vma
1465 && ft_addr < ft_section->vma + ft_section->size)
1466 break;
1467 }
1468
1469 if (ft_section == NULL)
1470 {
1471 fprintf (file,
1472 _("\nThere is a first thunk, but the section containing it could not be found\n"));
1473 continue;
1474 }
1475
1476 /* Now check to see if this section is the same as our current
1477 section. If it is not then we will have to load its data in. */
1478 if (ft_section != section)
1479 {
1480 ft_idx = first_thunk - (ft_section->vma - extra->ImageBase);
1481 ft_datasize = ft_section->size - ft_idx;
1482 ft_data = (bfd_byte *) bfd_malloc (ft_datasize);
1483 if (ft_data == NULL)
1484 continue;
1485
1486 /* Read ft_datasize bytes starting at offset ft_idx. */
1487 if (!bfd_get_section_contents (abfd, ft_section, ft_data,
1488 (bfd_vma) ft_idx, ft_datasize))
1489 {
1490 free (ft_data);
1491 continue;
1492 }
1493 ft_allocated = 1;
1494 }
1495 }
1496
1497 /* Print HintName vector entries. */
1498 #ifdef COFF_WITH_pex64
1499 for (j = 0; idx + j + 8 <= datasize; j += 8)
1500 {
1501 bfd_size_type amt;
1502 unsigned long member = bfd_get_32 (abfd, data + idx + j);
1503 unsigned long member_high = bfd_get_32 (abfd, data + idx + j + 4);
1504
1505 if (!member && !member_high)
1506 break;
1507
1508 amt = member - adj;
1509
1510 if (HighBitSet (member_high))
1511 fprintf (file, "\t%lx%08lx\t %4lx%08lx <none>",
1512 member_high, member,
1513 WithoutHighBit (member_high), member);
1514 /* PR binutils/17512: Handle corrupt PE data. */
1515 else if (amt + 2 >= datasize)
1516 fprintf (file, _("\t<corrupt: 0x%04lx>"), member);
1517 else
1518 {
1519 int ordinal;
1520 char *member_name;
1521
1522 ordinal = bfd_get_16 (abfd, data + amt);
1523 member_name = (char *) data + amt + 2;
1524 fprintf (file, "\t%04lx\t %4d %.*s",member, ordinal,
1525 (int) (datasize - (amt + 2)), member_name);
1526 }
1527
1528 /* If the time stamp is not zero, the import address
1529 table holds actual addresses. */
1530 if (time_stamp != 0
1531 && first_thunk != 0
1532 && first_thunk != hint_addr
1533 && j + 4 <= ft_datasize)
1534 fprintf (file, "\t%04lx",
1535 (unsigned long) bfd_get_32 (abfd, ft_data + j));
1536 fprintf (file, "\n");
1537 }
1538 #else
1539 for (j = 0; idx + j + 4 <= datasize; j += 4)
1540 {
1541 bfd_size_type amt;
1542 unsigned long member = bfd_get_32 (abfd, data + idx + j);
1543
1544 /* Print single IMAGE_IMPORT_BY_NAME vector. */
1545 if (member == 0)
1546 break;
1547
1548 amt = member - adj;
1549 if (HighBitSet (member))
1550 fprintf (file, "\t%04lx\t %4lu <none>",
1551 member, WithoutHighBit (member));
1552 /* PR binutils/17512: Handle corrupt PE data. */
1553 else if (amt + 2 >= datasize)
1554 fprintf (file, _("\t<corrupt: 0x%04lx>"), member);
1555 else
1556 {
1557 int ordinal;
1558 char *member_name;
1559
1560 ordinal = bfd_get_16 (abfd, data + amt);
1561 member_name = (char *) data + amt + 2;
1562 fprintf (file, "\t%04lx\t %4d %.*s",
1563 member, ordinal,
1564 (int) (datasize - (amt + 2)), member_name);
1565 }
1566
1567 /* If the time stamp is not zero, the import address
1568 table holds actual addresses. */
1569 if (time_stamp != 0
1570 && first_thunk != 0
1571 && first_thunk != hint_addr
1572 && j + 4 <= ft_datasize)
1573 fprintf (file, "\t%04lx",
1574 (unsigned long) bfd_get_32 (abfd, ft_data + j));
1575
1576 fprintf (file, "\n");
1577 }
1578 #endif
1579 if (ft_allocated)
1580 free (ft_data);
1581 }
1582
1583 fprintf (file, "\n");
1584 }
1585
1586 free (data);
1587
1588 return TRUE;
1589 }
1590
1591 static bfd_boolean
pe_print_edata(bfd * abfd,void * vfile)1592 pe_print_edata (bfd * abfd, void * vfile)
1593 {
1594 FILE *file = (FILE *) vfile;
1595 bfd_byte *data;
1596 asection *section;
1597 bfd_size_type datasize = 0;
1598 bfd_size_type dataoff;
1599 bfd_size_type i;
1600 bfd_vma adj;
1601 struct EDT_type
1602 {
1603 long export_flags; /* Reserved - should be zero. */
1604 long time_stamp;
1605 short major_ver;
1606 short minor_ver;
1607 bfd_vma name; /* RVA - relative to image base. */
1608 long base; /* Ordinal base. */
1609 unsigned long num_functions;/* Number in the export address table. */
1610 unsigned long num_names; /* Number in the name pointer table. */
1611 bfd_vma eat_addr; /* RVA to the export address table. */
1612 bfd_vma npt_addr; /* RVA to the Export Name Pointer Table. */
1613 bfd_vma ot_addr; /* RVA to the Ordinal Table. */
1614 } edt;
1615
1616 pe_data_type *pe = pe_data (abfd);
1617 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
1618
1619 bfd_vma addr;
1620
1621 addr = extra->DataDirectory[PE_EXPORT_TABLE].VirtualAddress;
1622
1623 if (addr == 0 && extra->DataDirectory[PE_EXPORT_TABLE].Size == 0)
1624 {
1625 /* Maybe the extra header isn't there. Look for the section. */
1626 section = bfd_get_section_by_name (abfd, ".edata");
1627 if (section == NULL)
1628 return TRUE;
1629
1630 addr = section->vma;
1631 dataoff = 0;
1632 datasize = section->size;
1633 if (datasize == 0)
1634 return TRUE;
1635 }
1636 else
1637 {
1638 addr += extra->ImageBase;
1639
1640 for (section = abfd->sections; section != NULL; section = section->next)
1641 if (addr >= section->vma && addr < section->vma + section->size)
1642 break;
1643
1644 if (section == NULL)
1645 {
1646 fprintf (file,
1647 _("\nThere is an export table, but the section containing it could not be found\n"));
1648 return TRUE;
1649 }
1650 else if (!(section->flags & SEC_HAS_CONTENTS))
1651 {
1652 fprintf (file,
1653 _("\nThere is an export table in %s, but that section has no contents\n"),
1654 section->name);
1655 return TRUE;
1656 }
1657
1658 dataoff = addr - section->vma;
1659 datasize = extra->DataDirectory[PE_EXPORT_TABLE].Size;
1660 if (datasize > section->size - dataoff)
1661 {
1662 fprintf (file,
1663 _("\nThere is an export table in %s, but it does not fit into that section\n"),
1664 section->name);
1665 return TRUE;
1666 }
1667 }
1668
1669 /* PR 17512: Handle corrupt PE binaries. */
1670 if (datasize < 36)
1671 {
1672 fprintf (file,
1673 _("\nThere is an export table in %s, but it is too small (%d)\n"),
1674 section->name, (int) datasize);
1675 return TRUE;
1676 }
1677
1678 fprintf (file, _("\nThere is an export table in %s at 0x%lx\n"),
1679 section->name, (unsigned long) addr);
1680
1681 data = (bfd_byte *) bfd_malloc (datasize);
1682 if (data == NULL)
1683 return FALSE;
1684
1685 if (! bfd_get_section_contents (abfd, section, data,
1686 (file_ptr) dataoff, datasize))
1687 return FALSE;
1688
1689 /* Go get Export Directory Table. */
1690 edt.export_flags = bfd_get_32 (abfd, data + 0);
1691 edt.time_stamp = bfd_get_32 (abfd, data + 4);
1692 edt.major_ver = bfd_get_16 (abfd, data + 8);
1693 edt.minor_ver = bfd_get_16 (abfd, data + 10);
1694 edt.name = bfd_get_32 (abfd, data + 12);
1695 edt.base = bfd_get_32 (abfd, data + 16);
1696 edt.num_functions = bfd_get_32 (abfd, data + 20);
1697 edt.num_names = bfd_get_32 (abfd, data + 24);
1698 edt.eat_addr = bfd_get_32 (abfd, data + 28);
1699 edt.npt_addr = bfd_get_32 (abfd, data + 32);
1700 edt.ot_addr = bfd_get_32 (abfd, data + 36);
1701
1702 adj = section->vma - extra->ImageBase + dataoff;
1703
1704 /* Dump the EDT first. */
1705 fprintf (file,
1706 _("\nThe Export Tables (interpreted %s section contents)\n\n"),
1707 section->name);
1708
1709 fprintf (file,
1710 _("Export Flags \t\t\t%lx\n"), (unsigned long) edt.export_flags);
1711
1712 fprintf (file,
1713 _("Time/Date stamp \t\t%lx\n"), (unsigned long) edt.time_stamp);
1714
1715 fprintf (file,
1716 _("Major/Minor \t\t\t%d/%d\n"), edt.major_ver, edt.minor_ver);
1717
1718 fprintf (file,
1719 _("Name \t\t\t\t"));
1720 bfd_fprintf_vma (abfd, file, edt.name);
1721
1722 if ((edt.name >= adj) && (edt.name < adj + datasize))
1723 fprintf (file, " %.*s\n",
1724 (int) (datasize - (edt.name - adj)),
1725 data + edt.name - adj);
1726 else
1727 fprintf (file, "(outside .edata section)\n");
1728
1729 fprintf (file,
1730 _("Ordinal Base \t\t\t%ld\n"), edt.base);
1731
1732 fprintf (file,
1733 _("Number in:\n"));
1734
1735 fprintf (file,
1736 _("\tExport Address Table \t\t%08lx\n"),
1737 edt.num_functions);
1738
1739 fprintf (file,
1740 _("\t[Name Pointer/Ordinal] Table\t%08lx\n"), edt.num_names);
1741
1742 fprintf (file,
1743 _("Table Addresses\n"));
1744
1745 fprintf (file,
1746 _("\tExport Address Table \t\t"));
1747 bfd_fprintf_vma (abfd, file, edt.eat_addr);
1748 fprintf (file, "\n");
1749
1750 fprintf (file,
1751 _("\tName Pointer Table \t\t"));
1752 bfd_fprintf_vma (abfd, file, edt.npt_addr);
1753 fprintf (file, "\n");
1754
1755 fprintf (file,
1756 _("\tOrdinal Table \t\t\t"));
1757 bfd_fprintf_vma (abfd, file, edt.ot_addr);
1758 fprintf (file, "\n");
1759
1760 /* The next table to find is the Export Address Table. It's basically
1761 a list of pointers that either locate a function in this dll, or
1762 forward the call to another dll. Something like:
1763 typedef union
1764 {
1765 long export_rva;
1766 long forwarder_rva;
1767 } export_address_table_entry; */
1768
1769 fprintf (file,
1770 _("\nExport Address Table -- Ordinal Base %ld\n"),
1771 edt.base);
1772
1773 /* PR 17512: Handle corrupt PE binaries. */
1774 if (edt.eat_addr + (edt.num_functions * 4) - adj >= datasize
1775 /* PR 17512 file: 140-165018-0.004. */
1776 || data + edt.eat_addr - adj < data)
1777 fprintf (file, _("\tInvalid Export Address Table rva (0x%lx) or entry count (0x%lx)\n"),
1778 (long) edt.eat_addr,
1779 (long) edt.num_functions);
1780 else for (i = 0; i < edt.num_functions; ++i)
1781 {
1782 bfd_vma eat_member = bfd_get_32 (abfd,
1783 data + edt.eat_addr + (i * 4) - adj);
1784 if (eat_member == 0)
1785 continue;
1786
1787 if (eat_member - adj <= datasize)
1788 {
1789 /* This rva is to a name (forwarding function) in our section. */
1790 /* Should locate a function descriptor. */
1791 fprintf (file,
1792 "\t[%4ld] +base[%4ld] %04lx %s -- %.*s\n",
1793 (long) i,
1794 (long) (i + edt.base),
1795 (unsigned long) eat_member,
1796 _("Forwarder RVA"),
1797 (int)(datasize - (eat_member - adj)),
1798 data + eat_member - adj);
1799 }
1800 else
1801 {
1802 /* Should locate a function descriptor in the reldata section. */
1803 fprintf (file,
1804 "\t[%4ld] +base[%4ld] %04lx %s\n",
1805 (long) i,
1806 (long) (i + edt.base),
1807 (unsigned long) eat_member,
1808 _("Export RVA"));
1809 }
1810 }
1811
1812 /* The Export Name Pointer Table is paired with the Export Ordinal Table. */
1813 /* Dump them in parallel for clarity. */
1814 fprintf (file,
1815 _("\n[Ordinal/Name Pointer] Table\n"));
1816
1817 /* PR 17512: Handle corrupt PE binaries. */
1818 if (edt.npt_addr + (edt.num_names * 4) - adj >= datasize
1819 || (data + edt.npt_addr - adj) < data)
1820 fprintf (file, _("\tInvalid Name Pointer Table rva (0x%lx) or entry count (0x%lx)\n"),
1821 (long) edt.npt_addr,
1822 (long) edt.num_names);
1823 /* PR 17512: file: 140-147171-0.004. */
1824 else if (edt.ot_addr + (edt.num_names * 2) - adj >= datasize
1825 || data + edt.ot_addr - adj < data)
1826 fprintf (file, _("\tInvalid Ordinal Table rva (0x%lx) or entry count (0x%lx)\n"),
1827 (long) edt.ot_addr,
1828 (long) edt.num_names);
1829 else for (i = 0; i < edt.num_names; ++i)
1830 {
1831 bfd_vma name_ptr;
1832 bfd_vma ord;
1833
1834 ord = bfd_get_16 (abfd, data + edt.ot_addr + (i * 2) - adj);
1835 name_ptr = bfd_get_32 (abfd, data + edt.npt_addr + (i * 4) - adj);
1836
1837 if ((name_ptr - adj) >= datasize)
1838 {
1839 fprintf (file, _("\t[%4ld] <corrupt offset: %lx>\n"),
1840 (long) ord, (long) name_ptr);
1841 }
1842 else
1843 {
1844 char * name = (char *) data + name_ptr - adj;
1845
1846 fprintf (file, "\t[%4ld] %.*s\n", (long) ord,
1847 (int)((char *)(data + datasize) - name), name);
1848 }
1849 }
1850
1851 free (data);
1852
1853 return TRUE;
1854 }
1855
1856 /* This really is architecture dependent. On IA-64, a .pdata entry
1857 consists of three dwords containing relative virtual addresses that
1858 specify the start and end address of the code range the entry
1859 covers and the address of the corresponding unwind info data.
1860
1861 On ARM and SH-4, a compressed PDATA structure is used :
1862 _IMAGE_CE_RUNTIME_FUNCTION_ENTRY, whereas MIPS is documented to use
1863 _IMAGE_ALPHA_RUNTIME_FUNCTION_ENTRY.
1864 See http://msdn2.microsoft.com/en-us/library/ms253988(VS.80).aspx .
1865
1866 This is the version for uncompressed data. */
1867
1868 static bfd_boolean
pe_print_pdata(bfd * abfd,void * vfile)1869 pe_print_pdata (bfd * abfd, void * vfile)
1870 {
1871 #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
1872 # define PDATA_ROW_SIZE (3 * 8)
1873 #else
1874 # define PDATA_ROW_SIZE (5 * 4)
1875 #endif
1876 FILE *file = (FILE *) vfile;
1877 bfd_byte *data = 0;
1878 asection *section = bfd_get_section_by_name (abfd, ".pdata");
1879 bfd_size_type datasize = 0;
1880 bfd_size_type i;
1881 bfd_size_type start, stop;
1882 int onaline = PDATA_ROW_SIZE;
1883
1884 if (section == NULL
1885 || coff_section_data (abfd, section) == NULL
1886 || pei_section_data (abfd, section) == NULL)
1887 return TRUE;
1888
1889 stop = pei_section_data (abfd, section)->virt_size;
1890 if ((stop % onaline) != 0)
1891 fprintf (file,
1892 _("Warning, .pdata section size (%ld) is not a multiple of %d\n"),
1893 (long) stop, onaline);
1894
1895 fprintf (file,
1896 _("\nThe Function Table (interpreted .pdata section contents)\n"));
1897 #if defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
1898 fprintf (file,
1899 _(" vma:\t\t\tBegin Address End Address Unwind Info\n"));
1900 #else
1901 fprintf (file, _("\
1902 vma:\t\tBegin End EH EH PrologEnd Exception\n\
1903 \t\tAddress Address Handler Data Address Mask\n"));
1904 #endif
1905
1906 datasize = section->size;
1907 if (datasize == 0)
1908 return TRUE;
1909
1910 if (! bfd_malloc_and_get_section (abfd, section, &data))
1911 {
1912 if (data != NULL)
1913 free (data);
1914 return FALSE;
1915 }
1916
1917 start = 0;
1918
1919 for (i = start; i < stop; i += onaline)
1920 {
1921 bfd_vma begin_addr;
1922 bfd_vma end_addr;
1923 bfd_vma eh_handler;
1924 bfd_vma eh_data;
1925 bfd_vma prolog_end_addr;
1926 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
1927 int em_data;
1928 #endif
1929
1930 if (i + PDATA_ROW_SIZE > stop)
1931 break;
1932
1933 begin_addr = GET_PDATA_ENTRY (abfd, data + i );
1934 end_addr = GET_PDATA_ENTRY (abfd, data + i + 4);
1935 eh_handler = GET_PDATA_ENTRY (abfd, data + i + 8);
1936 eh_data = GET_PDATA_ENTRY (abfd, data + i + 12);
1937 prolog_end_addr = GET_PDATA_ENTRY (abfd, data + i + 16);
1938
1939 if (begin_addr == 0 && end_addr == 0 && eh_handler == 0
1940 && eh_data == 0 && prolog_end_addr == 0)
1941 /* We are probably into the padding of the section now. */
1942 break;
1943
1944 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
1945 em_data = ((eh_handler & 0x1) << 2) | (prolog_end_addr & 0x3);
1946 #endif
1947 eh_handler &= ~(bfd_vma) 0x3;
1948 prolog_end_addr &= ~(bfd_vma) 0x3;
1949
1950 fputc (' ', file);
1951 bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
1952 bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
1953 bfd_fprintf_vma (abfd, file, end_addr); fputc (' ', file);
1954 bfd_fprintf_vma (abfd, file, eh_handler);
1955 #if !defined(COFF_WITH_pep) || defined(COFF_WITH_pex64)
1956 fputc (' ', file);
1957 bfd_fprintf_vma (abfd, file, eh_data); fputc (' ', file);
1958 bfd_fprintf_vma (abfd, file, prolog_end_addr);
1959 fprintf (file, " %x", em_data);
1960 #endif
1961
1962 #ifdef POWERPC_LE_PE
1963 if (eh_handler == 0 && eh_data != 0)
1964 {
1965 /* Special bits here, although the meaning may be a little
1966 mysterious. The only one I know for sure is 0x03
1967 Code Significance
1968 0x00 None
1969 0x01 Register Save Millicode
1970 0x02 Register Restore Millicode
1971 0x03 Glue Code Sequence. */
1972 switch (eh_data)
1973 {
1974 case 0x01:
1975 fprintf (file, _(" Register save millicode"));
1976 break;
1977 case 0x02:
1978 fprintf (file, _(" Register restore millicode"));
1979 break;
1980 case 0x03:
1981 fprintf (file, _(" Glue code sequence"));
1982 break;
1983 default:
1984 break;
1985 }
1986 }
1987 #endif
1988 fprintf (file, "\n");
1989 }
1990
1991 free (data);
1992
1993 return TRUE;
1994 #undef PDATA_ROW_SIZE
1995 }
1996
1997 typedef struct sym_cache
1998 {
1999 int symcount;
2000 asymbol ** syms;
2001 } sym_cache;
2002
2003 static asymbol **
slurp_symtab(bfd * abfd,sym_cache * psc)2004 slurp_symtab (bfd *abfd, sym_cache *psc)
2005 {
2006 asymbol ** sy = NULL;
2007 long storage;
2008
2009 if (!(bfd_get_file_flags (abfd) & HAS_SYMS))
2010 {
2011 psc->symcount = 0;
2012 return NULL;
2013 }
2014
2015 storage = bfd_get_symtab_upper_bound (abfd);
2016 if (storage < 0)
2017 return NULL;
2018 if (storage)
2019 sy = (asymbol **) bfd_malloc (storage);
2020
2021 psc->symcount = bfd_canonicalize_symtab (abfd, sy);
2022 if (psc->symcount < 0)
2023 return NULL;
2024 return sy;
2025 }
2026
2027 static const char *
my_symbol_for_address(bfd * abfd,bfd_vma func,sym_cache * psc)2028 my_symbol_for_address (bfd *abfd, bfd_vma func, sym_cache *psc)
2029 {
2030 int i;
2031
2032 if (psc->syms == 0)
2033 psc->syms = slurp_symtab (abfd, psc);
2034
2035 for (i = 0; i < psc->symcount; i++)
2036 {
2037 if (psc->syms[i]->section->vma + psc->syms[i]->value == func)
2038 return psc->syms[i]->name;
2039 }
2040
2041 return NULL;
2042 }
2043
2044 static void
cleanup_syms(sym_cache * psc)2045 cleanup_syms (sym_cache *psc)
2046 {
2047 psc->symcount = 0;
2048 free (psc->syms);
2049 psc->syms = NULL;
2050 }
2051
2052 /* This is the version for "compressed" pdata. */
2053
2054 bfd_boolean
_bfd_XX_print_ce_compressed_pdata(bfd * abfd,void * vfile)2055 _bfd_XX_print_ce_compressed_pdata (bfd * abfd, void * vfile)
2056 {
2057 # define PDATA_ROW_SIZE (2 * 4)
2058 FILE *file = (FILE *) vfile;
2059 bfd_byte *data = NULL;
2060 asection *section = bfd_get_section_by_name (abfd, ".pdata");
2061 bfd_size_type datasize = 0;
2062 bfd_size_type i;
2063 bfd_size_type start, stop;
2064 int onaline = PDATA_ROW_SIZE;
2065 struct sym_cache cache = {0, 0} ;
2066
2067 if (section == NULL
2068 || coff_section_data (abfd, section) == NULL
2069 || pei_section_data (abfd, section) == NULL)
2070 return TRUE;
2071
2072 stop = pei_section_data (abfd, section)->virt_size;
2073 if ((stop % onaline) != 0)
2074 fprintf (file,
2075 _("Warning, .pdata section size (%ld) is not a multiple of %d\n"),
2076 (long) stop, onaline);
2077
2078 fprintf (file,
2079 _("\nThe Function Table (interpreted .pdata section contents)\n"));
2080
2081 fprintf (file, _("\
2082 vma:\t\tBegin Prolog Function Flags Exception EH\n\
2083 \t\tAddress Length Length 32b exc Handler Data\n"));
2084
2085 datasize = section->size;
2086 if (datasize == 0)
2087 return TRUE;
2088
2089 if (! bfd_malloc_and_get_section (abfd, section, &data))
2090 {
2091 if (data != NULL)
2092 free (data);
2093 return FALSE;
2094 }
2095
2096 start = 0;
2097
2098 for (i = start; i < stop; i += onaline)
2099 {
2100 bfd_vma begin_addr;
2101 bfd_vma other_data;
2102 bfd_vma prolog_length, function_length;
2103 int flag32bit, exception_flag;
2104 asection *tsection;
2105
2106 if (i + PDATA_ROW_SIZE > stop)
2107 break;
2108
2109 begin_addr = GET_PDATA_ENTRY (abfd, data + i );
2110 other_data = GET_PDATA_ENTRY (abfd, data + i + 4);
2111
2112 if (begin_addr == 0 && other_data == 0)
2113 /* We are probably into the padding of the section now. */
2114 break;
2115
2116 prolog_length = (other_data & 0x000000FF);
2117 function_length = (other_data & 0x3FFFFF00) >> 8;
2118 flag32bit = (int)((other_data & 0x40000000) >> 30);
2119 exception_flag = (int)((other_data & 0x80000000) >> 31);
2120
2121 fputc (' ', file);
2122 bfd_fprintf_vma (abfd, file, i + section->vma); fputc ('\t', file);
2123 bfd_fprintf_vma (abfd, file, begin_addr); fputc (' ', file);
2124 bfd_fprintf_vma (abfd, file, prolog_length); fputc (' ', file);
2125 bfd_fprintf_vma (abfd, file, function_length); fputc (' ', file);
2126 fprintf (file, "%2d %2d ", flag32bit, exception_flag);
2127
2128 /* Get the exception handler's address and the data passed from the
2129 .text section. This is really the data that belongs with the .pdata
2130 but got "compressed" out for the ARM and SH4 architectures. */
2131 tsection = bfd_get_section_by_name (abfd, ".text");
2132 if (tsection && coff_section_data (abfd, tsection)
2133 && pei_section_data (abfd, tsection))
2134 {
2135 bfd_vma eh_off = (begin_addr - 8) - tsection->vma;
2136 bfd_byte *tdata;
2137
2138 tdata = (bfd_byte *) bfd_malloc (8);
2139 if (tdata)
2140 {
2141 if (bfd_get_section_contents (abfd, tsection, tdata, eh_off, 8))
2142 {
2143 bfd_vma eh, eh_data;
2144
2145 eh = bfd_get_32 (abfd, tdata);
2146 eh_data = bfd_get_32 (abfd, tdata + 4);
2147 fprintf (file, "%08x ", (unsigned int) eh);
2148 fprintf (file, "%08x", (unsigned int) eh_data);
2149 if (eh != 0)
2150 {
2151 const char *s = my_symbol_for_address (abfd, eh, &cache);
2152
2153 if (s)
2154 fprintf (file, " (%s) ", s);
2155 }
2156 }
2157 free (tdata);
2158 }
2159 }
2160
2161 fprintf (file, "\n");
2162 }
2163
2164 free (data);
2165
2166 cleanup_syms (& cache);
2167
2168 return TRUE;
2169 #undef PDATA_ROW_SIZE
2170 }
2171
2172
2173 #define IMAGE_REL_BASED_HIGHADJ 4
2174 static const char * const tbl[] =
2175 {
2176 "ABSOLUTE",
2177 "HIGH",
2178 "LOW",
2179 "HIGHLOW",
2180 "HIGHADJ",
2181 "MIPS_JMPADDR",
2182 "SECTION",
2183 "REL32",
2184 "RESERVED1",
2185 "MIPS_JMPADDR16",
2186 "DIR64",
2187 "HIGH3ADJ",
2188 "UNKNOWN", /* MUST be last. */
2189 };
2190
2191 static bfd_boolean
pe_print_reloc(bfd * abfd,void * vfile)2192 pe_print_reloc (bfd * abfd, void * vfile)
2193 {
2194 FILE *file = (FILE *) vfile;
2195 bfd_byte *data = 0;
2196 asection *section = bfd_get_section_by_name (abfd, ".reloc");
2197 bfd_byte *p, *end;
2198
2199 if (section == NULL || section->size == 0 || !(section->flags & SEC_HAS_CONTENTS))
2200 return TRUE;
2201
2202 fprintf (file,
2203 _("\n\nPE File Base Relocations (interpreted .reloc section contents)\n"));
2204
2205 if (! bfd_malloc_and_get_section (abfd, section, &data))
2206 {
2207 if (data != NULL)
2208 free (data);
2209 return FALSE;
2210 }
2211
2212 p = data;
2213 end = data + section->size;
2214 while (p + 8 <= end)
2215 {
2216 int j;
2217 bfd_vma virtual_address;
2218 long number, size;
2219 bfd_byte *chunk_end;
2220
2221 /* The .reloc section is a sequence of blocks, with a header consisting
2222 of two 32 bit quantities, followed by a number of 16 bit entries. */
2223 virtual_address = bfd_get_32 (abfd, p);
2224 size = bfd_get_32 (abfd, p + 4);
2225 p += 8;
2226 number = (size - 8) / 2;
2227
2228 if (size == 0)
2229 break;
2230
2231 fprintf (file,
2232 _("\nVirtual Address: %08lx Chunk size %ld (0x%lx) Number of fixups %ld\n"),
2233 (unsigned long) virtual_address, size, (unsigned long) size, number);
2234
2235 chunk_end = p + size;
2236 if (chunk_end > end)
2237 chunk_end = end;
2238 j = 0;
2239 while (p + 2 <= chunk_end)
2240 {
2241 unsigned short e = bfd_get_16 (abfd, p);
2242 unsigned int t = (e & 0xF000) >> 12;
2243 int off = e & 0x0FFF;
2244
2245 if (t >= sizeof (tbl) / sizeof (tbl[0]))
2246 t = (sizeof (tbl) / sizeof (tbl[0])) - 1;
2247
2248 fprintf (file,
2249 _("\treloc %4d offset %4x [%4lx] %s"),
2250 j, off, (unsigned long) (off + virtual_address), tbl[t]);
2251
2252 p += 2;
2253 j++;
2254
2255 /* HIGHADJ takes an argument, - the next record *is* the
2256 low 16 bits of addend. */
2257 if (t == IMAGE_REL_BASED_HIGHADJ && p + 2 <= chunk_end)
2258 {
2259 fprintf (file, " (%4x)", (unsigned int) bfd_get_16 (abfd, p));
2260 p += 2;
2261 j++;
2262 }
2263
2264 fprintf (file, "\n");
2265 }
2266 }
2267
2268 free (data);
2269
2270 return TRUE;
2271 }
2272
2273 /* A data structure describing the regions of a .rsrc section.
2274 Some fields are filled in as the section is parsed. */
2275
2276 typedef struct rsrc_regions
2277 {
2278 bfd_byte * section_start;
2279 bfd_byte * section_end;
2280 bfd_byte * strings_start;
2281 bfd_byte * resource_start;
2282 } rsrc_regions;
2283
2284 static bfd_byte *
2285 rsrc_print_resource_directory (FILE * , bfd *, unsigned int, bfd_byte *,
2286 rsrc_regions *, bfd_vma);
2287
2288 /* Print the resource entry at DATA, with the text indented by INDENT.
2289 Recusively calls rsrc_print_resource_directory to print the contents
2290 of directory entries.
2291 Returns the address of the end of the data associated with the entry
2292 or section_end + 1 upon failure. */
2293
2294 static bfd_byte *
rsrc_print_resource_entries(FILE * file,bfd * abfd,unsigned int indent,bfd_boolean is_name,bfd_byte * data,rsrc_regions * regions,bfd_vma rva_bias)2295 rsrc_print_resource_entries (FILE * file,
2296 bfd * abfd,
2297 unsigned int indent,
2298 bfd_boolean is_name,
2299 bfd_byte * data,
2300 rsrc_regions * regions,
2301 bfd_vma rva_bias)
2302 {
2303 unsigned long entry, addr, size;
2304
2305 if (data + 8 >= regions->section_end)
2306 return regions->section_end + 1;
2307
2308 fprintf (file, _("%03x %*.s Entry: "), (int)(data - regions->section_start), indent, " ");
2309
2310 entry = (unsigned long) bfd_get_32 (abfd, data);
2311 if (is_name)
2312 {
2313 bfd_byte * name;
2314
2315 /* Note - the documentation says that this field is an RVA value
2316 but windres appears to produce a section relative offset with
2317 the top bit set. Support both styles for now. */
2318 if (HighBitSet (entry))
2319 name = regions->section_start + WithoutHighBit (entry);
2320 else
2321 name = regions->section_start + entry - rva_bias;
2322
2323 if (name + 2 < regions->section_end && name > regions->section_start)
2324 {
2325 unsigned int len;
2326
2327 if (regions->strings_start == NULL)
2328 regions->strings_start = name;
2329
2330 len = bfd_get_16 (abfd, name);
2331
2332 fprintf (file, _("name: [val: %08lx len %d]: "), entry, len);
2333
2334 if (name + 2 + len * 2 < regions->section_end)
2335 {
2336 /* This strange loop is to cope with multibyte characters. */
2337 while (len --)
2338 {
2339 char c;
2340
2341 name += 2;
2342 c = * name;
2343 /* Avoid printing control characters. */
2344 if (c > 0 && c < 32)
2345 fprintf (file, "^%c", c + 64);
2346 else
2347 fprintf (file, "%.1s", name);
2348 }
2349 }
2350 else
2351 {
2352 fprintf (file, _("<corrupt string length: %#x>\n"), len);
2353 /* PR binutils/17512: Do not try to continue decoding a
2354 corrupted resource section. It is likely to end up with
2355 reams of extraneous output. FIXME: We could probably
2356 continue if we disable the printing of strings... */
2357 return regions->section_end + 1;
2358 }
2359 }
2360 else
2361 {
2362 fprintf (file, _("<corrupt string offset: %#lx>\n"), entry);
2363 return regions->section_end + 1;
2364 }
2365 }
2366 else
2367 fprintf (file, _("ID: %#08lx"), entry);
2368
2369 entry = (long) bfd_get_32 (abfd, data + 4);
2370 fprintf (file, _(", Value: %#08lx\n"), entry);
2371
2372 if (HighBitSet (entry))
2373 {
2374 data = regions->section_start + WithoutHighBit (entry);
2375 if (data <= regions->section_start || data > regions->section_end)
2376 return regions->section_end + 1;
2377
2378 /* FIXME: PR binutils/17512: A corrupt file could contain a loop
2379 in the resource table. We need some way to detect this. */
2380 return rsrc_print_resource_directory (file, abfd, indent + 1, data,
2381 regions, rva_bias);
2382 }
2383
2384 if (regions->section_start + entry + 16 >= regions->section_end)
2385 return regions->section_end + 1;
2386
2387 fprintf (file, _("%03x %*.s Leaf: Addr: %#08lx, Size: %#08lx, Codepage: %d\n"),
2388 (int) (entry),
2389 indent, " ",
2390 addr = (long) bfd_get_32 (abfd, regions->section_start + entry),
2391 size = (long) bfd_get_32 (abfd, regions->section_start + entry + 4),
2392 (int) bfd_get_32 (abfd, regions->section_start + entry + 8));
2393
2394 /* Check that the reserved entry is 0. */
2395 if (bfd_get_32 (abfd, regions->section_start + entry + 12) != 0
2396 /* And that the data address/size is valid too. */
2397 || (regions->section_start + (addr - rva_bias) + size > regions->section_end))
2398 return regions->section_end + 1;
2399
2400 if (regions->resource_start == NULL)
2401 regions->resource_start = regions->section_start + (addr - rva_bias);
2402
2403 return regions->section_start + (addr - rva_bias) + size;
2404 }
2405
2406 #define max(a,b) ((a) > (b) ? (a) : (b))
2407 #define min(a,b) ((a) < (b) ? (a) : (b))
2408
2409 static bfd_byte *
rsrc_print_resource_directory(FILE * file,bfd * abfd,unsigned int indent,bfd_byte * data,rsrc_regions * regions,bfd_vma rva_bias)2410 rsrc_print_resource_directory (FILE * file,
2411 bfd * abfd,
2412 unsigned int indent,
2413 bfd_byte * data,
2414 rsrc_regions * regions,
2415 bfd_vma rva_bias)
2416 {
2417 unsigned int num_names, num_ids;
2418 bfd_byte * highest_data = data;
2419
2420 if (data + 16 >= regions->section_end)
2421 return regions->section_end + 1;
2422
2423 fprintf (file, "%03x %*.s ", (int)(data - regions->section_start), indent, " ");
2424 switch (indent)
2425 {
2426 case 0: fprintf (file, "Type"); break;
2427 case 2: fprintf (file, "Name"); break;
2428 case 4: fprintf (file, "Language"); break;
2429 default:
2430 fprintf (file, _("<unknown directory type: %d>\n"), indent);
2431 /* FIXME: For now we end the printing here. If in the
2432 future more directory types are added to the RSRC spec
2433 then we will need to change this. */
2434 return regions->section_end + 1;
2435 }
2436
2437 fprintf (file, _(" Table: Char: %d, Time: %08lx, Ver: %d/%d, Num Names: %d, IDs: %d\n"),
2438 (int) bfd_get_32 (abfd, data),
2439 (long) bfd_get_32 (abfd, data + 4),
2440 (int) bfd_get_16 (abfd, data + 8),
2441 (int) bfd_get_16 (abfd, data + 10),
2442 num_names = (int) bfd_get_16 (abfd, data + 12),
2443 num_ids = (int) bfd_get_16 (abfd, data + 14));
2444 data += 16;
2445
2446 while (num_names --)
2447 {
2448 bfd_byte * entry_end;
2449
2450 entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, TRUE,
2451 data, regions, rva_bias);
2452 data += 8;
2453 highest_data = max (highest_data, entry_end);
2454 if (entry_end >= regions->section_end)
2455 return entry_end;
2456 }
2457
2458 while (num_ids --)
2459 {
2460 bfd_byte * entry_end;
2461
2462 entry_end = rsrc_print_resource_entries (file, abfd, indent + 1, FALSE,
2463 data, regions, rva_bias);
2464 data += 8;
2465 highest_data = max (highest_data, entry_end);
2466 if (entry_end >= regions->section_end)
2467 return entry_end;
2468 }
2469
2470 return max (highest_data, data);
2471 }
2472
2473 /* Display the contents of a .rsrc section. We do not try to
2474 reproduce the resources, windres does that. Instead we dump
2475 the tables in a human readable format. */
2476
2477 static bfd_boolean
rsrc_print_section(bfd * abfd,void * vfile)2478 rsrc_print_section (bfd * abfd, void * vfile)
2479 {
2480 bfd_vma rva_bias;
2481 pe_data_type * pe;
2482 FILE * file = (FILE *) vfile;
2483 bfd_size_type datasize;
2484 asection * section;
2485 bfd_byte * data;
2486 rsrc_regions regions;
2487
2488 pe = pe_data (abfd);
2489 if (pe == NULL)
2490 return TRUE;
2491
2492 section = bfd_get_section_by_name (abfd, ".rsrc");
2493 if (section == NULL)
2494 return TRUE;
2495 if (!(section->flags & SEC_HAS_CONTENTS))
2496 return TRUE;
2497
2498 datasize = section->size;
2499 if (datasize == 0)
2500 return TRUE;
2501
2502 rva_bias = section->vma - pe->pe_opthdr.ImageBase;
2503
2504 if (! bfd_malloc_and_get_section (abfd, section, & data))
2505 {
2506 if (data != NULL)
2507 free (data);
2508 return FALSE;
2509 }
2510
2511 regions.section_start = data;
2512 regions.section_end = data + datasize;
2513 regions.strings_start = NULL;
2514 regions.resource_start = NULL;
2515
2516 fflush (file);
2517 fprintf (file, "\nThe .rsrc Resource Directory section:\n");
2518
2519 while (data < regions.section_end)
2520 {
2521 bfd_byte * p = data;
2522
2523 data = rsrc_print_resource_directory (file, abfd, 0, data, & regions, rva_bias);
2524
2525 if (data == regions.section_end + 1)
2526 fprintf (file, _("Corrupt .rsrc section detected!\n"));
2527 else
2528 {
2529 /* Align data before continuing. */
2530 int align = (1 << section->alignment_power) - 1;
2531
2532 data = (bfd_byte *) (((ptrdiff_t) (data + align)) & ~ align);
2533 rva_bias += data - p;
2534
2535 /* For reasons that are unclear .rsrc sections are sometimes created
2536 aligned to a 1^3 boundary even when their alignment is set at
2537 1^2. Catch that case here before we issue a spurious warning
2538 message. */
2539 if (data == (regions.section_end - 4))
2540 data = regions.section_end;
2541 else if (data < regions.section_end)
2542 {
2543 /* If the extra data is all zeros then do not complain.
2544 This is just padding so that the section meets the
2545 page size requirements. */
2546 while (data ++ < regions.section_end)
2547 if (*data != 0)
2548 break;
2549 if (data < regions.section_end)
2550 fprintf (file, _("\nWARNING: Extra data in .rsrc section - it will be ignored by Windows:\n"));
2551 }
2552 }
2553 }
2554
2555 if (regions.strings_start != NULL)
2556 fprintf (file, " String table starts at offset: %#03x\n",
2557 (int) (regions.strings_start - regions.section_start));
2558 if (regions.resource_start != NULL)
2559 fprintf (file, " Resources start at offset: %#03x\n",
2560 (int) (regions.resource_start - regions.section_start));
2561
2562 free (regions.section_start);
2563 return TRUE;
2564 }
2565
2566 #define IMAGE_NUMBEROF_DEBUG_TYPES 12
2567
2568 static char * debug_type_names[IMAGE_NUMBEROF_DEBUG_TYPES] =
2569 {
2570 "Unknown",
2571 "COFF",
2572 "CodeView",
2573 "FPO",
2574 "Misc",
2575 "Exception",
2576 "Fixup",
2577 "OMAP-to-SRC",
2578 "OMAP-from-SRC",
2579 "Borland",
2580 "Reserved",
2581 "CLSID",
2582 };
2583
2584 static bfd_boolean
pe_print_debugdata(bfd * abfd,void * vfile)2585 pe_print_debugdata (bfd * abfd, void * vfile)
2586 {
2587 FILE *file = (FILE *) vfile;
2588 pe_data_type *pe = pe_data (abfd);
2589 struct internal_extra_pe_aouthdr *extra = &pe->pe_opthdr;
2590 asection *section;
2591 bfd_byte *data = 0;
2592 bfd_size_type dataoff;
2593 unsigned int i;
2594
2595 bfd_vma addr = extra->DataDirectory[PE_DEBUG_DATA].VirtualAddress;
2596 bfd_size_type size = extra->DataDirectory[PE_DEBUG_DATA].Size;
2597
2598 if (size == 0)
2599 return TRUE;
2600
2601 addr += extra->ImageBase;
2602 for (section = abfd->sections; section != NULL; section = section->next)
2603 {
2604 if ((addr >= section->vma) && (addr < (section->vma + section->size)))
2605 break;
2606 }
2607
2608 if (section == NULL)
2609 {
2610 fprintf (file,
2611 _("\nThere is a debug directory, but the section containing it could not be found\n"));
2612 return TRUE;
2613 }
2614 else if (!(section->flags & SEC_HAS_CONTENTS))
2615 {
2616 fprintf (file,
2617 _("\nThere is a debug directory in %s, but that section has no contents\n"),
2618 section->name);
2619 return TRUE;
2620 }
2621 else if (section->size < size)
2622 {
2623 fprintf (file,
2624 _("\nError: section %s contains the debug data starting address but it is too small\n"),
2625 section->name);
2626 return FALSE;
2627 }
2628
2629 fprintf (file, _("\nThere is a debug directory in %s at 0x%lx\n\n"),
2630 section->name, (unsigned long) addr);
2631
2632 dataoff = addr - section->vma;
2633
2634 if (size > (section->size - dataoff))
2635 {
2636 fprintf (file, _("The debug data size field in the data directory is too big for the section"));
2637 return FALSE;
2638 }
2639
2640 fprintf (file,
2641 _("Type Size Rva Offset\n"));
2642
2643 /* Read the whole section. */
2644 if (!bfd_malloc_and_get_section (abfd, section, &data))
2645 {
2646 if (data != NULL)
2647 free (data);
2648 return FALSE;
2649 }
2650
2651 for (i = 0; i < size / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
2652 {
2653 const char *type_name;
2654 struct external_IMAGE_DEBUG_DIRECTORY *ext
2655 = &((struct external_IMAGE_DEBUG_DIRECTORY *)(data + dataoff))[i];
2656 struct internal_IMAGE_DEBUG_DIRECTORY idd;
2657
2658 _bfd_XXi_swap_debugdir_in (abfd, ext, &idd);
2659
2660 if ((idd.Type) >= IMAGE_NUMBEROF_DEBUG_TYPES)
2661 type_name = debug_type_names[0];
2662 else
2663 type_name = debug_type_names[idd.Type];
2664
2665 fprintf (file, " %2ld %14s %08lx %08lx %08lx\n",
2666 idd.Type, type_name, idd.SizeOfData,
2667 idd.AddressOfRawData, idd.PointerToRawData);
2668
2669 if (idd.Type == PE_IMAGE_DEBUG_TYPE_CODEVIEW)
2670 {
2671 char signature[CV_INFO_SIGNATURE_LENGTH * 2 + 1];
2672 char buffer [idd.SizeOfData];
2673 CODEVIEW_INFO * cvinfo = (CODEVIEW_INFO *) buffer;
2674
2675 /* The debug entry doesn't have to have to be in a section,
2676 in which case AddressOfRawData is 0, so always use PointerToRawData. */
2677 if (!_bfd_XXi_slurp_codeview_record (abfd, (file_ptr) idd.PointerToRawData,
2678 idd.SizeOfData, cvinfo))
2679 continue;
2680
2681 for (i = 0; i < cvinfo->SignatureLength; i++)
2682 sprintf (&signature[i*2], "%02x", cvinfo->Signature[i] & 0xff);
2683
2684 fprintf (file, "(format %c%c%c%c signature %s age %ld pdb %s)\n",
2685 buffer[0], buffer[1], buffer[2], buffer[3],
2686 signature, cvinfo->Age, cvinfo->PdbFileName);
2687 }
2688 }
2689
2690 if (size % sizeof (struct external_IMAGE_DEBUG_DIRECTORY) != 0)
2691 fprintf (file,
2692 _("The debug directory size is not a multiple of the debug directory entry size\n"));
2693
2694 return TRUE;
2695 }
2696
2697 /* Print out the program headers. */
2698
2699 bfd_boolean
_bfd_XX_print_private_bfd_data_common(bfd * abfd,void * vfile)2700 _bfd_XX_print_private_bfd_data_common (bfd * abfd, void * vfile)
2701 {
2702 FILE *file = (FILE *) vfile;
2703 int j;
2704 pe_data_type *pe = pe_data (abfd);
2705 struct internal_extra_pe_aouthdr *i = &pe->pe_opthdr;
2706 const char *subsystem_name = NULL;
2707 const char *name;
2708
2709 /* The MS dumpbin program reportedly ands with 0xff0f before
2710 printing the characteristics field. Not sure why. No reason to
2711 emulate it here. */
2712 fprintf (file, _("\nCharacteristics 0x%x\n"), pe->real_flags);
2713 #undef PF
2714 #define PF(x, y) if (pe->real_flags & x) { fprintf (file, "\t%s\n", y); }
2715 PF (IMAGE_FILE_RELOCS_STRIPPED, "relocations stripped");
2716 PF (IMAGE_FILE_EXECUTABLE_IMAGE, "executable");
2717 PF (IMAGE_FILE_LINE_NUMS_STRIPPED, "line numbers stripped");
2718 PF (IMAGE_FILE_LOCAL_SYMS_STRIPPED, "symbols stripped");
2719 PF (IMAGE_FILE_LARGE_ADDRESS_AWARE, "large address aware");
2720 PF (IMAGE_FILE_BYTES_REVERSED_LO, "little endian");
2721 PF (IMAGE_FILE_32BIT_MACHINE, "32 bit words");
2722 PF (IMAGE_FILE_DEBUG_STRIPPED, "debugging information removed");
2723 PF (IMAGE_FILE_SYSTEM, "system file");
2724 PF (IMAGE_FILE_DLL, "DLL");
2725 PF (IMAGE_FILE_BYTES_REVERSED_HI, "big endian");
2726 #undef PF
2727
2728 /* ctime implies '\n'. */
2729 {
2730 time_t t = pe->coff.timestamp;
2731 fprintf (file, "\nTime/Date\t\t%s", ctime (&t));
2732 }
2733
2734 #ifndef IMAGE_NT_OPTIONAL_HDR_MAGIC
2735 # define IMAGE_NT_OPTIONAL_HDR_MAGIC 0x10b
2736 #endif
2737 #ifndef IMAGE_NT_OPTIONAL_HDR64_MAGIC
2738 # define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b
2739 #endif
2740 #ifndef IMAGE_NT_OPTIONAL_HDRROM_MAGIC
2741 # define IMAGE_NT_OPTIONAL_HDRROM_MAGIC 0x107
2742 #endif
2743
2744 switch (i->Magic)
2745 {
2746 case IMAGE_NT_OPTIONAL_HDR_MAGIC:
2747 name = "PE32";
2748 break;
2749 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
2750 name = "PE32+";
2751 break;
2752 case IMAGE_NT_OPTIONAL_HDRROM_MAGIC:
2753 name = "ROM";
2754 break;
2755 default:
2756 name = NULL;
2757 break;
2758 }
2759 fprintf (file, "Magic\t\t\t%04x", i->Magic);
2760 if (name)
2761 fprintf (file, "\t(%s)",name);
2762 fprintf (file, "\nMajorLinkerVersion\t%d\n", i->MajorLinkerVersion);
2763 fprintf (file, "MinorLinkerVersion\t%d\n", i->MinorLinkerVersion);
2764 fprintf (file, "SizeOfCode\t\t%08lx\n", (unsigned long) i->SizeOfCode);
2765 fprintf (file, "SizeOfInitializedData\t%08lx\n",
2766 (unsigned long) i->SizeOfInitializedData);
2767 fprintf (file, "SizeOfUninitializedData\t%08lx\n",
2768 (unsigned long) i->SizeOfUninitializedData);
2769 fprintf (file, "AddressOfEntryPoint\t");
2770 bfd_fprintf_vma (abfd, file, i->AddressOfEntryPoint);
2771 fprintf (file, "\nBaseOfCode\t\t");
2772 bfd_fprintf_vma (abfd, file, i->BaseOfCode);
2773 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
2774 /* PE32+ does not have BaseOfData member! */
2775 fprintf (file, "\nBaseOfData\t\t");
2776 bfd_fprintf_vma (abfd, file, i->BaseOfData);
2777 #endif
2778
2779 fprintf (file, "\nImageBase\t\t");
2780 bfd_fprintf_vma (abfd, file, i->ImageBase);
2781 fprintf (file, "\nSectionAlignment\t");
2782 bfd_fprintf_vma (abfd, file, i->SectionAlignment);
2783 fprintf (file, "\nFileAlignment\t\t");
2784 bfd_fprintf_vma (abfd, file, i->FileAlignment);
2785 fprintf (file, "\nMajorOSystemVersion\t%d\n", i->MajorOperatingSystemVersion);
2786 fprintf (file, "MinorOSystemVersion\t%d\n", i->MinorOperatingSystemVersion);
2787 fprintf (file, "MajorImageVersion\t%d\n", i->MajorImageVersion);
2788 fprintf (file, "MinorImageVersion\t%d\n", i->MinorImageVersion);
2789 fprintf (file, "MajorSubsystemVersion\t%d\n", i->MajorSubsystemVersion);
2790 fprintf (file, "MinorSubsystemVersion\t%d\n", i->MinorSubsystemVersion);
2791 fprintf (file, "Win32Version\t\t%08lx\n", (unsigned long) i->Reserved1);
2792 fprintf (file, "SizeOfImage\t\t%08lx\n", (unsigned long) i->SizeOfImage);
2793 fprintf (file, "SizeOfHeaders\t\t%08lx\n", (unsigned long) i->SizeOfHeaders);
2794 fprintf (file, "CheckSum\t\t%08lx\n", (unsigned long) i->CheckSum);
2795
2796 switch (i->Subsystem)
2797 {
2798 case IMAGE_SUBSYSTEM_UNKNOWN:
2799 subsystem_name = "unspecified";
2800 break;
2801 case IMAGE_SUBSYSTEM_NATIVE:
2802 subsystem_name = "NT native";
2803 break;
2804 case IMAGE_SUBSYSTEM_WINDOWS_GUI:
2805 subsystem_name = "Windows GUI";
2806 break;
2807 case IMAGE_SUBSYSTEM_WINDOWS_CUI:
2808 subsystem_name = "Windows CUI";
2809 break;
2810 case IMAGE_SUBSYSTEM_POSIX_CUI:
2811 subsystem_name = "POSIX CUI";
2812 break;
2813 case IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
2814 subsystem_name = "Wince CUI";
2815 break;
2816 // These are from UEFI Platform Initialization Specification 1.1.
2817 case IMAGE_SUBSYSTEM_EFI_APPLICATION:
2818 subsystem_name = "EFI application";
2819 break;
2820 case IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
2821 subsystem_name = "EFI boot service driver";
2822 break;
2823 case IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
2824 subsystem_name = "EFI runtime driver";
2825 break;
2826 case IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER:
2827 subsystem_name = "SAL runtime driver";
2828 break;
2829 // This is from revision 8.0 of the MS PE/COFF spec
2830 case IMAGE_SUBSYSTEM_XBOX:
2831 subsystem_name = "XBOX";
2832 break;
2833 // Added default case for clarity - subsystem_name is NULL anyway.
2834 default:
2835 subsystem_name = NULL;
2836 }
2837
2838 fprintf (file, "Subsystem\t\t%08x", i->Subsystem);
2839 if (subsystem_name)
2840 fprintf (file, "\t(%s)", subsystem_name);
2841 fprintf (file, "\nDllCharacteristics\t%08x\n", i->DllCharacteristics);
2842 fprintf (file, "SizeOfStackReserve\t");
2843 bfd_fprintf_vma (abfd, file, i->SizeOfStackReserve);
2844 fprintf (file, "\nSizeOfStackCommit\t");
2845 bfd_fprintf_vma (abfd, file, i->SizeOfStackCommit);
2846 fprintf (file, "\nSizeOfHeapReserve\t");
2847 bfd_fprintf_vma (abfd, file, i->SizeOfHeapReserve);
2848 fprintf (file, "\nSizeOfHeapCommit\t");
2849 bfd_fprintf_vma (abfd, file, i->SizeOfHeapCommit);
2850 fprintf (file, "\nLoaderFlags\t\t%08lx\n", (unsigned long) i->LoaderFlags);
2851 fprintf (file, "NumberOfRvaAndSizes\t%08lx\n",
2852 (unsigned long) i->NumberOfRvaAndSizes);
2853
2854 fprintf (file, "\nThe Data Directory\n");
2855 for (j = 0; j < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; j++)
2856 {
2857 fprintf (file, "Entry %1x ", j);
2858 bfd_fprintf_vma (abfd, file, i->DataDirectory[j].VirtualAddress);
2859 fprintf (file, " %08lx ", (unsigned long) i->DataDirectory[j].Size);
2860 fprintf (file, "%s\n", dir_names[j]);
2861 }
2862
2863 pe_print_idata (abfd, vfile);
2864 pe_print_edata (abfd, vfile);
2865 if (bfd_coff_have_print_pdata (abfd))
2866 bfd_coff_print_pdata (abfd, vfile);
2867 else
2868 pe_print_pdata (abfd, vfile);
2869 pe_print_reloc (abfd, vfile);
2870 pe_print_debugdata (abfd, file);
2871
2872 rsrc_print_section (abfd, vfile);
2873
2874 return TRUE;
2875 }
2876
2877 static bfd_boolean
is_vma_in_section(bfd * abfd ATTRIBUTE_UNUSED,asection * sect,void * obj)2878 is_vma_in_section (bfd *abfd ATTRIBUTE_UNUSED, asection *sect, void *obj)
2879 {
2880 bfd_vma addr = * (bfd_vma *) obj;
2881 return (addr >= sect->vma) && (addr < (sect->vma + sect->size));
2882 }
2883
2884 static asection *
find_section_by_vma(bfd * abfd,bfd_vma addr)2885 find_section_by_vma (bfd *abfd, bfd_vma addr)
2886 {
2887 return bfd_sections_find_if (abfd, is_vma_in_section, (void *) & addr);
2888 }
2889
2890 /* Copy any private info we understand from the input bfd
2891 to the output bfd. */
2892
2893 bfd_boolean
_bfd_XX_bfd_copy_private_bfd_data_common(bfd * ibfd,bfd * obfd)2894 _bfd_XX_bfd_copy_private_bfd_data_common (bfd * ibfd, bfd * obfd)
2895 {
2896 pe_data_type *ipe, *ope;
2897
2898 /* One day we may try to grok other private data. */
2899 if (ibfd->xvec->flavour != bfd_target_coff_flavour
2900 || obfd->xvec->flavour != bfd_target_coff_flavour)
2901 return TRUE;
2902
2903 ipe = pe_data (ibfd);
2904 ope = pe_data (obfd);
2905
2906 /* pe_opthdr is copied in copy_object. */
2907 ope->dll = ipe->dll;
2908
2909 /* Don't copy input subsystem if output is different from input. */
2910 if (obfd->xvec != ibfd->xvec)
2911 ope->pe_opthdr.Subsystem = IMAGE_SUBSYSTEM_UNKNOWN;
2912
2913 /* For strip: if we removed .reloc, we'll make a real mess of things
2914 if we don't remove this entry as well. */
2915 if (! pe_data (obfd)->has_reloc_section)
2916 {
2917 pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].VirtualAddress = 0;
2918 pe_data (obfd)->pe_opthdr.DataDirectory[PE_BASE_RELOCATION_TABLE].Size = 0;
2919 }
2920
2921 /* For PIE, if there is .reloc, we won't add IMAGE_FILE_RELOCS_STRIPPED.
2922 But there is no .reloc, we make sure that IMAGE_FILE_RELOCS_STRIPPED
2923 won't be added. */
2924 if (! pe_data (ibfd)->has_reloc_section
2925 && ! (pe_data (ibfd)->real_flags & IMAGE_FILE_RELOCS_STRIPPED))
2926 pe_data (obfd)->dont_strip_reloc = 1;
2927
2928 /* The file offsets contained in the debug directory need rewriting. */
2929 if (ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size != 0)
2930 {
2931 bfd_vma addr = ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].VirtualAddress
2932 + ope->pe_opthdr.ImageBase;
2933 asection *section = find_section_by_vma (obfd, addr);
2934 bfd_byte *data;
2935
2936 if (section && bfd_malloc_and_get_section (obfd, section, &data))
2937 {
2938 unsigned int i;
2939 struct external_IMAGE_DEBUG_DIRECTORY *dd =
2940 (struct external_IMAGE_DEBUG_DIRECTORY *)(data + (addr - section->vma));
2941
2942 for (i = 0; i < ope->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size
2943 / sizeof (struct external_IMAGE_DEBUG_DIRECTORY); i++)
2944 {
2945 asection *ddsection;
2946 struct external_IMAGE_DEBUG_DIRECTORY *edd = &(dd[i]);
2947 struct internal_IMAGE_DEBUG_DIRECTORY idd;
2948
2949 _bfd_XXi_swap_debugdir_in (obfd, edd, &idd);
2950
2951 if (idd.AddressOfRawData == 0)
2952 continue; /* RVA 0 means only offset is valid, not handled yet. */
2953
2954 ddsection = find_section_by_vma (obfd, idd.AddressOfRawData + ope->pe_opthdr.ImageBase);
2955 if (!ddsection)
2956 continue; /* Not in a section! */
2957
2958 idd.PointerToRawData = ddsection->filepos + (idd.AddressOfRawData
2959 + ope->pe_opthdr.ImageBase) - ddsection->vma;
2960
2961 _bfd_XXi_swap_debugdir_out (obfd, &idd, edd);
2962 }
2963
2964 if (!bfd_set_section_contents (obfd, section, data, 0, section->size))
2965 _bfd_error_handler (_("Failed to update file offsets in debug directory"));
2966 }
2967 }
2968
2969 return TRUE;
2970 }
2971
2972 /* Copy private section data. */
2973
2974 bfd_boolean
_bfd_XX_bfd_copy_private_section_data(bfd * ibfd,asection * isec,bfd * obfd,asection * osec)2975 _bfd_XX_bfd_copy_private_section_data (bfd *ibfd,
2976 asection *isec,
2977 bfd *obfd,
2978 asection *osec)
2979 {
2980 if (bfd_get_flavour (ibfd) != bfd_target_coff_flavour
2981 || bfd_get_flavour (obfd) != bfd_target_coff_flavour)
2982 return TRUE;
2983
2984 if (coff_section_data (ibfd, isec) != NULL
2985 && pei_section_data (ibfd, isec) != NULL)
2986 {
2987 if (coff_section_data (obfd, osec) == NULL)
2988 {
2989 bfd_size_type amt = sizeof (struct coff_section_tdata);
2990 osec->used_by_bfd = bfd_zalloc (obfd, amt);
2991 if (osec->used_by_bfd == NULL)
2992 return FALSE;
2993 }
2994
2995 if (pei_section_data (obfd, osec) == NULL)
2996 {
2997 bfd_size_type amt = sizeof (struct pei_section_tdata);
2998 coff_section_data (obfd, osec)->tdata = bfd_zalloc (obfd, amt);
2999 if (coff_section_data (obfd, osec)->tdata == NULL)
3000 return FALSE;
3001 }
3002
3003 pei_section_data (obfd, osec)->virt_size =
3004 pei_section_data (ibfd, isec)->virt_size;
3005 pei_section_data (obfd, osec)->pe_flags =
3006 pei_section_data (ibfd, isec)->pe_flags;
3007 }
3008
3009 return TRUE;
3010 }
3011
3012 void
_bfd_XX_get_symbol_info(bfd * abfd,asymbol * symbol,symbol_info * ret)3013 _bfd_XX_get_symbol_info (bfd * abfd, asymbol *symbol, symbol_info *ret)
3014 {
3015 coff_get_symbol_info (abfd, symbol, ret);
3016 }
3017
3018 #if !defined(COFF_WITH_pep) && defined(COFF_WITH_pex64)
3019 static int
sort_x64_pdata(const void * l,const void * r)3020 sort_x64_pdata (const void *l, const void *r)
3021 {
3022 const char *lp = (const char *) l;
3023 const char *rp = (const char *) r;
3024 bfd_vma vl, vr;
3025 vl = bfd_getl32 (lp); vr = bfd_getl32 (rp);
3026 if (vl != vr)
3027 return (vl < vr ? -1 : 1);
3028 /* We compare just begin address. */
3029 return 0;
3030 }
3031 #endif
3032
3033 /* Functions to process a .rsrc section. */
3034
3035 static unsigned int sizeof_leaves;
3036 static unsigned int sizeof_strings;
3037 static unsigned int sizeof_tables_and_entries;
3038
3039 static bfd_byte *
3040 rsrc_count_directory (bfd *, bfd_byte *, bfd_byte *, bfd_byte *, bfd_vma);
3041
3042 static bfd_byte *
rsrc_count_entries(bfd * abfd,bfd_boolean is_name,bfd_byte * datastart,bfd_byte * data,bfd_byte * dataend,bfd_vma rva_bias)3043 rsrc_count_entries (bfd * abfd,
3044 bfd_boolean is_name,
3045 bfd_byte * datastart,
3046 bfd_byte * data,
3047 bfd_byte * dataend,
3048 bfd_vma rva_bias)
3049 {
3050 unsigned long entry, addr, size;
3051
3052 if (data + 8 >= dataend)
3053 return dataend + 1;
3054
3055 if (is_name)
3056 {
3057 bfd_byte * name;
3058
3059 entry = (long) bfd_get_32 (abfd, data);
3060
3061 if (HighBitSet (entry))
3062 name = datastart + WithoutHighBit (entry);
3063 else
3064 name = datastart + entry - rva_bias;
3065
3066 if (name + 2 >= dataend || name < datastart)
3067 return dataend + 1;
3068
3069 unsigned int len = bfd_get_16 (abfd, name);
3070 if (len == 0 || len > 256)
3071 return dataend + 1;
3072 }
3073
3074 entry = (long) bfd_get_32 (abfd, data + 4);
3075
3076 if (HighBitSet (entry))
3077 {
3078 data = datastart + WithoutHighBit (entry);
3079
3080 if (data <= datastart || data >= dataend)
3081 return dataend + 1;
3082
3083 return rsrc_count_directory (abfd, datastart, data, dataend, rva_bias);
3084 }
3085
3086 if (datastart + entry + 16 >= dataend)
3087 return dataend + 1;
3088
3089 addr = (long) bfd_get_32 (abfd, datastart + entry);
3090 size = (long) bfd_get_32 (abfd, datastart + entry + 4);
3091
3092 return datastart + addr - rva_bias + size;
3093 }
3094
3095 static bfd_byte *
rsrc_count_directory(bfd * abfd,bfd_byte * datastart,bfd_byte * data,bfd_byte * dataend,bfd_vma rva_bias)3096 rsrc_count_directory (bfd * abfd,
3097 bfd_byte * datastart,
3098 bfd_byte * data,
3099 bfd_byte * dataend,
3100 bfd_vma rva_bias)
3101 {
3102 unsigned int num_entries, num_ids;
3103 bfd_byte * highest_data = data;
3104
3105 if (data + 16 >= dataend)
3106 return dataend + 1;
3107
3108 num_entries = (int) bfd_get_16 (abfd, data + 12);
3109 num_ids = (int) bfd_get_16 (abfd, data + 14);
3110
3111 num_entries += num_ids;
3112
3113 data += 16;
3114
3115 while (num_entries --)
3116 {
3117 bfd_byte * entry_end;
3118
3119 entry_end = rsrc_count_entries (abfd, num_entries >= num_ids,
3120 datastart, data, dataend, rva_bias);
3121 data += 8;
3122 highest_data = max (highest_data, entry_end);
3123 if (entry_end >= dataend)
3124 break;
3125 }
3126
3127 return max (highest_data, data);
3128 }
3129
3130 typedef struct rsrc_dir_chain
3131 {
3132 unsigned int num_entries;
3133 struct rsrc_entry * first_entry;
3134 struct rsrc_entry * last_entry;
3135 } rsrc_dir_chain;
3136
3137 typedef struct rsrc_directory
3138 {
3139 unsigned int characteristics;
3140 unsigned int time;
3141 unsigned int major;
3142 unsigned int minor;
3143
3144 rsrc_dir_chain names;
3145 rsrc_dir_chain ids;
3146
3147 struct rsrc_entry * entry;
3148 } rsrc_directory;
3149
3150 typedef struct rsrc_string
3151 {
3152 unsigned int len;
3153 bfd_byte * string;
3154 } rsrc_string;
3155
3156 typedef struct rsrc_leaf
3157 {
3158 unsigned int size;
3159 unsigned int codepage;
3160 bfd_byte * data;
3161 } rsrc_leaf;
3162
3163 typedef struct rsrc_entry
3164 {
3165 bfd_boolean is_name;
3166 union
3167 {
3168 unsigned int id;
3169 struct rsrc_string name;
3170 } name_id;
3171
3172 bfd_boolean is_dir;
3173 union
3174 {
3175 struct rsrc_directory * directory;
3176 struct rsrc_leaf * leaf;
3177 } value;
3178
3179 struct rsrc_entry * next_entry;
3180 struct rsrc_directory * parent;
3181 } rsrc_entry;
3182
3183 static bfd_byte *
3184 rsrc_parse_directory (bfd *, rsrc_directory *, bfd_byte *,
3185 bfd_byte *, bfd_byte *, bfd_vma, rsrc_entry *);
3186
3187 static bfd_byte *
rsrc_parse_entry(bfd * abfd,bfd_boolean is_name,rsrc_entry * entry,bfd_byte * datastart,bfd_byte * data,bfd_byte * dataend,bfd_vma rva_bias,rsrc_directory * parent)3188 rsrc_parse_entry (bfd * abfd,
3189 bfd_boolean is_name,
3190 rsrc_entry * entry,
3191 bfd_byte * datastart,
3192 bfd_byte * data,
3193 bfd_byte * dataend,
3194 bfd_vma rva_bias,
3195 rsrc_directory * parent)
3196 {
3197 unsigned long val, addr, size;
3198
3199 val = bfd_get_32 (abfd, data);
3200
3201 entry->parent = parent;
3202 entry->is_name = is_name;
3203
3204 if (is_name)
3205 {
3206 bfd_byte * address;
3207
3208 if (HighBitSet (val))
3209 {
3210 val = WithoutHighBit (val);
3211
3212 address = datastart + val;
3213 }
3214 else
3215 {
3216 address = datastart + val - rva_bias;
3217 }
3218
3219 if (address + 3 > dataend)
3220 return dataend;
3221
3222 entry->name_id.name.len = bfd_get_16 (abfd, address);
3223 entry->name_id.name.string = address + 2;
3224 }
3225 else
3226 entry->name_id.id = val;
3227
3228 val = bfd_get_32 (abfd, data + 4);
3229
3230 if (HighBitSet (val))
3231 {
3232 entry->is_dir = TRUE;
3233 entry->value.directory = bfd_malloc (sizeof * entry->value.directory);
3234 if (entry->value.directory == NULL)
3235 return dataend;
3236
3237 return rsrc_parse_directory (abfd, entry->value.directory,
3238 datastart,
3239 datastart + WithoutHighBit (val),
3240 dataend, rva_bias, entry);
3241 }
3242
3243 entry->is_dir = FALSE;
3244 entry->value.leaf = bfd_malloc (sizeof * entry->value.leaf);
3245 if (entry->value.leaf == NULL)
3246 return dataend;
3247
3248 addr = bfd_get_32 (abfd, datastart + val);
3249 size = entry->value.leaf->size = bfd_get_32 (abfd, datastart + val + 4);
3250 entry->value.leaf->codepage = bfd_get_32 (abfd, datastart + val + 8);
3251
3252 entry->value.leaf->data = bfd_malloc (size);
3253 if (entry->value.leaf->data == NULL)
3254 return dataend;
3255
3256 memcpy (entry->value.leaf->data, datastart + addr - rva_bias, size);
3257 return datastart + (addr - rva_bias) + size;
3258 }
3259
3260 static bfd_byte *
rsrc_parse_entries(bfd * abfd,rsrc_dir_chain * chain,bfd_boolean is_name,bfd_byte * highest_data,bfd_byte * datastart,bfd_byte * data,bfd_byte * dataend,bfd_vma rva_bias,rsrc_directory * parent)3261 rsrc_parse_entries (bfd * abfd,
3262 rsrc_dir_chain * chain,
3263 bfd_boolean is_name,
3264 bfd_byte * highest_data,
3265 bfd_byte * datastart,
3266 bfd_byte * data,
3267 bfd_byte * dataend,
3268 bfd_vma rva_bias,
3269 rsrc_directory * parent)
3270 {
3271 unsigned int i;
3272 rsrc_entry * entry;
3273
3274 if (chain->num_entries == 0)
3275 {
3276 chain->first_entry = chain->last_entry = NULL;
3277 return highest_data;
3278 }
3279
3280 entry = bfd_malloc (sizeof * entry);
3281 if (entry == NULL)
3282 return dataend;
3283
3284 chain->first_entry = entry;
3285
3286 for (i = chain->num_entries; i--;)
3287 {
3288 bfd_byte * entry_end;
3289
3290 entry_end = rsrc_parse_entry (abfd, is_name, entry, datastart,
3291 data, dataend, rva_bias, parent);
3292 data += 8;
3293 highest_data = max (entry_end, highest_data);
3294 if (entry_end > dataend)
3295 return dataend;
3296
3297 if (i)
3298 {
3299 entry->next_entry = bfd_malloc (sizeof * entry);
3300 entry = entry->next_entry;
3301 if (entry == NULL)
3302 return dataend;
3303 }
3304 else
3305 entry->next_entry = NULL;
3306 }
3307
3308 chain->last_entry = entry;
3309
3310 return highest_data;
3311 }
3312
3313 static bfd_byte *
rsrc_parse_directory(bfd * abfd,rsrc_directory * table,bfd_byte * datastart,bfd_byte * data,bfd_byte * dataend,bfd_vma rva_bias,rsrc_entry * entry)3314 rsrc_parse_directory (bfd * abfd,
3315 rsrc_directory * table,
3316 bfd_byte * datastart,
3317 bfd_byte * data,
3318 bfd_byte * dataend,
3319 bfd_vma rva_bias,
3320 rsrc_entry * entry)
3321 {
3322 bfd_byte * highest_data = data;
3323
3324 if (table == NULL)
3325 return dataend;
3326
3327 table->characteristics = bfd_get_32 (abfd, data);
3328 table->time = bfd_get_32 (abfd, data + 4);
3329 table->major = bfd_get_16 (abfd, data + 8);
3330 table->minor = bfd_get_16 (abfd, data + 10);
3331 table->names.num_entries = bfd_get_16 (abfd, data + 12);
3332 table->ids.num_entries = bfd_get_16 (abfd, data + 14);
3333 table->entry = entry;
3334
3335 data += 16;
3336
3337 highest_data = rsrc_parse_entries (abfd, & table->names, TRUE, data,
3338 datastart, data, dataend, rva_bias, table);
3339 data += table->names.num_entries * 8;
3340
3341 highest_data = rsrc_parse_entries (abfd, & table->ids, FALSE, highest_data,
3342 datastart, data, dataend, rva_bias, table);
3343 data += table->ids.num_entries * 8;
3344
3345 return max (highest_data, data);
3346 }
3347
3348 typedef struct rsrc_write_data
3349 {
3350 bfd * abfd;
3351 bfd_byte * datastart;
3352 bfd_byte * next_table;
3353 bfd_byte * next_leaf;
3354 bfd_byte * next_string;
3355 bfd_byte * next_data;
3356 bfd_vma rva_bias;
3357 } rsrc_write_data;
3358
3359 static void
rsrc_write_string(rsrc_write_data * data,rsrc_string * string)3360 rsrc_write_string (rsrc_write_data * data,
3361 rsrc_string * string)
3362 {
3363 bfd_put_16 (data->abfd, string->len, data->next_string);
3364 memcpy (data->next_string + 2, string->string, string->len * 2);
3365 data->next_string += (string->len + 1) * 2;
3366 }
3367
3368 static inline unsigned int
rsrc_compute_rva(rsrc_write_data * data,bfd_byte * addr)3369 rsrc_compute_rva (rsrc_write_data * data,
3370 bfd_byte * addr)
3371 {
3372 return (addr - data->datastart) + data->rva_bias;
3373 }
3374
3375 static void
rsrc_write_leaf(rsrc_write_data * data,rsrc_leaf * leaf)3376 rsrc_write_leaf (rsrc_write_data * data,
3377 rsrc_leaf * leaf)
3378 {
3379 bfd_put_32 (data->abfd, rsrc_compute_rva (data, data->next_data),
3380 data->next_leaf);
3381 bfd_put_32 (data->abfd, leaf->size, data->next_leaf + 4);
3382 bfd_put_32 (data->abfd, leaf->codepage, data->next_leaf + 8);
3383 bfd_put_32 (data->abfd, 0 /*reserved*/, data->next_leaf + 12);
3384 data->next_leaf += 16;
3385
3386 memcpy (data->next_data, leaf->data, leaf->size);
3387 /* An undocumented feature of Windows resources is that each unit
3388 of raw data is 8-byte aligned... */
3389 data->next_data += ((leaf->size + 7) & ~7);
3390 }
3391
3392 static void rsrc_write_directory (rsrc_write_data *, rsrc_directory *);
3393
3394 static void
rsrc_write_entry(rsrc_write_data * data,bfd_byte * where,rsrc_entry * entry)3395 rsrc_write_entry (rsrc_write_data * data,
3396 bfd_byte * where,
3397 rsrc_entry * entry)
3398 {
3399 if (entry->is_name)
3400 {
3401 bfd_put_32 (data->abfd,
3402 SetHighBit (data->next_string - data->datastart),
3403 where);
3404 rsrc_write_string (data, & entry->name_id.name);
3405 }
3406 else
3407 bfd_put_32 (data->abfd, entry->name_id.id, where);
3408
3409 if (entry->is_dir)
3410 {
3411 bfd_put_32 (data->abfd,
3412 SetHighBit (data->next_table - data->datastart),
3413 where + 4);
3414 rsrc_write_directory (data, entry->value.directory);
3415 }
3416 else
3417 {
3418 bfd_put_32 (data->abfd, data->next_leaf - data->datastart, where + 4);
3419 rsrc_write_leaf (data, entry->value.leaf);
3420 }
3421 }
3422
3423 static void
rsrc_compute_region_sizes(rsrc_directory * dir)3424 rsrc_compute_region_sizes (rsrc_directory * dir)
3425 {
3426 struct rsrc_entry * entry;
3427
3428 if (dir == NULL)
3429 return;
3430
3431 sizeof_tables_and_entries += 16;
3432
3433 for (entry = dir->names.first_entry; entry != NULL; entry = entry->next_entry)
3434 {
3435 sizeof_tables_and_entries += 8;
3436
3437 sizeof_strings += (entry->name_id.name.len + 1) * 2;
3438
3439 if (entry->is_dir)
3440 rsrc_compute_region_sizes (entry->value.directory);
3441 else
3442 sizeof_leaves += 16;
3443 }
3444
3445 for (entry = dir->ids.first_entry; entry != NULL; entry = entry->next_entry)
3446 {
3447 sizeof_tables_and_entries += 8;
3448
3449 if (entry->is_dir)
3450 rsrc_compute_region_sizes (entry->value.directory);
3451 else
3452 sizeof_leaves += 16;
3453 }
3454 }
3455
3456 static void
rsrc_write_directory(rsrc_write_data * data,rsrc_directory * dir)3457 rsrc_write_directory (rsrc_write_data * data,
3458 rsrc_directory * dir)
3459 {
3460 rsrc_entry * entry;
3461 unsigned int i;
3462 bfd_byte * next_entry;
3463 bfd_byte * nt;
3464
3465 bfd_put_32 (data->abfd, dir->characteristics, data->next_table);
3466 bfd_put_32 (data->abfd, 0 /*dir->time*/, data->next_table + 4);
3467 bfd_put_16 (data->abfd, dir->major, data->next_table + 8);
3468 bfd_put_16 (data->abfd, dir->minor, data->next_table + 10);
3469 bfd_put_16 (data->abfd, dir->names.num_entries, data->next_table + 12);
3470 bfd_put_16 (data->abfd, dir->ids.num_entries, data->next_table + 14);
3471
3472 /* Compute where the entries and the next table will be placed. */
3473 next_entry = data->next_table + 16;
3474 data->next_table = next_entry + (dir->names.num_entries * 8)
3475 + (dir->ids.num_entries * 8);
3476 nt = data->next_table;
3477
3478 /* Write the entries. */
3479 for (i = dir->names.num_entries, entry = dir->names.first_entry;
3480 i > 0 && entry != NULL;
3481 i--, entry = entry->next_entry)
3482 {
3483 BFD_ASSERT (entry->is_name);
3484 rsrc_write_entry (data, next_entry, entry);
3485 next_entry += 8;
3486 }
3487 BFD_ASSERT (i == 0);
3488 BFD_ASSERT (entry == NULL);
3489
3490 for (i = dir->ids.num_entries, entry = dir->ids.first_entry;
3491 i > 0 && entry != NULL;
3492 i--, entry = entry->next_entry)
3493 {
3494 BFD_ASSERT (! entry->is_name);
3495 rsrc_write_entry (data, next_entry, entry);
3496 next_entry += 8;
3497 }
3498 BFD_ASSERT (i == 0);
3499 BFD_ASSERT (entry == NULL);
3500 BFD_ASSERT (nt == next_entry);
3501 }
3502
3503 #if defined HAVE_WCHAR_H && ! defined __CYGWIN__ && ! defined __MINGW32__
3504 /* Return the length (number of units) of the first character in S,
3505 putting its 'ucs4_t' representation in *PUC. */
3506
3507 static unsigned int
3508 #if defined HAVE_WCTYPE_H
u16_mbtouc(wint_t * puc,const unsigned short * s,unsigned int n)3509 u16_mbtouc (wint_t * puc, const unsigned short * s, unsigned int n)
3510 #else
3511 u16_mbtouc (wchar_t * puc, const unsigned short * s, unsigned int n)
3512 #endif
3513 {
3514 unsigned short c = * s;
3515
3516 if (c < 0xd800 || c >= 0xe000)
3517 {
3518 *puc = c;
3519 return 1;
3520 }
3521
3522 if (c < 0xdc00)
3523 {
3524 if (n >= 2)
3525 {
3526 if (s[1] >= 0xdc00 && s[1] < 0xe000)
3527 {
3528 *puc = 0x10000 + ((c - 0xd800) << 10) + (s[1] - 0xdc00);
3529 return 2;
3530 }
3531 }
3532 else
3533 {
3534 /* Incomplete multibyte character. */
3535 *puc = 0xfffd;
3536 return n;
3537 }
3538 }
3539
3540 /* Invalid multibyte character. */
3541 *puc = 0xfffd;
3542 return 1;
3543 }
3544 #endif /* HAVE_WCHAR_H and not Cygwin/Mingw */
3545
3546 /* Perform a comparison of two entries. */
3547 static signed int
rsrc_cmp(bfd_boolean is_name,rsrc_entry * a,rsrc_entry * b)3548 rsrc_cmp (bfd_boolean is_name, rsrc_entry * a, rsrc_entry * b)
3549 {
3550 signed int res;
3551 bfd_byte * astring;
3552 unsigned int alen;
3553 bfd_byte * bstring;
3554 unsigned int blen;
3555
3556 if (! is_name)
3557 return a->name_id.id - b->name_id.id;
3558
3559 /* We have to perform a case insenstive, unicode string comparison... */
3560 astring = a->name_id.name.string;
3561 alen = a->name_id.name.len;
3562 bstring = b->name_id.name.string;
3563 blen = b->name_id.name.len;
3564
3565 #if defined __CYGWIN__ || defined __MINGW32__
3566 /* Under Windows hosts (both Cygwin and Mingw types),
3567 unicode == UTF-16 == wchar_t. The case insensitive string comparison
3568 function however goes by different names in the two environments... */
3569
3570 #undef rscpcmp
3571 #ifdef __CYGWIN__
3572 #define rscpcmp wcsncasecmp
3573 #endif
3574 #ifdef __MINGW32__
3575 #define rscpcmp wcsnicmp
3576 #endif
3577
3578 res = rscpcmp ((const wchar_t *) astring, (const wchar_t *) bstring,
3579 min (alen, blen));
3580
3581 #elif defined HAVE_WCHAR_H
3582 {
3583 unsigned int i;
3584
3585 res = 0;
3586 for (i = min (alen, blen); i--; astring += 2, bstring += 2)
3587 {
3588 #if defined HAVE_WCTYPE_H
3589 wint_t awc;
3590 wint_t bwc;
3591 #else
3592 wchar_t awc;
3593 wchar_t bwc;
3594 #endif
3595
3596 /* Convert UTF-16 unicode characters into wchar_t characters
3597 so that we can then perform a case insensitive comparison. */
3598 unsigned int Alen = u16_mbtouc (& awc, (const unsigned short *) astring, 2);
3599 unsigned int Blen = u16_mbtouc (& bwc, (const unsigned short *) bstring, 2);
3600
3601 if (Alen != Blen)
3602 return Alen - Blen;
3603
3604 #ifdef HAVE_WCTYPE_H
3605 awc = towlower (awc);
3606 bwc = towlower (bwc);
3607
3608 res = awc - bwc;
3609 #else
3610 res = wcsncasecmp (& awc, & bwc, 1);
3611 #endif
3612 if (res)
3613 break;
3614 }
3615 }
3616 #else
3617 /* Do the best we can - a case sensitive, untranslated comparison. */
3618 res = memcmp (astring, bstring, min (alen, blen) * 2);
3619 #endif
3620
3621 if (res == 0)
3622 res = alen - blen;
3623
3624 return res;
3625 }
3626
3627 static void
rsrc_print_name(char * buffer,rsrc_string string)3628 rsrc_print_name (char * buffer, rsrc_string string)
3629 {
3630 unsigned int i;
3631 bfd_byte * name = string.string;
3632
3633 for (i = string.len; i--; name += 2)
3634 sprintf (buffer + strlen (buffer), "%.1s", name);
3635 }
3636
3637 static const char *
rsrc_resource_name(rsrc_entry * entry,rsrc_directory * dir)3638 rsrc_resource_name (rsrc_entry * entry, rsrc_directory * dir)
3639 {
3640 static char buffer [256];
3641 bfd_boolean is_string = FALSE;
3642
3643 buffer[0] = 0;
3644
3645 if (dir != NULL && dir->entry != NULL && dir->entry->parent != NULL
3646 && dir->entry->parent->entry != NULL)
3647 {
3648 strcpy (buffer, "type: ");
3649 if (dir->entry->parent->entry->is_name)
3650 rsrc_print_name (buffer + strlen (buffer),
3651 dir->entry->parent->entry->name_id.name);
3652 else
3653 {
3654 unsigned int id = dir->entry->parent->entry->name_id.id;
3655
3656 sprintf (buffer + strlen (buffer), "%x", id);
3657 switch (id)
3658 {
3659 case 1: strcat (buffer, " (CURSOR)"); break;
3660 case 2: strcat (buffer, " (BITMAP)"); break;
3661 case 3: strcat (buffer, " (ICON)"); break;
3662 case 4: strcat (buffer, " (MENU)"); break;
3663 case 5: strcat (buffer, " (DIALOG)"); break;
3664 case 6: strcat (buffer, " (STRING)"); is_string = TRUE; break;
3665 case 7: strcat (buffer, " (FONTDIR)"); break;
3666 case 8: strcat (buffer, " (FONT)"); break;
3667 case 9: strcat (buffer, " (ACCELERATOR)"); break;
3668 case 10: strcat (buffer, " (RCDATA)"); break;
3669 case 11: strcat (buffer, " (MESSAGETABLE)"); break;
3670 case 12: strcat (buffer, " (GROUP_CURSOR)"); break;
3671 case 14: strcat (buffer, " (GROUP_ICON)"); break;
3672 case 16: strcat (buffer, " (VERSION)"); break;
3673 case 17: strcat (buffer, " (DLGINCLUDE)"); break;
3674 case 19: strcat (buffer, " (PLUGPLAY)"); break;
3675 case 20: strcat (buffer, " (VXD)"); break;
3676 case 21: strcat (buffer, " (ANICURSOR)"); break;
3677 case 22: strcat (buffer, " (ANIICON)"); break;
3678 case 23: strcat (buffer, " (HTML)"); break;
3679 case 24: strcat (buffer, " (MANIFEST)"); break;
3680 case 240: strcat (buffer, " (DLGINIT)"); break;
3681 case 241: strcat (buffer, " (TOOLBAR)"); break;
3682 }
3683 }
3684 }
3685
3686 if (dir != NULL && dir->entry != NULL)
3687 {
3688 strcat (buffer, " name: ");
3689 if (dir->entry->is_name)
3690 rsrc_print_name (buffer + strlen (buffer), dir->entry->name_id.name);
3691 else
3692 {
3693 unsigned int id = dir->entry->name_id.id;
3694
3695 sprintf (buffer + strlen (buffer), "%x", id);
3696
3697 if (is_string)
3698 sprintf (buffer + strlen (buffer), " (resource id range: %d - %d)",
3699 (id - 1) << 4, (id << 4) - 1);
3700 }
3701 }
3702
3703 if (entry != NULL)
3704 {
3705 strcat (buffer, " lang: ");
3706
3707 if (entry->is_name)
3708 rsrc_print_name (buffer + strlen (buffer), entry->name_id.name);
3709 else
3710 sprintf (buffer + strlen (buffer), "%x", entry->name_id.id);
3711 }
3712
3713 return buffer;
3714 }
3715
3716 /* *sigh* Windows resource strings are special. Only the top 28-bits of
3717 their ID is stored in the NAME entry. The bottom four bits are used as
3718 an index into unicode string table that makes up the data of the leaf.
3719 So identical type-name-lang string resources may not actually be
3720 identical at all.
3721
3722 This function is called when we have detected two string resources with
3723 match top-28-bit IDs. We have to scan the string tables inside the leaves
3724 and discover if there are any real collisions. If there are then we report
3725 them and return FALSE. Otherwise we copy any strings from B into A and
3726 then return TRUE. */
3727
3728 static bfd_boolean
rsrc_merge_string_entries(rsrc_entry * a ATTRIBUTE_UNUSED,rsrc_entry * b ATTRIBUTE_UNUSED)3729 rsrc_merge_string_entries (rsrc_entry * a ATTRIBUTE_UNUSED,
3730 rsrc_entry * b ATTRIBUTE_UNUSED)
3731 {
3732 unsigned int copy_needed = 0;
3733 unsigned int i;
3734 bfd_byte * astring;
3735 bfd_byte * bstring;
3736 bfd_byte * new_data;
3737 bfd_byte * nstring;
3738
3739 /* Step one: Find out what we have to do. */
3740 BFD_ASSERT (! a->is_dir);
3741 astring = a->value.leaf->data;
3742
3743 BFD_ASSERT (! b->is_dir);
3744 bstring = b->value.leaf->data;
3745
3746 for (i = 0; i < 16; i++)
3747 {
3748 unsigned int alen = astring[0] + (astring[1] << 8);
3749 unsigned int blen = bstring[0] + (bstring[1] << 8);
3750
3751 if (alen == 0)
3752 {
3753 copy_needed += blen * 2;
3754 }
3755 else if (blen == 0)
3756 ;
3757 else if (alen != blen)
3758 /* FIXME: Should we continue the loop in order to report other duplicates ? */
3759 break;
3760 /* alen == blen != 0. We might have two identical strings. If so we
3761 can ignore the second one. There is no need for wchar_t vs UTF-16
3762 theatrics here - we are only interested in (case sensitive) equality. */
3763 else if (memcmp (astring + 2, bstring + 2, alen * 2) != 0)
3764 break;
3765
3766 astring += (alen + 1) * 2;
3767 bstring += (blen + 1) * 2;
3768 }
3769
3770 if (i != 16)
3771 {
3772 if (a->parent != NULL
3773 && a->parent->entry != NULL
3774 && a->parent->entry->is_name == FALSE)
3775 _bfd_error_handler (_(".rsrc merge failure: duplicate string resource: %d"),
3776 ((a->parent->entry->name_id.id - 1) << 4) + i);
3777 return FALSE;
3778 }
3779
3780 if (copy_needed == 0)
3781 return TRUE;
3782
3783 /* If we reach here then A and B must both have non-colliding strings.
3784 (We never get string resources with fully empty string tables).
3785 We need to allocate an extra COPY_NEEDED bytes in A and then bring
3786 in B's strings. */
3787 new_data = bfd_malloc (a->value.leaf->size + copy_needed);
3788 if (new_data == NULL)
3789 return FALSE;
3790
3791 nstring = new_data;
3792 astring = a->value.leaf->data;
3793 bstring = b->value.leaf->data;
3794
3795 for (i = 0; i < 16; i++)
3796 {
3797 unsigned int alen = astring[0] + (astring[1] << 8);
3798 unsigned int blen = bstring[0] + (bstring[1] << 8);
3799
3800 if (alen != 0)
3801 {
3802 memcpy (nstring, astring, (alen + 1) * 2);
3803 nstring += (alen + 1) * 2;
3804 }
3805 else if (blen != 0)
3806 {
3807 memcpy (nstring, bstring, (blen + 1) * 2);
3808 nstring += (blen + 1) * 2;
3809 }
3810 else
3811 {
3812 * nstring++ = 0;
3813 * nstring++ = 0;
3814 }
3815
3816 astring += (alen + 1) * 2;
3817 bstring += (blen + 1) * 2;
3818 }
3819
3820 BFD_ASSERT (nstring - new_data == (signed) (a->value.leaf->size + copy_needed));
3821
3822 free (a->value.leaf->data);
3823 a->value.leaf->data = new_data;
3824 a->value.leaf->size += copy_needed;
3825
3826 return TRUE;
3827 }
3828
3829 static void rsrc_merge (rsrc_entry *, rsrc_entry *);
3830
3831 /* Sort the entries in given part of the directory.
3832 We use an old fashioned bubble sort because we are dealing
3833 with lists and we want to handle matches specially. */
3834
3835 static void
rsrc_sort_entries(rsrc_dir_chain * chain,bfd_boolean is_name,rsrc_directory * dir)3836 rsrc_sort_entries (rsrc_dir_chain * chain,
3837 bfd_boolean is_name,
3838 rsrc_directory * dir)
3839 {
3840 rsrc_entry * entry;
3841 rsrc_entry * next;
3842 rsrc_entry ** points_to_entry;
3843 bfd_boolean swapped;
3844
3845 if (chain->num_entries < 2)
3846 return;
3847
3848 do
3849 {
3850 swapped = FALSE;
3851 points_to_entry = & chain->first_entry;
3852 entry = * points_to_entry;
3853 next = entry->next_entry;
3854
3855 do
3856 {
3857 signed int cmp = rsrc_cmp (is_name, entry, next);
3858
3859 if (cmp > 0)
3860 {
3861 entry->next_entry = next->next_entry;
3862 next->next_entry = entry;
3863 * points_to_entry = next;
3864 points_to_entry = & next->next_entry;
3865 next = entry->next_entry;
3866 swapped = TRUE;
3867 }
3868 else if (cmp == 0)
3869 {
3870 if (entry->is_dir && next->is_dir)
3871 {
3872 /* When we encounter identical directory entries we have to
3873 merge them together. The exception to this rule is for
3874 resource manifests - there can only be one of these,
3875 even if they differ in language. Zero-language manifests
3876 are assumed to be default manifests (provided by the
3877 Cygwin/MinGW build system) and these can be silently dropped,
3878 unless that would reduce the number of manifests to zero.
3879 There should only ever be one non-zero lang manifest -
3880 if there are more it is an error. A non-zero lang
3881 manifest takes precedence over a default manifest. */
3882 if (entry->is_name == FALSE
3883 && entry->name_id.id == 1
3884 && dir != NULL
3885 && dir->entry != NULL
3886 && dir->entry->is_name == FALSE
3887 && dir->entry->name_id.id == 0x18)
3888 {
3889 if (next->value.directory->names.num_entries == 0
3890 && next->value.directory->ids.num_entries == 1
3891 && next->value.directory->ids.first_entry->is_name == FALSE
3892 && next->value.directory->ids.first_entry->name_id.id == 0)
3893 /* Fall through so that NEXT is dropped. */
3894 ;
3895 else if (entry->value.directory->names.num_entries == 0
3896 && entry->value.directory->ids.num_entries == 1
3897 && entry->value.directory->ids.first_entry->is_name == FALSE
3898 && entry->value.directory->ids.first_entry->name_id.id == 0)
3899 {
3900 /* Swap ENTRY and NEXT. Then fall through so that the old ENTRY is dropped. */
3901 entry->next_entry = next->next_entry;
3902 next->next_entry = entry;
3903 * points_to_entry = next;
3904 points_to_entry = & next->next_entry;
3905 next = entry->next_entry;
3906 swapped = TRUE;
3907 }
3908 else
3909 {
3910 _bfd_error_handler (_(".rsrc merge failure: multiple non-default manifests"));
3911 bfd_set_error (bfd_error_file_truncated);
3912 return;
3913 }
3914
3915 /* Unhook NEXT from the chain. */
3916 /* FIXME: memory loss here. */
3917 entry->next_entry = next->next_entry;
3918 chain->num_entries --;
3919 if (chain->num_entries < 2)
3920 return;
3921 next = next->next_entry;
3922 }
3923 else
3924 rsrc_merge (entry, next);
3925 }
3926 else if (entry->is_dir != next->is_dir)
3927 {
3928 _bfd_error_handler (_(".rsrc merge failure: a directory matches a leaf"));
3929 bfd_set_error (bfd_error_file_truncated);
3930 return;
3931 }
3932 else
3933 {
3934 /* Otherwise with identical leaves we issue an error
3935 message - because there should never be duplicates.
3936 The exception is Type 18/Name 1/Lang 0 which is the
3937 defaul manifest - this can just be dropped. */
3938 if (entry->is_name == FALSE
3939 && entry->name_id.id == 0
3940 && dir != NULL
3941 && dir->entry != NULL
3942 && dir->entry->is_name == FALSE
3943 && dir->entry->name_id.id == 1
3944 && dir->entry->parent != NULL
3945 && dir->entry->parent->entry != NULL
3946 && dir->entry->parent->entry->is_name == FALSE
3947 && dir->entry->parent->entry->name_id.id == 0x18 /* RT_MANIFEST */)
3948 ;
3949 else if (dir != NULL
3950 && dir->entry != NULL
3951 && dir->entry->parent != NULL
3952 && dir->entry->parent->entry != NULL
3953 && dir->entry->parent->entry->is_name == FALSE
3954 && dir->entry->parent->entry->name_id.id == 0x6 /* RT_STRING */)
3955 {
3956 /* Strings need special handling. */
3957 if (! rsrc_merge_string_entries (entry, next))
3958 {
3959 /* _bfd_error_handler should have been called inside merge_strings. */
3960 bfd_set_error (bfd_error_file_truncated);
3961 return;
3962 }
3963 }
3964 else
3965 {
3966 if (dir == NULL
3967 || dir->entry == NULL
3968 || dir->entry->parent == NULL
3969 || dir->entry->parent->entry == NULL)
3970 _bfd_error_handler (_(".rsrc merge failure: duplicate leaf"));
3971 else
3972 _bfd_error_handler (_(".rsrc merge failure: duplicate leaf: %s"),
3973 rsrc_resource_name (entry, dir));
3974 bfd_set_error (bfd_error_file_truncated);
3975 return;
3976 }
3977 }
3978
3979 /* Unhook NEXT from the chain. */
3980 entry->next_entry = next->next_entry;
3981 chain->num_entries --;
3982 if (chain->num_entries < 2)
3983 return;
3984 next = next->next_entry;
3985 }
3986 else
3987 {
3988 points_to_entry = & entry->next_entry;
3989 entry = next;
3990 next = next->next_entry;
3991 }
3992 }
3993 while (next);
3994
3995 chain->last_entry = entry;
3996 }
3997 while (swapped);
3998 }
3999
4000 /* Attach B's chain onto A. */
4001 static void
rsrc_attach_chain(rsrc_dir_chain * achain,rsrc_dir_chain * bchain)4002 rsrc_attach_chain (rsrc_dir_chain * achain, rsrc_dir_chain * bchain)
4003 {
4004 if (bchain->num_entries == 0)
4005 return;
4006
4007 achain->num_entries += bchain->num_entries;
4008
4009 if (achain->first_entry == NULL)
4010 {
4011 achain->first_entry = bchain->first_entry;
4012 achain->last_entry = bchain->last_entry;
4013 }
4014 else
4015 {
4016 achain->last_entry->next_entry = bchain->first_entry;
4017 achain->last_entry = bchain->last_entry;
4018 }
4019
4020 bchain->num_entries = 0;
4021 bchain->first_entry = bchain->last_entry = NULL;
4022 }
4023
4024 static void
rsrc_merge(struct rsrc_entry * a,struct rsrc_entry * b)4025 rsrc_merge (struct rsrc_entry * a, struct rsrc_entry * b)
4026 {
4027 rsrc_directory * adir;
4028 rsrc_directory * bdir;
4029
4030 BFD_ASSERT (a->is_dir);
4031 BFD_ASSERT (b->is_dir);
4032
4033 adir = a->value.directory;
4034 bdir = b->value.directory;
4035
4036 if (adir->characteristics != bdir->characteristics)
4037 {
4038 _bfd_error_handler (_(".rsrc merge failure: dirs with differing characteristics\n"));
4039 bfd_set_error (bfd_error_file_truncated);
4040 return;
4041 }
4042
4043 if (adir->major != bdir->major || adir->minor != bdir->minor)
4044 {
4045 _bfd_error_handler (_(".rsrc merge failure: differing directory versions\n"));
4046 bfd_set_error (bfd_error_file_truncated);
4047 return;
4048 }
4049
4050 /* Attach B's name chain to A. */
4051 rsrc_attach_chain (& adir->names, & bdir->names);
4052
4053 /* Attach B's ID chain to A. */
4054 rsrc_attach_chain (& adir->ids, & bdir->ids);
4055
4056 /* Now sort A's entries. */
4057 rsrc_sort_entries (& adir->names, TRUE, adir);
4058 rsrc_sort_entries (& adir->ids, FALSE, adir);
4059 }
4060
4061 /* Check the .rsrc section. If it contains multiple concatenated
4062 resources then we must merge them properly. Otherwise Windows
4063 will ignore all but the first set. */
4064
4065 static void
rsrc_process_section(bfd * abfd,struct coff_final_link_info * pfinfo)4066 rsrc_process_section (bfd * abfd,
4067 struct coff_final_link_info * pfinfo)
4068 {
4069 rsrc_directory new_table;
4070 bfd_size_type size;
4071 asection * sec;
4072 pe_data_type * pe;
4073 bfd_vma rva_bias;
4074 bfd_byte * data;
4075 bfd_byte * datastart;
4076 bfd_byte * dataend;
4077 bfd_byte * new_data;
4078 unsigned int num_resource_sets;
4079 rsrc_directory * type_tables;
4080 rsrc_write_data write_data;
4081 unsigned int indx;
4082 bfd * input;
4083 unsigned int num_input_rsrc = 0;
4084 unsigned int max_num_input_rsrc = 4;
4085 ptrdiff_t * rsrc_sizes = NULL;
4086
4087 new_table.names.num_entries = 0;
4088 new_table.ids.num_entries = 0;
4089
4090 sec = bfd_get_section_by_name (abfd, ".rsrc");
4091 if (sec == NULL || (size = sec->rawsize) == 0)
4092 return;
4093
4094 pe = pe_data (abfd);
4095 if (pe == NULL)
4096 return;
4097
4098 rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
4099
4100 data = bfd_malloc (size);
4101 if (data == NULL)
4102 return;
4103
4104 datastart = data;
4105
4106 if (! bfd_get_section_contents (abfd, sec, data, 0, size))
4107 goto end;
4108
4109 /* Step zero: Scan the input bfds looking for .rsrc sections and record
4110 their lengths. Note - we rely upon the fact that the linker script
4111 does *not* sort the input .rsrc sections, so that the order in the
4112 linkinfo list matches the order in the output .rsrc section.
4113
4114 We need to know the lengths because each input .rsrc section has padding
4115 at the end of a variable amount. (It does not appear to be based upon
4116 the section alignment or the file alignment). We need to skip any
4117 padding bytes when parsing the input .rsrc sections. */
4118 rsrc_sizes = bfd_malloc (max_num_input_rsrc * sizeof * rsrc_sizes);
4119 if (rsrc_sizes == NULL)
4120 goto end;
4121
4122 for (input = pfinfo->info->input_bfds;
4123 input != NULL;
4124 input = input->link.next)
4125 {
4126 asection * rsrc_sec = bfd_get_section_by_name (input, ".rsrc");
4127
4128 if (rsrc_sec != NULL)
4129 {
4130 if (num_input_rsrc == max_num_input_rsrc)
4131 {
4132 max_num_input_rsrc += 10;
4133 rsrc_sizes = bfd_realloc (rsrc_sizes, max_num_input_rsrc
4134 * sizeof * rsrc_sizes);
4135 if (rsrc_sizes == NULL)
4136 goto end;
4137 }
4138
4139 BFD_ASSERT (rsrc_sec->size > 0);
4140 rsrc_sizes [num_input_rsrc ++] = rsrc_sec->size;
4141 }
4142 }
4143
4144 if (num_input_rsrc < 2)
4145 goto end;
4146
4147 /* Step one: Walk the section, computing the size of the tables,
4148 leaves and data and decide if we need to do anything. */
4149 dataend = data + size;
4150 num_resource_sets = 0;
4151
4152 while (data < dataend)
4153 {
4154 bfd_byte * p = data;
4155
4156 data = rsrc_count_directory (abfd, data, data, dataend, rva_bias);
4157
4158 if (data > dataend)
4159 {
4160 /* Corrupted .rsrc section - cannot merge. */
4161 _bfd_error_handler (_("%s: .rsrc merge failure: corrupt .rsrc section"),
4162 bfd_get_filename (abfd));
4163 bfd_set_error (bfd_error_file_truncated);
4164 goto end;
4165 }
4166
4167 if ((data - p) > rsrc_sizes [num_resource_sets])
4168 {
4169 _bfd_error_handler (_("%s: .rsrc merge failure: unexpected .rsrc size"),
4170 bfd_get_filename (abfd));
4171 bfd_set_error (bfd_error_file_truncated);
4172 goto end;
4173 }
4174 /* FIXME: Should we add a check for "data - p" being much smaller
4175 than rsrc_sizes[num_resource_sets] ? */
4176
4177 data = p + rsrc_sizes[num_resource_sets];
4178 rva_bias += data - p;
4179 ++ num_resource_sets;
4180 }
4181 BFD_ASSERT (num_resource_sets == num_input_rsrc);
4182
4183 /* Step two: Walk the data again, building trees of the resources. */
4184 data = datastart;
4185 rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
4186
4187 type_tables = bfd_malloc (num_resource_sets * sizeof * type_tables);
4188 if (type_tables == NULL)
4189 goto end;
4190
4191 indx = 0;
4192 while (data < dataend)
4193 {
4194 bfd_byte * p = data;
4195
4196 (void) rsrc_parse_directory (abfd, type_tables + indx, data, data,
4197 dataend, rva_bias, NULL);
4198 data = p + rsrc_sizes[indx];
4199 rva_bias += data - p;
4200 ++ indx;
4201 }
4202 BFD_ASSERT (indx == num_resource_sets);
4203
4204 /* Step three: Merge the top level tables (there can be only one).
4205
4206 We must ensure that the merged entries are in ascending order.
4207
4208 We also thread the top level table entries from the old tree onto
4209 the new table, so that they can be pulled off later. */
4210
4211 /* FIXME: Should we verify that all type tables are the same ? */
4212 new_table.characteristics = type_tables[0].characteristics;
4213 new_table.time = type_tables[0].time;
4214 new_table.major = type_tables[0].major;
4215 new_table.minor = type_tables[0].minor;
4216
4217 /* Chain the NAME entries onto the table. */
4218 new_table.names.first_entry = NULL;
4219 new_table.names.last_entry = NULL;
4220
4221 for (indx = 0; indx < num_resource_sets; indx++)
4222 rsrc_attach_chain (& new_table.names, & type_tables[indx].names);
4223
4224 rsrc_sort_entries (& new_table.names, TRUE, & new_table);
4225
4226 /* Chain the ID entries onto the table. */
4227 new_table.ids.first_entry = NULL;
4228 new_table.ids.last_entry = NULL;
4229
4230 for (indx = 0; indx < num_resource_sets; indx++)
4231 rsrc_attach_chain (& new_table.ids, & type_tables[indx].ids);
4232
4233 rsrc_sort_entries (& new_table.ids, FALSE, & new_table);
4234
4235 /* Step four: Create new contents for the .rsrc section. */
4236 /* Step four point one: Compute the size of each region of the .rsrc section.
4237 We do this now, rather than earlier, as the merging above may have dropped
4238 some entries. */
4239 sizeof_leaves = sizeof_strings = sizeof_tables_and_entries = 0;
4240 rsrc_compute_region_sizes (& new_table);
4241 /* We increment sizeof_strings to make sure that resource data
4242 starts on an 8-byte boundary. FIXME: Is this correct ? */
4243 sizeof_strings = (sizeof_strings + 7) & ~ 7;
4244
4245 new_data = bfd_zalloc (abfd, size);
4246 if (new_data == NULL)
4247 goto end;
4248
4249 write_data.abfd = abfd;
4250 write_data.datastart = new_data;
4251 write_data.next_table = new_data;
4252 write_data.next_leaf = new_data + sizeof_tables_and_entries;
4253 write_data.next_string = write_data.next_leaf + sizeof_leaves;
4254 write_data.next_data = write_data.next_string + sizeof_strings;
4255 write_data.rva_bias = sec->vma - pe->pe_opthdr.ImageBase;
4256
4257 rsrc_write_directory (& write_data, & new_table);
4258
4259 /* Step five: Replace the old contents with the new.
4260 We recompute the size as we may have lost entries due to mergeing. */
4261 size = ((write_data.next_data - new_data) + 3) & ~ 3;
4262
4263 {
4264 int page_size;
4265
4266 if (coff_data (abfd)->link_info)
4267 {
4268 page_size = pe_data (abfd)->pe_opthdr.FileAlignment;
4269
4270 /* If no file alignment has been set, default to one.
4271 This repairs 'ld -r' for arm-wince-pe target. */
4272 if (page_size == 0)
4273 page_size = 1;
4274 }
4275 else
4276 page_size = PE_DEF_FILE_ALIGNMENT;
4277 size = (size + page_size - 1) & - page_size;
4278 }
4279
4280 bfd_set_section_contents (pfinfo->output_bfd, sec, new_data, 0, size);
4281 sec->size = sec->rawsize = size;
4282
4283 end:
4284 /* Step six: Free all the memory that we have used. */
4285 /* FIXME: Free the resource tree, if we have one. */
4286 free (datastart);
4287 free (rsrc_sizes);
4288 }
4289
4290 /* Handle the .idata section and other things that need symbol table
4291 access. */
4292
4293 bfd_boolean
_bfd_XXi_final_link_postscript(bfd * abfd,struct coff_final_link_info * pfinfo)4294 _bfd_XXi_final_link_postscript (bfd * abfd, struct coff_final_link_info *pfinfo)
4295 {
4296 struct coff_link_hash_entry *h1;
4297 struct bfd_link_info *info = pfinfo->info;
4298 bfd_boolean result = TRUE;
4299
4300 /* There are a few fields that need to be filled in now while we
4301 have symbol table access.
4302
4303 The .idata subsections aren't directly available as sections, but
4304 they are in the symbol table, so get them from there. */
4305
4306 /* The import directory. This is the address of .idata$2, with size
4307 of .idata$2 + .idata$3. */
4308 h1 = coff_link_hash_lookup (coff_hash_table (info),
4309 ".idata$2", FALSE, FALSE, TRUE);
4310 if (h1 != NULL)
4311 {
4312 /* PR ld/2729: We cannot rely upon all the output sections having been
4313 created properly, so check before referencing them. Issue a warning
4314 message for any sections tht could not be found. */
4315 if ((h1->root.type == bfd_link_hash_defined
4316 || h1->root.type == bfd_link_hash_defweak)
4317 && h1->root.u.def.section != NULL
4318 && h1->root.u.def.section->output_section != NULL)
4319 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress =
4320 (h1->root.u.def.value
4321 + h1->root.u.def.section->output_section->vma
4322 + h1->root.u.def.section->output_offset);
4323 else
4324 {
4325 _bfd_error_handler
4326 (_("%B: unable to fill in DataDictionary[1] because .idata$2 is missing"),
4327 abfd);
4328 result = FALSE;
4329 }
4330
4331 h1 = coff_link_hash_lookup (coff_hash_table (info),
4332 ".idata$4", FALSE, FALSE, TRUE);
4333 if (h1 != NULL
4334 && (h1->root.type == bfd_link_hash_defined
4335 || h1->root.type == bfd_link_hash_defweak)
4336 && h1->root.u.def.section != NULL
4337 && h1->root.u.def.section->output_section != NULL)
4338 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].Size =
4339 ((h1->root.u.def.value
4340 + h1->root.u.def.section->output_section->vma
4341 + h1->root.u.def.section->output_offset)
4342 - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_TABLE].VirtualAddress);
4343 else
4344 {
4345 _bfd_error_handler
4346 (_("%B: unable to fill in DataDictionary[1] because .idata$4 is missing"),
4347 abfd);
4348 result = FALSE;
4349 }
4350
4351 /* The import address table. This is the size/address of
4352 .idata$5. */
4353 h1 = coff_link_hash_lookup (coff_hash_table (info),
4354 ".idata$5", FALSE, FALSE, TRUE);
4355 if (h1 != NULL
4356 && (h1->root.type == bfd_link_hash_defined
4357 || h1->root.type == bfd_link_hash_defweak)
4358 && h1->root.u.def.section != NULL
4359 && h1->root.u.def.section->output_section != NULL)
4360 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
4361 (h1->root.u.def.value
4362 + h1->root.u.def.section->output_section->vma
4363 + h1->root.u.def.section->output_offset);
4364 else
4365 {
4366 _bfd_error_handler
4367 (_("%B: unable to fill in DataDictionary[12] because .idata$5 is missing"),
4368 abfd);
4369 result = FALSE;
4370 }
4371
4372 h1 = coff_link_hash_lookup (coff_hash_table (info),
4373 ".idata$6", FALSE, FALSE, TRUE);
4374 if (h1 != NULL
4375 && (h1->root.type == bfd_link_hash_defined
4376 || h1->root.type == bfd_link_hash_defweak)
4377 && h1->root.u.def.section != NULL
4378 && h1->root.u.def.section->output_section != NULL)
4379 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
4380 ((h1->root.u.def.value
4381 + h1->root.u.def.section->output_section->vma
4382 + h1->root.u.def.section->output_offset)
4383 - pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress);
4384 else
4385 {
4386 _bfd_error_handler
4387 (_("%B: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE (12)] because .idata$6 is missing"),
4388 abfd);
4389 result = FALSE;
4390 }
4391 }
4392 else
4393 {
4394 h1 = coff_link_hash_lookup (coff_hash_table (info),
4395 "__IAT_start__", FALSE, FALSE, TRUE);
4396 if (h1 != NULL
4397 && (h1->root.type == bfd_link_hash_defined
4398 || h1->root.type == bfd_link_hash_defweak)
4399 && h1->root.u.def.section != NULL
4400 && h1->root.u.def.section->output_section != NULL)
4401 {
4402 bfd_vma iat_va;
4403
4404 iat_va =
4405 (h1->root.u.def.value
4406 + h1->root.u.def.section->output_section->vma
4407 + h1->root.u.def.section->output_offset);
4408
4409 h1 = coff_link_hash_lookup (coff_hash_table (info),
4410 "__IAT_end__", FALSE, FALSE, TRUE);
4411 if (h1 != NULL
4412 && (h1->root.type == bfd_link_hash_defined
4413 || h1->root.type == bfd_link_hash_defweak)
4414 && h1->root.u.def.section != NULL
4415 && h1->root.u.def.section->output_section != NULL)
4416 {
4417 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size =
4418 ((h1->root.u.def.value
4419 + h1->root.u.def.section->output_section->vma
4420 + h1->root.u.def.section->output_offset)
4421 - iat_va);
4422 if (pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].Size != 0)
4423 pe_data (abfd)->pe_opthdr.DataDirectory[PE_IMPORT_ADDRESS_TABLE].VirtualAddress =
4424 iat_va - pe_data (abfd)->pe_opthdr.ImageBase;
4425 }
4426 else
4427 {
4428 _bfd_error_handler
4429 (_("%B: unable to fill in DataDictionary[PE_IMPORT_ADDRESS_TABLE(12)]"
4430 " because .idata$6 is missing"), abfd);
4431 result = FALSE;
4432 }
4433 }
4434 }
4435
4436 h1 = coff_link_hash_lookup (coff_hash_table (info),
4437 (bfd_get_symbol_leading_char (abfd) != 0
4438 ? "__tls_used" : "_tls_used"),
4439 FALSE, FALSE, TRUE);
4440 if (h1 != NULL)
4441 {
4442 if ((h1->root.type == bfd_link_hash_defined
4443 || h1->root.type == bfd_link_hash_defweak)
4444 && h1->root.u.def.section != NULL
4445 && h1->root.u.def.section->output_section != NULL)
4446 pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].VirtualAddress =
4447 (h1->root.u.def.value
4448 + h1->root.u.def.section->output_section->vma
4449 + h1->root.u.def.section->output_offset
4450 - pe_data (abfd)->pe_opthdr.ImageBase);
4451 else
4452 {
4453 _bfd_error_handler
4454 (_("%B: unable to fill in DataDictionary[9] because __tls_used is missing"),
4455 abfd);
4456 result = FALSE;
4457 }
4458 /* According to PECOFF sepcifications by Microsoft version 8.2
4459 the TLS data directory consists of 4 pointers, followed
4460 by two 4-byte integer. This implies that the total size
4461 is different for 32-bit and 64-bit executables. */
4462 #if !defined(COFF_WITH_pep) && !defined(COFF_WITH_pex64)
4463 pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x18;
4464 #else
4465 pe_data (abfd)->pe_opthdr.DataDirectory[PE_TLS_TABLE].Size = 0x28;
4466 #endif
4467 }
4468
4469 /* If there is a .pdata section and we have linked pdata finally, we
4470 need to sort the entries ascending. */
4471 #if !defined(COFF_WITH_pep) && defined(COFF_WITH_pex64)
4472 {
4473 asection *sec = bfd_get_section_by_name (abfd, ".pdata");
4474
4475 if (sec)
4476 {
4477 bfd_size_type x = sec->rawsize;
4478 bfd_byte *tmp_data = NULL;
4479
4480 if (x)
4481 tmp_data = bfd_malloc (x);
4482
4483 if (tmp_data != NULL)
4484 {
4485 if (bfd_get_section_contents (abfd, sec, tmp_data, 0, x))
4486 {
4487 qsort (tmp_data,
4488 (size_t) (x / 12),
4489 12, sort_x64_pdata);
4490 bfd_set_section_contents (pfinfo->output_bfd, sec,
4491 tmp_data, 0, x);
4492 }
4493 free (tmp_data);
4494 }
4495 }
4496 }
4497 #endif
4498
4499 rsrc_process_section (abfd, pfinfo);
4500
4501 /* If we couldn't find idata$2, we either have an excessively
4502 trivial program or are in DEEP trouble; we have to assume trivial
4503 program.... */
4504 return result;
4505 }
4506